liveBook · Manning

Roles()

As explained in Spring Security in Action, Second Edition

roles() is a Spring Security User builder method that creates role authorities and adds the ROLE_ prefix to supplied role names.

roles() is a User builder method for assigning roles. It creates GrantedAuthority objects and automatically adds the ROLE_ prefix to each supplied name. section 7.1.2

Assigning roles to users

Use roles("ADMIN") and roles("MANAGER"), not names containing ROLE_. Then hasRole("ADMIN") allows John to access the endpoint while Jane 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.

Roles provide coarse-grained authorization: each role grants access to the actions associated with a user's purpose. section 7.1.2

How Spring Security in Action, Second Edition covers it

How deep it goes
Explains authority creation, automatic prefixing, correct parameters, and the exception caused by supplying ROLE_.
Examples
Uses in-memory John and Jane users, ADMIN and MANAGER roles, curl requests, and a 403 response.
What you can do after
Build role-based users from scratch with the User builder and apply their roles to endpoint authorization.
How it connects
Connects User builder roles to GrantedAuthority, authorities(), and hasRole().

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.