How to Manually Authenticate User with Spring Security – 如何用Spring Security手动认证用户

最后修改: 2018年 1月 26日

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

1. Overview

1.概述

In this quick article, we’ll focus on how to programmatically set an authenticated user in Spring Security and Spring MVC.

在这篇快速的文章中,我们将重点介绍如何在Spring Security和Spring MVC中以编程方式设置一个已认证的用户。

2. Spring Security

2.Spring安全

Simply put, Spring Security hold the principal information of each authenticated user in a ThreadLocal – represented as an Authentication object.

简单地说,Spring Security在ThreadLocal中持有每个认证用户的主要信息–表示为Authentication对象。

In order to construct and set this Authentication object – we need to use the same approach Spring Security typically uses to build the object on a standard authentication.

为了构建和设置这个Authentication对象–我们需要使用Spring Security通常使用的相同方法,在标准认证上构建对象。

To, let’s manually trigger authentication and then set the resulting Authentication object into the current SecurityContext used by the framework to hold the currently logged-in user:

为了,让我们手动触发认证,然后将产生的Authentication对象设置到当前SecurityContext中,由框架用来保存当前登录的用户。

UsernamePasswordAuthenticationToken authReq
 = new UsernamePasswordAuthenticationToken(user, pass);
Authentication auth = authManager.authenticate(authReq);
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);

After setting the Authentication in the context, we’ll now be able to check if the current user is authenticated – using securityContext.getAuthentication().isAuthenticated().

在上下文中设置了Authentication之后,我们现在就可以检查当前用户是否已被认证–使用securityContext.getAuthentication().isAuthenticated()

3. Spring MVC

3.Spring MVC[/strong

By default, Spring Security adds an additional filter in the Spring Security filter chain – which is capable of persisting the Security Context (SecurityContextPersistenceFilter class).

默认情况下,Spring Security在Spring Security过滤器链中添加了一个额外的过滤器–它能够持久化安全上下文(SecurityContextPersistenceFilter类)。

In turn, it delegates the persistence of the Security Context to an instance of SecurityContextRepository, defaulting to the HttpSessionSecurityContextRepository class.

反过来,它将安全上下文的持久性委托给SecurityContextRepository的一个实例,默认为HttpSessionSecurityContextRepository类。

So, in order to set the authentication on the request and hence, make it available for all subsequent requests from the client, we need to manually set the SecurityContext containing the Authentication in the HTTP session:

因此,为了在请求中设置认证,从而使其可用于客户端的所有后续请求,我们需要在HTTP会话中手动设置包含AuthenticationSecurityContext

public void login(HttpServletRequest req, String user, String pass) { 
    UsernamePasswordAuthenticationToken authReq
      = new UsernamePasswordAuthenticationToken(user, pass);
    Authentication auth = authManager.authenticate(authReq);
    
    SecurityContext sc = SecurityContextHolder.getContext();
    sc.setAuthentication(auth);
    HttpSession session = req.getSession(true);
    session.setAttribute(SPRING_SECURITY_CONTEXT_KEY, sc);
}

SPRING_SECURITY_CONTEXT_KEY is a statically imported HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY.

SPRING_SECURITY_CONTEXT_KEY是一个静态导入的HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY

It should be noted that we can’t directly use the HttpSessionSecurityContextRepository – because it works in conjunction with the SecurityContextPersistenceFilter.

应该注意的是,我们不能直接使用HttpSessionSecurityContextRepository–因为它与SecurityContextPersistenceFilter一起工作。

That is because the filter uses the repository in order to load and store the security context before and after the execution of the rest of defined filters in the chain, but it uses a custom wrapper over the response which is passed to the chain.

这是因为该过滤器使用存储库,以便在执行链中其他定义的过滤器前后加载和存储安全上下文,但它在传递给链的响应上使用了一个自定义的包装器。

So in this case, you should know the class type of the wrapper used and pass it to the appropriate save method in the repository.

所以在这种情况下,你应该知道所使用的包装器的类的类型,并把它传递给版本库中适当的保存方法。

4. Conclusion

4.结论

In this quick tutorial, we went over how to manually set the user Authentication in the Spring Security context and how it can be made available for Spring MVC purposes, focusing on the code samples that illustrate the simplest way to achieve it.

在这个快速教程中,我们介绍了如何在Spring Security上下文中手动设置用户Authentication,以及如何使其用于Spring MVC的目的,重点介绍了说明最简单实现方法的代码示例。

As always, code samples can be found over on GitHub.

一如既往,代码样本可以在GitHub上找到over