liveBook · Manning

hasRole()

As explained in Spring Security in Action, Second Edition

hasRole() is an authorization configuration method that permits access when the user has a specified role.

hasRole() restricts requests to users holding a specified role. Roles are coarse-grained permissions represented internally as GrantedAuthority values. section 7.1.2

Declare roles with the ROLE_ prefix, but pass only the role name to hasRole(). Use hasRole() or hasAnyRole() before falling back to access(). section 7.1.2

Allow administrators only

Configure any request with c -> c.anyRequest().hasRole("ADMIN"). A user with the ADMIN role reaches /hello; a MANAGER receives HTTP 403 Forbidden.

Figure 7.5 Roles are coarse grained. Each user with a specific role can only do the actions granted by that role. When applying this philosophy in authorization, a request is allowed based on the purpose of the user in the system. Only users who have a specific role can call a certain endpoint.

Use the role model when endpoint permissions follow a user's coarse-grained purpose in the system. section 7.1.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains declaration, configuration, prefix handling, and 403 testing, but defers custom AuthorizationManager details.
Examples
Demonstrates ADMIN and MANAGER users, an admin-only endpoint, curl requests, and an HTTP 403 response.
What you can do after
Configure endpoint authorization with hasRole() and verify permitted and forbidden requests.
How it connects
Connects roles with authorities, GrantedAuthority, hasAnyRole(), access(), and AuthorizationManager.

Also explained in

Compare how 2 books explain hasRole() →

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.