注册后弹簧安全自动登录

时间:2013-08-29 13:47:47

标签: spring-security autologin

我创建了一个使用spring security进行身份验证的spring MVC应用程序,这里是spring-security.xml

<http use-expressions="true">
    <form-login login-page="/homepage.jsp" default-target-url="/homepage.jsp" authentication-failure-url="/homepage.jsp?login-success=false" />
    <logout logout-success-url="/homepage.jsp" />
</http>
<authentication-manager alias="authenticationManager" > 
   <authentication-provider>
    <password-encoder hash="sha" />
    <jdbc-user-service data-source-ref="marketDataSource" 

       users-by-username-query="
          select email_address, password, '1' 
          from user where email_address=?" 

        authorities-by-username-query="
          select email_address, 'ROLE_USER' from user 
          where email_address=?" 
      />
   </authentication-provider>
</authentication-manager>

当新用户尝试注册时,他填写注册并按提交,这将创建一个新用户,如果注册成功完成,我尝试使用此方法验证注册用户:

private void authenticateUserAndSetSession(User user, HttpServletRequest request) {

List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
    user.getEmailAddress(), user.getPasswordSha(), grantedAuthorities);

request.getSession();

token.setDetails(new WebAuthenticationDetails(request));
try {
  Authentication authenticatedUser = authenticationManager
      .authenticate(token);
  SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
} catch (Exception e) {
  e.printStackTrace();
}

}

我查看了这篇文章Auto login after successful registration以制作上一个方法,但是当我尝试使用它时,它会抛出Bad Credential Exception,这个解决方案有什么问题?

1 个答案:

答案 0 :(得分:0)

我遇到过类似的问题。在遗留代码中,密码是手工散列的。

更好的选择是使用普通密码存储User类的对象(可能是普通的表单绑定),稍后将其清除。清算credencials也是spring-security的责任(界面org.springframework.security.core.CredentialsContainer)。 如果无法删除编码器的标签或使用纯文本编码器<password-encoder hash="plaintext"/>