...
Configuración de MvcMatchers
La primera forma de configuración es añadir un mvcMatcher en el método configure de nuestra clase "SecurityConfig".
Se añade el mvcMatcher que capture la/s rutas/s a securizar con nuestro nuevo scope (antes del mvcMatcher configurado por defecto para private-apiPath) y se le añade .hasAuthority("SCOPE_miotroscope").
Ejemplo:
| Bloque de código | ||||||
|---|---|---|---|---|---|---|
| ||||||
@Override
protected void configure( HttpSecurity http ) throws Exception {
http.requestMatchers().antMatchers( "/public/**" ).and().requestMatchers().antMatchers( apiPath + "/**" ).and()
.sessionManagement().sessionCreationPolicy( SessionCreationPolicy.STATELESS )
.and().cors()
.and().csrf().disable().authorizeRequests()
.mvcMatchers( "/public/**" ).permitAll()
.mvcMatchers( apiPath + "**/mirecurso/misubrecursoconotroscope/**" ).hasAuthority( "SCOPE_miotrorecurso" )
.mvcMatchers( apiPath + "/**" ).hasAnyAuthority( serverScopes ).anyRequest().authenticated()
.and().addFilterAfter( loggingFilterBean(), BearerTokenAuthenticationFilter.class )
.oauth2ResourceServer().jwt();
} |
-- Respuesta de error --
Cuando llega una petición al endpoint securizado de esta forma con un token que no incluye el scope configurado, la librería spring-security-oauth2-resource-server toma el control y devuelve la respuesta de la siguiente forma:
- Status Code: 403 Forbbiden
- Body: VACIO
- Cabecera WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token.", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
| Advertencia |
|---|
!!OJO¡¡ Como la librería spring-security-oauth2-resource-server toma el control del error, cualquier otro manejo de la excepción configurado según Manejo de Errores en FundeWebJS NO TENDRÁ EFECTO. |
Para sobreescribir el comportamiento de la respuesta de error habrá que crear una clase AccessDeniedExceptionHandler propia y configurarla en el mismo método configure de nuesta clase "SecurityConfig" añadiendo el exceptionHandling de esta forma:
| Bloque de código | ||||
|---|---|---|---|---|
| ||||
...
.mvcMatchers( apiPath + "**/mirecurso/misubrecursoconotroscope/**" ).hasAuthority( "SCOPE_miotrorecurso" )
.mvcMatchers( apiPath + "/**" ).hasAnyAuthority( serverScopes ).anyRequest().authenticated()
.and().exceptionHandling().accessDeniedHandler( new MiOtroAccessDeniedHandler())
.and().addFilterAfter( loggingFilterBean(), BearerTokenAuthenticationFilter.class )
.oauth2ResourceServer().jwt()
... |
| Info |
|---|
Tomar de ejemplo la clase BearerTokenAccessDeniedHandler (handler por defecto de spring-security-oauth2-resource-server) para crear nuestra clase AccessDeniedExceptionHandler propia. |
| Info |
|---|
Artículos Relacionados
...