I am using oauth2, and I have an authorization server and a (separate) resource server. A client gets a token from the authorization server and then uses the token to make requests to the resource server. When the resource server fetches the SecurityContext from the authorization server, I would like to add additional info. At the moment it gets the username of the user and I would like to add the user ID too. In the authorization server I have the following setup:
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//... more logic in here
return new CurrentUser(user.getId(), user.getUsername(), user.getPassword(), true, true, true, true, grantedAuthorities);
}
where CurrentUser is defined as follows:
public class CurrentUser extends org.springframework.security.core.userdetails.User {
private Long userId;
public CurrentUser(Long userId, String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userId = userId;
}
}
In the resource server Im trying to cast the principal to CurrentUser but the principal is just a String. Looks like it is not being sent. Do you have an idea what am I missing?
Authentication a = SecurityContextHolder.getContext().getAuthentication();
CurrentUser user = (CurrentUser)a.getPrincipal(); //throws exception
The resource server (a separate application) is configured as follows:
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter
{
private static final String RESOURCE_ID = "my_id";
@Override
public void configure(ResourceServerSecurityConfigurer resources)
{
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("...").access("...")
.and()
.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
In the properties file of the resource server I have the necessary information where to validate the token:
security.oauth2.resource.token-info-uri=http://localhost:8000/auth-service/oauth/check_token
security.oauth2.client.client-id = my-client
security.oauth2.client.client-secret = password