如何在 Spring Security/SpringMVC 中手动设置经过身份验证的用户 [英] How to manually set an authenticated user in Spring Security / SpringMVC

查看:38
本文介绍了如何在 Spring Security/SpringMVC 中手动设置经过身份验证的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在新用户提交新帐户"表单后,我想手动登录该用户,这样他们就不必在后续页面上登录.

After a new user submits a 'New account' form, I want to manually log that user in so they don't have to login on the subsequent page.

通过 spring 安全拦截器的普通表单登录页面工作正常.

The normal form login page going through the spring security interceptor works just fine.

在 new-account-form 控制器中,我正在创建一个 UsernamePasswordAuthenticationToken 并在 SecurityContext 中手动设置它:

In the new-account-form controller I am creating a UsernamePasswordAuthenticationToken and setting it in the SecurityContext manually:

SecurityContextHolder.getContext().setAuthentication(authentication);

在同一页面上,我稍后检查用户是否登录:

On that same page I later check that the user is logged in with:

SecurityContextHolder.getContext().getAuthentication().getAuthorities();

这将返回我之前在身份验证中设置的权限.一切都很好.

This returns the authorities I set earlier in the authentication. All is well.

但是当在我加载的下一个页面上调用相同的代码时,身份验证令牌只是 UserAnonymous.

But when this same code is called on the very next page I load, the authentication token is just UserAnonymous.

我不清楚为什么它没有保留我在上一个请求中设置的身份验证.有什么想法吗?

I'm not clear why it did not keep the authentication I set on the previous request. Any thoughts?

  • 是否与会话 ID 设置不正确有关?
  • 有什么东西可能会以某种方式覆盖我的身份验证吗?
  • 也许我只需要另一个步骤来保存身份验证?
  • 或者我需要做些什么来声明整个会话而不是单个请求的身份验证?

只是寻找一些可能有助于我了解这里发生的事情的想法.

Just looking for some thoughts that might help me see what's happening here.

推荐答案

不久前我遇到了与您相同的问题.我不记得细节,但以下代码对我有用.此代码在 Spring Webflow 流中使用,因此使用 RequestContext 和 ExternalContext 类.但与您最相关的部分是 doAutoLogin 方法.

I had the same problem as you a while back. I can't remember the details but the following code got things working for me. This code is used within a Spring Webflow flow, hence the RequestContext and ExternalContext classes. But the part that is most relevant to you is the doAutoLogin method.

public String registerUser(UserRegistrationFormBean userRegistrationFormBean,
                           RequestContext requestContext,
                           ExternalContext externalContext) {

    try {
        Locale userLocale = requestContext.getExternalContext().getLocale();
        this.userService.createNewUser(userRegistrationFormBean, userLocale, Constants.SYSTEM_USER_ID);
        String emailAddress = userRegistrationFormBean.getChooseEmailAddressFormBean().getEmailAddress();
        String password = userRegistrationFormBean.getChoosePasswordFormBean().getPassword();
        doAutoLogin(emailAddress, password, (HttpServletRequest) externalContext.getNativeRequest());
        return "success";

    } catch (EmailAddressNotUniqueException e) {
        MessageResolver messageResolvable 
                = new MessageBuilder().error()
                                      .source(UserRegistrationFormBean.PROPERTYNAME_EMAIL_ADDRESS)
                                      .code("userRegistration.emailAddress.not.unique")
                                      .build();
        requestContext.getMessageContext().addMessage(messageResolvable);
        return "error";
    }

}


private void doAutoLogin(String username, String password, HttpServletRequest request) {

    try {
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = this.authenticationProvider.authenticate(token);
        logger.debug("Logging in with [{}]", authentication.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        logger.error("Failure in autoLogin", e);
    }

}

这篇关于如何在 Spring Security/SpringMVC 中手动设置经过身份验证的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆