Versiones comparadas

Clave

  • Se ha añadido esta línea.
  • Se ha eliminado esta línea.
  • El formato se ha cambiado.

...

El primer paso para validar scopes diferentes en FundeWebJS es añadirlos a la property server.scopes del application.properties. Esta property ya está configurado para el scope "micampus".
Para añadir un scope nuevo, hay que ponerlo a continuación del existente separado por comas y con el prefijo "SCOPE_".

Por ejemplo

Bloque de código
themeEclipse
titleapplication.properties
#Valida los scopes 'micampus' y 'miotroscope'
server.scopes=SCOPE_micampus,SCOPE_miotroscope

...

Con la configuración del punto 1 se configura TODA la aplicación para permitir tokens que contengan cualquiera de los scopes configurados.
Esto significa que un token obtenido desde micampus por cualquier usuario sería válido para acceder a cualquier endpoint.
Si hemos tenido que configurar varios scopes, lo normal es que está situación sea no deseada (no queremos que cualquier token sirva para acceder a endpoints que requieran un nivel diferente de acceso).

En este paso se explica cómo configurar nuestra aplicación para securizar diferentes endpoints con scopes distintos.
Existen dos alternativas:

...

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 ForbbidenForbidden
  • 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"

...

Info

Tomar de ejemplo la clase BearerTokenAccessDeniedHandler (handler por defecto de spring-security-oauth2-resource-server) para crear nuestra clase AccessDeniedExceptionHandler propia.


Configuración con PreAuthorize


La segunda forma para configurar endpoints para ser 










3. Buenas prácticas

Como se ha mencionado en los apartados de respuesta de error, los mecanismos estándar de manejo de excepciones de spring-security y spring-security-oauth2-resource-server devuelven siempre un 403 Forbidden, con body vacío y con la cabecera WWW-Authenticate informando del error "insufficient_scope".

Esta configuración se puede sobreescribir pero, siguiendo el RFC de Oauth se recomienda mantener el 403 Forbidden y la cabecera con "insufficient_scope" => "The resource server SHOULD respond with the HTTP 403 (Forbidden) status code and MAY include the "scope" attribute with the scope necessary to access the protected resource".

...

Bloque de código
languagetext
themeConfluence
titleRFC Oauth - Error Codes
collapsetrue
3.1.  Error Codes

   When a request fails, the resource server responds using the
   appropriate HTTP status code (typically, 400, 401, 403, or 405) and
   includes one of the following error codes in the response:

   invalid_request
         The request is missing a required parameter, includes an
         unsupported parameter or parameter value, repeats the same
         parameter, uses more than one method for including an access
         token, or is otherwise malformed.  The resource server SHOULD
         respond with the HTTP 400 (Bad Request) status code.

   invalid_token
         The access token provided is expired, revoked, malformed, or
         invalid for other reasons.  The resource SHOULD respond with
         the HTTP 401 (Unauthorized) status code.  The client MAY
         request a new access token and retry the protected resource
         request.

   insufficient_scope
         The request requires higher privileges than provided by the
         access token.  The resource server SHOULD respond with the HTTP
         403 (Forbidden) status code and MAY include the "scope"
         attribute with the scope necessary to access the protected
         resource.

   If the request lacks any authentication information (e.g., the client
   was unaware that authentication is necessary or attempted using an
   unsupported authentication method), the resource server SHOULD NOT
   include an error code or other error information.

   For example:

     HTTP/1.1 401 Unauthorized
     WWW-Authenticate: Bearer realm="example"


Referencias

https://www.baeldung.com/spring-security-method-security

...

Artículos Relacionados

Contenido por etiqueta
showLabelsfalse
max5
spaces~ramon.ginel@ticarum.es
showSpacefalse
sortmodified
reversetrue
typepage
cqllabel in ("oauth2","fundewebjs","authorization_code_pkcs","spring-boot","scopes","client_credentials","autorización") and type = "page" and space = "~ramon.ginel@ticarum.es"
labelsspring-boot fundewebjs autorización scopes oauth2 client_credentials authorization_code_pkcs

...

hiddentrue

...