Cómo configurar el servidor de recursos en Spring Security para que use información adicional en el token JWT
Tengo un servidor de token oauth2 jwt configurado para configurar información adicional sobre las autoridades del usuario.
@Configuration
@Component
public class CustomTokenEnhancer extends JwtAccessTokenConverter {
CustomTokenEnhancer(){
super();
}
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
// TODO Auto-generated method stub
MyUserDetails user = (MyUserDetails) authentication.getPrincipal();
final Map<String, Object> additionalInfo = new HashMap<>();
@SuppressWarnings("unchecked")
List<GrantedAuthority> authorities= (List<GrantedAuthority>) user.getAuthorities();
additionalInfo.put("authorities", authorities);
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
No estoy seguro de cómo configurar mi servidor de recursos para extraer las autorizaciones de usuario establecidas por el servidor oauth2 y utilizar esa autorización para usar en controladores anotados @Secured en el marco de Spring Security.
La configuración de mi servidor de autenticación se ve así:
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Value("${config.oauth2.privateKey}")
private String privateKey;
@Value("${config.oauth2.publicKey}")
private String publicKey;
@Value("{config.clienturl}")
private String clientUrl;
@Autowired
AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter customTokenEnhancer(){
JwtAccessTokenConverter customTokenEnhancer = new CustomTokenEnhancer();
customTokenEnhancer.setSigningKey(privateKey);
return customTokenEnhancer;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(customTokenEnhancer());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("isAnonymous() || hasRole('ROLE_TRUSTED_CLIENT')") // permitAll()
.checkTokenAccess("hasRole('TRUSTED_CLIENT')"); // isAuthenticated()
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(customTokenEnhancer())
;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
String url = clientUrl;
clients.inMemory()
.withClient("public")
.authorizedGrantTypes("client_credentials", "implicit")
.scopes("read")
.redirectUris(url)
.and()
.withClient("eagree_web").secret("eagree_web_dev")
//eagree_web should come from properties file?
.authorities("ROLE_TRUSTED_CLIENT")
.authorizedGrantTypes("client_credentials", "password", "authorization_code", "refresh_token")
.scopes("read", "write", "trust")
.redirectUris(url).resourceIds("dummy");
}
}
Y mi configuración del servidor de recursos se ve así:
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Value("{config.oauth2.publicKey}")
private String publicKey;
@Autowired
CustomTokenEnhancer tokenConverter;
@Autowired
JwtTokenStore jwtTokenStore;
@Bean
public JwtTokenStore jwtTokenStore() {
tokenConverter.setVerifierKey(publicKey);
jwtTokenStore.setTokenEnhancer(tokenConverter);
return jwtTokenStore;
}
@Bean
public ResourceServerTokenServices defaultTokenServices() {
final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenEnhancer(tokenConverter);
defaultTokenServices.setTokenStore(jwtTokenStore());
return defaultTokenServices;
}
@Override
public void configure(HttpSecurity http) throws Exception {
super.configure(http);
// @formatter:off
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.requestMatchers()
.antMatchers("/**")
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll()
.antMatchers(HttpMethod.GET, "/api/**").access("#oauth2.hasScope('read')")
.antMatchers(HttpMethod.PATCH, "/api/**").access("#oauth2.hasScope('write')")
.antMatchers(HttpMethod.POST, "/api/**").access("#oauth2.hasScope('write')")
.antMatchers(HttpMethod.PUT, "/api/**").access("#oauth2.hasScope('write')")
.antMatchers(HttpMethod.DELETE, "/api/**").access("#oauth2.hasScope('write')")
.antMatchers("/admin/**").access("hasRole('ROLE_USER')");
// @formatter:on
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
System.out.println("Configuring ResourceServerSecurityConfigurer ");
resources.resourceId("dummy").tokenServices(defaultTokenServices());
}
}
Mi caso de prueba falla miserablemente diciendo:
{"error": "invalid_token", "error_description": "No se puede convertir el token de acceso a JSON"}
¿Cómo obtengo el objeto de autenticación del JWT? ¿Cómo autentico al cliente con credenciales de cliente? ¿Cómo uso la anotación @Secured en mis controladores de recursos?
¿Qué código se usa en el lado del servidor de recursos para decodificar el token con el fin de extraer las credenciales del cliente y qué código llega al rol de usuario verificado?
Por favor, ayuda, ya que pasé 2 días golpeándome la cabeza en esta tarea aparentemente fácil.
Nota: recibo el token del servidor Auth como: {access_token = b5d89a13-3c8b-4bda-b0f2-a6e9d7b7a285, token_type = bearer, refresh_token = 43777224-b6f2-44d7-bf36-4e1934d32cbb, expires, = = 43 autoridades = [{autoridad = ROLE_USER}, {autoridad = ROLE_ADMIN}]}
Explique los conceptos y señale si falta algo en mi configuración. Necesito conocer las mejores prácticas en la configuración de mi recurso y servidor de autenticación, por favor.