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

































