liveBook · Manning

hasRole()

As explained in Spring AI in Action

hasRole() is a Spring Security expression function that tests whether the current security context contains a specified role.

hasRole() is a Spring Security extension to SpEL that tests whether the active security context contains a specified role. Used inside @PreAuthorize, it permits a method call when the expression returns true and blocks it with AccessDeniedException when false. section 10.2

A tool such as getGameComplexity can require the PREMIUM_USER role by placing @PreAuthorize("hasRole('PREMIUM_USER')") on the @Tool method or on a Function implementation’s apply() method. Method security must be enabled with @EnableMethodSecurity. section 10.2

Role-gated game information

A premium user receives the game’s complexity, while an unauthorized user receives “That information is reserved for premium users.” The security check prevents the protected method from being invoked.

How Spring AI in Action covers it

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 it assumes
Requires Spring Security method security, SpEL expressions, and a security context containing roles.
What you can do after
Apply role-based access control to Spring methods and tools with @PreAuthorize expressions.
How it connects
Connects Spring Security, SpEL, @PreAuthorize, method-level security, roles, and AccessDeniedException.

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 AI in Action. The section links point to the parts of the book it draws on.