Retrieve User Information in Spring Security – 在Spring Security中检索用户信息

最后修改: 2013年 7月 16日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This tutorial will show how to retrieve the user details in Spring Security.

本教程将展示如何在Spring Security中检索用户详情。

The currently authenticated user is available through a number of different mechanisms in Spring. Let’s cover the most common solution first — programmatic access.

在Spring中,当前认证的用户可以通过一些不同的机制获得。我们先来介绍一下最常见的解决方案–程序化访问。

2. Get the User in a Bean

2.在一个Bean中获取用户

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

检索当前认证的委托人的最简单方法是通过静态调用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;
}

There are of course downsides to having a static call like this, and decreased testability of the code is one of the more obvious. Instead, we’ll explore alternative solutions for this very common requirement.

当然,像这样的静态调用也有缺点,代码的可测试性下降就是其中一个比较明显的缺点。相反,我们将探讨这个非常普遍的需求的替代解决方案。

3. Get the User in a Controller

3.在控制器中获取用户

We have additional options in a @Controller annotated bean.

@Controller注解的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:

Authentication类的API是非常开放的,以便框架尽可能地保持灵活性。正因为如此,Spring Security principal只能以Object的形式被检索,并且需要被转换为正确的UserDetails实例

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

And finally, here’s directly from the HTTP request:

最后,这里是直接来自HTTP请求的

@Controller
public class GetUserWithHTTPServletRequestController {

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

4. Get the User via a Custom Interface

4.通过自定义界面获取用户

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:

为了充分利用Spring的依赖注入,并且能够在任何地方检索认证,而不仅仅是在@Controller Bean中,我们需要将静态访问隐藏在一个简单的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:

Facade暴露了Authentication对象,同时隐藏了静态状态,并保持代码解耦和完全可测试。

@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();
    }
}

5. Get the User in JSP

5.在JSP中获取用户

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

通过利用Spring Security Taglib支持,当前认证的委托人也可以在JSP页面中访问

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

6.在Thymeleaf中获取用户

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

Thymeleaf是一个现代的服务器端Web模板引擎,具有良好的与Spring MVC框架的集成性。

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

让我们看看如何用Thymeleaf引擎在一个页面中访问当前认证的校长。

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

首先,我们需要添加thymeleaf-spring5thymeleaf-extras-springsecurity5依赖项,以便将Thymeleaf与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页面中使用sec:authorize属性来引用委托人

<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>

7. Conclusion

7.结论

This article showed how to get the user information in a Spring application, starting with the common static access mechanism, followed by several better ways to inject the principal.

这篇文章展示了如何在Spring应用程序中获取用户信息,首先是常见的静态访问机制,然后是几种更好的注入本金的方法。

The implementation of these examples can be found in the GitHub project. This is an Eclipse-based project, so it should be easy to import and run as it is. When running the project locally, we can access the homepage HTML here:

这些示例的实现可以在GitHub项目中找到。这是一个基于 Eclipse 的项目,因此应该很容易导入并按原样运行。在本地运行该项目时,我们可以在这里访问主页的HTML。

http://localhost:8080/spring-security-rest-custom/foos/1