OAuth2 con la aplicación Spring Boot REST: no se puede acceder a los recursos con token
Quiero usar OAuth2 para mi proyecto de arranque de primavera REST. Usando algunos ejemplos, he creado la configuración para OAuth2:
@Configuration
public class OAuth2Configuration {
private static final String RESOURCE_ID = "restservice";
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
// @formatter:off
resources
.resourceId(RESOURCE_ID);
// @formatter:on
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.anonymous().disable()
.authorizeRequests().anyRequest().authenticated();
// @formatter:on
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {
private TokenStore tokenStore = new InMemoryTokenStore();
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
// @formatter:off
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// @formatter:on
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients
.inMemory()
.withClient("clientapp")
.authorizedGrantTypes("password", "refresh_token", "trust")
.authorities("USER")
.scopes("read", "write")
.resourceIds(RESOURCE_ID)
.secret("clientsecret")
.accessTokenValiditySeconds(1200)
.refreshTokenValiditySeconds(3600);
// @formatter:on
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
}
Esta es mi clase de SecurityConfiguration:
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http
.authorizeRequests().antMatchers("/api/register").permitAll()
.and()
.authorizeRequests().antMatchers("/api/free").permitAll()
.and()
.authorizeRequests().antMatchers("/oauth/token").permitAll()
.and()
.authorizeRequests().antMatchers("/api/secured").hasRole("USER")
.and()
.authorizeRequests().anyRequest().authenticated();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Traté de verificar mi solicitud con 2 solicitudes simples:
@RequestMapping(value = "/api/secured", method = RequestMethod.GET)
public String checkSecured(){
return "Authorization is ok";
}
@RequestMapping(value = "/api/free", method = RequestMethod.GET)
public String checkFree(){
return "Free from authorization";
}
En primer lugar, verifiqué dos solicitudes:
/ api / free código devuelto 200 y la cadena "Libre de autorización"
/ api / asegurado devuelto {"marca de tiempo": 1487451065106, "estado": 403, "error": "Prohibido", "mensaje": "Acceso denegado", "ruta": "/ api / secure"}
Y parece que funcionan bien.
Luego obtuve access_token (usando credenciales de mi base de datos de usuarios)
/ oauth / token? grant_type = contraseña y nombre de usuario = emaila & contraseña = emailo
Respuesta:
{"access_token": "3344669f-c66c-4161-9516-d7e2f31a32e8", "token_type": "bearer", "refresh_token": "c71c17e4-45ba-458c-9d98-574de33d1859", "expires_in": "1199" :"leer escribir"}
Luego intenté enviar una solicitud (con el token que obtuve) para el recurso que requiere autenticación:
/ api / secure? access_token = 3344669f-c66c-4161-9516-d7e2f31a32e8
Aquí está la respuesta:
{"marca de tiempo": 1487451630224, "estado": 403, "error": "Prohibido", "mensaje": "Acceso denegado", "ruta": "/ api / secure"}
No puedo entender por qué se deniega el acceso. No estoy seguro de las configuraciones y parece que son incorrectas. Además, todavía no entiendo claramente las relaciones de los métodos.configurar (HttpSecurity http) en clase que se extiendeWebSecurityConfigurerAdapter y en otro que se extiendeResourceServerConfigurerAdapter. ¡Gracias por cualquier ayuda!