liveBook · Manning

Authentication

As explained in Spring in Action, Sixth Edition

Authentication is a Spring Security object that represents an authentication request or the resulting authenticated identity and authorities.

Authentication represents the current security identity in a Spring application. After login, it gives application code access to the authenticated principal, such as the User who placed an order. section 5.5

Use several supported paths to obtain the authenticated user:

  • Inject Authentication into a controller method and call getPrincipal(), casting the result to User. section 5.5
  • Retrieve Authentication from SecurityContextHolder when direct controller injection is unsuitable. section 5.5
  • Prefer @AuthenticationPrincipal when a controller needs the User directly, avoiding a cast and keeping security-specific code in the annotation. section 5.5

Associating an order with its authenticated user

A Taco Cloud order can store its User relationship. The order-processing method receives the authenticated User with @AuthenticationPrincipal, assigns it to the order, saves the order, and redirects to the home page. section 5.5

@PostMapping
public String processOrder(@Valid TacoOrder order, Errors errors, 
    SessionStatus sessionStatus, 
    @AuthenticationPrincipal User user) {
  
  if (errors.hasErrors()) {
    return "orderForm";
  }
  
  order.setUser(user);
  
  orderRepo.save(order);
  sessionStatus.setComplete();
  
  return "redirect:/";
}

Shows the recommended controller signature and the complete flow from authenticated User to saved TacoOrder. section 5.5

Adding the Spring Security starter enables authentication for every HTTP request by default, supplies a plain login page, and creates one user with a generated password written to the application log. section 5.1

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains controller access patterns and principal retrieval, but stops short of authentication-provider or protocol internals.
Examples
Demonstrates TacoOrder persistence, controller method parameters, generated login credentials, and Spring Security’s plain login page.
What it assumes
Assumes a Spring application with Spring Security and a User model, while demonstrating principal access from basic controller code.
What you can do after
Apply it via Spring Security controller injection to retrieve the current User and attach that identity to domain data.
How it connects
Connects Authentication with Principal, SecurityContextHolder, @AuthenticationPrincipal, UserRepository, and authenticated User.

Also explained in

Compare how 34 books explain authentication →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.