Current Logged in User in Spring Security

Current Logged in User in Spring Security

In Spring Security, retrieving the details of the currently logged in user is a common task. These details are often needed for various purposes, such as auditing, personalizing content, or securing resources based on user roles.

Logged in User

Spring Security provides several ways to access the details of the authenticated user:

1. SecurityContextHolder:

This is the main approach. Spring Security stores the details of the authenticated user in the `SecurityContext`, which can be accessed through the `SecurityContextHolder` class.

2. Principal Object

Another way is to access the `Principal` object directly from the method parameter in a controller.

3. Authentication Object

You can also directly access the `Authentication` object, which contains information about the user’s identity.

Java Example

Here’s an example of how to get the current logged-in user details in a Spring Boot application using Spring Security.

Example

```java
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @GetMapping("/current")
    public String getCurrentUser() {
        // Get the authentication object from the security context
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // If the authentication is valid and has user details, return the username
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return "Current Logged-in User: " + userDetails.getUsername();
        } else {
            // If authentication is not valid, return an anonymous user message
            return "Anonymous User";
        }
    }
}
```

Explanation of the Code Logged in User

  1. SecurityContextHolder: We retrieve the Authentication object from the SecurityContextHolder. This object holds the user’s authentication information.
  2. Authentication Object: The Authentication object has a method getPrincipal() that returns the currently logged-in user’s details.
  3. UserDetails: If the getPrincipal() method returns an instance of UserDetails, it means a user is authenticated, and we can extract the username or other details from it.
  4. Controller: The controller has an endpoint (/api/user/current) that returns the username of the currently logged-in user.

Homepage

Readmore