hasRole()
hasRole() is a Spring Security authorization expression that tests whether the current user has a specified role or authority.
Spring Security in Action, Second Edition
hasRole() is an authorization configuration method that permits access when the user has a specified role.
- How it is used
- Restricts endpoint requests according to a user's named role.
- 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.
Read how Spring Security in Action, Second Edition explains hasRole() →
Spring AI in Action
hasRole() is a Spring Security expression function that tests whether the current security context contains a specified role.
- How it is used
- Restricts tool or method invocation to users whose security context contains a required role.
- How deep it goes
- Explains boolean evaluation, denial behavior, annotation placement, and method-security enablement without detailing role storage or expression internals.
- Examples
- Demonstrates PREMIUM_USER protection for a game-complexity tool and contrasts authorized and unauthorized HTTP requests.
- What you can do after
- Apply role-based access control to Spring methods and tools with @PreAuthorize expressions.
Related concepts
- roleuses · A role is a defined function, responsibility, perspective, or set of permissions associated with a participant in an organization or system.
- authorizationuses · Authorization is the determination and enforcement of rules governing which subjects may access resources or perform operations.
- security contextuses · A security context is security-related configuration or execution state associated with a subject, request, container, or runtime environment.
- hasAnyRole()alternative to · hasAnyRole() is an authorization configuration method that permits access when the user has at least one role from a specified set.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.

