Spring Security – Auto Login User After Registration – Spring Security – 注册后自动登录用户

最后修改: 2018年 1月 23日

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

1. Overview

1.概述

In this quick tutorial, we’ll discuss how to auto-authenticate users immediately after the registration process – in a Spring Security implementation.

在这个快速教程中,我们将讨论如何在注册过程后立即对用户进行自动认证–在Spring Security的实现中。

Simply put, once the user finishes registering, they’re typically redirected to the login page and have to now re-type their username and password.

简单地说,一旦用户完成了注册,他们通常会被重定向到登录页面,现在必须重新输入他们的用户名和密码。

Let’s see how we can avoid that by auto-authenticating the user instead.

让我们看看我们如何通过自动认证用户来避免这种情况。

Before we get started, note that we’re working within the scope of the registration series here on the site.

在我们开始之前,请注意我们是在网站上的注册系列的范围内工作。

2. Using the HttpServletRequest

2.使用HttpServletRequest

A very simple way to programmatically force an authentication is to leverage the HttpServletRequest login() method:

一个非常简单的方法是利用HttpServletRequest login()方法,以编程方式强制进行认证。

public void authWithHttpServletRequest(HttpServletRequest request, String username, String password) {
    try {
        request.login(username, password);
    } catch (ServletException e) {
        LOGGER.error("Error while login ", e);
    }
}

Now that, under the hood, the HttpServletRequest.login() API does use the AuthenticationManager to perform the authentication.

现在,在引擎盖下,HttpServletRequest.login() API确实使用AuthenticationManager来执行认证。

It’s also important to understand and deal with the ServletException that might occur at this level.

了解并处理在这一层可能发生的ServletException也很重要。

3. Using the AuthenticationManager

3. 使用AuthenticationManager

Next, we can also directly create a UsernamePasswordAuthenticationToken – and then go through the standard AuthenticationManager manually:

接下来,我们也可以直接创建一个UsernamePasswordAuthenticationToken–然后手动通过标准的AuthenticationManager

public void authWithAuthManager(HttpServletRequest request, String username, String password) {
    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
    authToken.setDetails(new WebAuthenticationDetails(request));
    
    Authentication authentication = authenticationManager.authenticate(authToken);
    
    SecurityContextHolder.getContext().setAuthentication(authentication);
}

Notice how we’re creating the token request, passing it through the standard authentication flow, and then explicitly setting the result in the current security context.

注意我们是如何创建令牌请求,通过标准的认证流程,然后明确地在当前的安全上下文中设置结果。

4. Complex Registration

4.复杂的注册

In some, more complex scenarios, the registration process has multiple stages, such as – for example – a confirmation step until the user can log into the system.

在一些更复杂的情况下,注册过程有多个阶段,例如——确认步骤,直到用户可以登录到系统。

In cases like this, it’s, of course, important to understand exactly where we can auto-authenticate the user. We cannot do that right after they register because, at that point, the newly created account is still disabled.

在这样的情况下,当然,重要的是要了解我们到底在哪里可以自动认证用户。我们不能在他们注册后立即这样做,因为在这一点上,新创建的账户仍然是禁用的。

Simply put – we have to perform an automatic authentication after they confirm their account.

简单地说–我们必须在他们确认其账户后进行自动认证

Also, keep in mind that, at that point – we no longer have access to their actual, raw credentials. We only have access to the encoded password of the user – and that’s what we’ll use here:

此外,请记住,在这一点上,我们不再有机会获得他们实际的、原始的凭证。我们只能访问用户的编码密码,这就是我们在这里要使用的。

public void authWithoutPassword(User user){
    
    List<Privilege> privileges = user.getRoles().stream().map(Role::getPrivileges)
      .flatMap(Collection::stream).distinct().collect(Collectors.toList());
    List<GrantedAuthority> authorities = privileges.stream()
        .map(p -> new SimpleGrantedAuthority(p.getName()))
        .collect(Collectors.toList());

    Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
    SecurityContextHolder.getContext().setAuthentication(authentication);
}

Note how we’re setting the authentication authorities properly here, as would typically be done in the AuthenticationProvider.

注意我们如何在这里正确地设置认证机构,通常在AuthenticationProvider.中完成。

5. Conclusion

5.结论

We discussed different ways to auto-authenticate users after the registration process.

我们讨论了在注册过程后自动认证用户的不同方法。

As always, the full source code is available over on GitHub.

一如既往,完整的源代码可在GitHub上获得