liveBook · Manning

hasAnyRole()

As explained in Spring Security in Action, Second Edition

hasAnyRole() is an authorization configuration method that permits access when the user has at least one role from a specified set.

hasAnyRole() restricts an endpoint to users holding at least one role from a specified set. It provides a coarse-grained alternative to authority-based checks. section 7.1.2

Use role checks as follows:

  • Pass the permitted role names to hasAnyRole(); a request succeeds when the user has one of them. section 7.1.2
  • Declare roles with the ROLE_ prefix, but use the role name without that prefix in the authorization method. section 7.1.2
  • Prefer hasAnyRole() or hasRole() before falling back to access() with an AuthorizationManager. section 7.1.2

Role-based endpoint access

Configure an endpoint with hasAnyRole("ADMIN", "MANAGER") when either role should be allowed. Users with neither role receive HTTP 403 Forbidden. User builders can create these roles with roles("ADMIN") and roles("MANAGER"), which adds ROLE_ automatically. section 7.1.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Defines role selection, prefix handling, alternatives, and HTTP 403 testing, but does not detail AuthorizationManager internals.
Examples
Uses ADMIN and MANAGER users, endpoint requests, HTTP Basic credentials, successful responses, and HTTP 403 Forbidden responses.
What it assumes
Assumes basic Spring Security configuration and distinguishes roles from authorities through the GrantedAuthority contract.
What you can do after
Apply role-based endpoint authorization and interpret denied requests as HTTP 403 Forbidden.
How it connects
Connects roles with authorities, GrantedAuthority, hasRole(), access(), AuthorizationManager, and WebExpressionAuthorizationManager.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.