Search⌘ K
AI Features

Tapping Into User Context

Understand how to leverage Spring Security to access current user details and create user-specific shopping carts in a reactive Spring Boot application. Explore adding authentication context to templates and method parameters to support multi-user scenarios and secure user experiences.

An essential requirement of security management is that we have access to the current user’s details. Throughout this course, presuming we’ve followed the examples, the cart’s name has simply been My Cart.

Making the shopping cart user-specific

With the user login details, we can suddenly support a different cart for every user. The code below shows how to do just that:

Java
@GetMapping
Mono<Rendering> home(Authentication auth) { // 1
return Mono.just(Rendering.view("home.html")
.modelAttribute("items", this.inventoryService.getInventory())
.modelAttribute("cart", this.inventoryService.getCart(cartName(auth)) // 2
.defaultIfEmpty(new Cart(cartName(auth))))
.modelAttribute("auth", auth) // 3
.build());
}
Making the shopping cart user-specific

Here’s a breakdown of the code above:

  1. In line 2, we add Authentication as another parameter to the home() method so that Spring Security extracts it from the subscriber context.

  2. In line 5 ...