1.Get the User in a Bean

The simplest way to retrieve the currently authenticated principal is via a static call to the SecurityContextHolder:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String currentPrincipalName = authentication.getName();

An improvement to this snippet is first checking if there is an authenticated user before trying to access it:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
    String currentUserName = authentication.getName();
    return currentUserName;
}

2. Get the User in a Controller

We have additional options in a @Controller annotated bean.

We can define the principal directly as a method argument, and it will be correctly resolved by the framework:

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Principal principal) {
        return principal.getName();
    }
}

Alternatively, we can also use the authentication token:

@Controller
public class SecurityController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserName(Authentication authentication) {
        return authentication.getName();
    }
}

The API of the Authentication class is very open so that the framework remains as flexible as possible. Because of this, the Spring Security principal can only be retrieved as an Object and needs to be cast to the correct UserDetails instance:

UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("User has authorities: " + userDetails.getAuthorities());

Also, here's directly from the HTTP request:

@Controller
public class GetUserWithHTTPServletRequestController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserNameSimple(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        return principal.getName();
    }
}

Finally, we can use the @AuthenticationPrincipal annotation to get the currently authenticated user details:

@RestController
public class SecurityController {
    
    @GetMapping("/user")
    public String getUser(@AuthenticationPrincipal UserDetails userDetails) {
        return "User Details: " + userDetails.getUsername();
    }
}

Here, the @AuthenticationPrincipal annotation injects the currently authenticated user's UserDetails into the method. This annotation helps resolve Authentication.getPrincipal() to a method argument.

Additionally, when we annotate a method parameter with @AuthenticationPrincipal, Spring Security automatically provides the principal of the currently authenticated user. The principal represents the user's identity, which can be the username, a user object, or any form of user identification.

3.Get the User via a Custom Interface

To fully leverage the Spring dependency injection and be able to retrieve the authentication everywhere, not just in @Controller beans, we need to hide the static access behind a simple facade:

public interface IAuthenticationFacade {
    Authentication getAuthentication();
}
@Component
public class AuthenticationFacade implements IAuthenticationFacade {

    @Override
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}

The facade exposes the Authentication object while hiding the static state and keeping the code decoupled and fully testable:

@Controller
public class GetUserWithCustomInterfaceController {
    @Autowired
    private IAuthenticationFacade authenticationFacade;

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody
    public String currentUserNameSimple() {
        Authentication authentication = authenticationFacade.getAuthentication();
        return authentication.getName();
    }
}

4.Get the User in JSP

The currently authenticated principal can also be accessed in JSP pages, by leveraging the Spring Security Taglib support.

First, we need to define the tag in the page:

<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

Next, we can refer to the principal:

<security:authorize access="isAuthenticated()">
    authenticated as <security:authentication property="principal.username" /> 
</security:authorize>

6.Get the User in Thymeleaf

Thymeleaf is a modern, server-side web templating engine, with good integration with the Spring MVC framework.

Let's see how to access the currently authenticated principal in a page with Thymeleaf engine.

First, we need to add the thymeleaf-spring5 and the thymeleaf-extras-springsecurity5 dependencies to integrate Thymeleaf with Spring Security:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>

Now we can refer to the principal in the HTML page using the sec:authorize attribute:

<html xmlns:th="https://www.thymeleaf.org" 
  xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
    <div sec:authorize="isAuthenticated()">
      Authenticated as <span sec:authentication="name"></span></div>
</body>
</html>
https://www.baeldung.com/get-user-in-spring-security

标签: none

添加新评论