liveBook · Manning

@PreAuthorize

As explained in Spring AI in Action

@PreAuthorize is a Spring Security annotation that permits a method invocation only when its authorization expression evaluates to true.

@PreAuthorize restricts a method invocation until a Spring Expression Language (SpEL) expression evaluates to true. Enable method-level security with @EnableMethodSecurity, then place the annotation on secured bean methods. section 10.2

Authorization behavior follows the expression result:

  • A true expression permits the invocation. section 10.2
  • A false expression throws AccessDeniedException before the method runs. section 10.2

Restricting an AI tool

Annotate getGameComplexity with @PreAuthorize("hasRole('PREMIUM_USER')") to limit the tool to users holding the PREMIUM_USER role. The same annotation can secure apply() when the tool is implemented as a Function. section 10.2

@Tool(name = "getGameComplexity",
    description = "Returns a game's complexity/difficulty " +
        "given the game's title/name.")
@PreAuthorize("hasRole('PREMIUM_USER')")
public GameComplexityResponse getGameComplexity(
          @ToolParam(description="The title of the game")
          String gameTitle) {

  // ...

}

Shows method-security enablement and a role-protected @Tool declaration. section 10.2

How Spring AI in Action covers it

How deep it goes
Explains configuration, SpEL evaluation, role checking, and failure behavior, while deferring other method-security annotations.
Examples
Uses getGameComplexity, the PREMIUM_USER role, Function.apply(), and authorized or refused Burger Battle requests.
What it assumes
Assumes an existing Spring Security configuration and teaches method-security enablement plus role-based SpEL expressions.
What you can do after
Configure role-based method authorization for tools and prevent unauthorized invocations.
How it connects
Connects method-level security with Spring Security, SpEL, security contexts, roles, and tool calling.

Also explained in

Compare how 2 books explain @PreAuthorize →

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.