liveBook · Manning

Authorization

As explained in Spring AI in Action

Authorization is the determination of whether an authenticated subject has permission to perform a requested operation or access a resource.

Access control determines whether an authenticated user may retrieve a document, invoke a tool, or receive an answer. In a generative AI application, it prevents unauthorized access through retrieval-augmented generation and limits responses to information the user is permitted to see. section 10.0

A practical implementation marks restricted documents during ingestion, then combines Spring Security authentication with authorization checks. A document reader can inspect a filename convention such as -premium and store documentType=PREMIUM in every resulting chunk. Security configuration then authenticates users and supplies their granted roles for later decisions. section 10.1.1 section 10.1.2

Listing 10.1 Altering the document reader bean to handle premium content
@Bean
Function<Flux<Message<byte[]>>, Flux<Document>> documentReader() {
  return resourceFlux -> resourceFlux
      .map(message -> {
        var fileName = (String) message.getHeaders().get("file_name");    #1
        LOGGER.info("Reading document from file: {}", fileName);

        var fileBytes = message.getPayload();
        var document = new TikaDocumentReader(
            new ByteArrayResource(fileBytes))
            .get()
            .getFirst();
        if (isPremiumDocument(fileName)) {
          document.getMetadata().put("documentType", "PREMIUM");  #2
        }
        return document;
      })
      .subscribeOn(Schedulers.boundedElastic());
}

private boolean isPremiumDocument(String fileName) {     #3
  var baseFilename = fileName
      .substring(0, fileName.toString().lastIndexOf('.'));
  return baseFilename.endsWith("-premium");
}

Shows how document metadata is created during ingestion so vector searches can later distinguish premium content. section 10.1.1

Authorization can also guard tool methods directly. Enable method security and annotate a tool or service method with @PreAuthorize("hasRole('PREMIUM_USER')"). Spring Expression Language evaluates the expression; a true result permits invocation, while a false result raises AccessDeniedException before the method runs. section 10.2

Restricting game-complexity answers

A getGameComplexity tool requires the PREMIUM_USER role. Mickey, a premium user, receives “The complexity of Burger Battle is EASY.” Donald, a nonpremium user, receives “That information is reserved for premium users.” A matching system-prompt instruction makes the denied response explicit. 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) {

  // ...

}

Provides the direct method-level authorization pattern for securing a Spring AI tool with a premium-user role. section 10.2

How Spring AI in Action covers it

How deep it goes
Implements metadata filtering, HTTP Basic authentication, in-memory users, and method-level role checks while deferring broader expression details.
Examples
Uses premium game-rule metadata, secured game-complexity tools, and authenticated HTTP requests from premium and nonpremium users.
What it assumes
Assumes a Spring application and authenticated users while teaching document marking, security configuration, roles, and authorization checks.
What you can do after
Apply it via Spring Security to authenticate users, assign roles, filter premium content, and block unauthorized tool execution.
How it connects
Connects authentication, Spring Security, retrieval-augmented generation, vector stores, method-level security, Spring Expression Language, and tool invocation.

Also explained in

Compare how 28 books explain authorization →

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.