2012-05-31 43 views
0

我在login.jsp上有一个自定义字段以及“j_username”和“j_password”,我需要对用户进行身份验证。我正在使用CustomUsernamePasswordAuthenticationFilter来访问自定义字段,如下所示。如何在弹簧安全中从登录页面访问自定义参数?

public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { 
    @Override 
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { 
     String myCustomField= request.getParameter("myCustomField"); 
     request.getSession().setAttribute("CUSTOM_FIELD", myCustomField); 

     return super.attemptAuthentication(request, response); 
    } 
} 

我试过的UserDetailsS​​ervice类的loadByUsername方法访问会话,但我得到一个错误。以下是我的自定义UserDetailsS​​ervice的代码。

public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException { 

     ServletRequestAttributes attr = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes(); 
     HttpSession session = attr.getRequest().getSession(); 
     User userObject = dbObject.retrieveUser(userName,myCustomParameter) 
// code here to retrieve my user from the DB using the userName and myCustomParameter that was retrieved from login.jsp and put in the session. Get the custom parameter from the session here. 

     if (userObject == null) 
       throw new UsernameNotFoundException("user not found"); 

     return new AuthenticationUserDetails(userObject); 
    } 

有没有什么办法可以访问这个自定义参数进行身份验证?通过会话发送它似乎没有工作。

回答

0

在身份验证发生后不会创建会话。因此,一个新的认证会话可能您的来电后创建attemptAuthentication

这里是在抽象类的春天DOC你实现

http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.html#successfulAuthentication%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse,%20org.springframework.security.core.Authentication%29

您可能会被时间loadByUsername失去会话属性调用。

+0

dardo:谢谢你的回复。是的,这似乎是问题,因为会话是在验证后创建的。有什么办法可以在我的'loadByUsername'方法中访问这个新参数,因为我需要检索传递到AuthenticationUserDetails中进行身份验证的用户对象。 – user1041836

+0

你可以真正做你想做的任何事情,如果你想把它放在Session中,然后在loadByUsername中检索它,使用org.springframework.web.context.request.RequestContextHolder,比如... attrs =(ServletRequestAttributes)RequestContextHolder。 currentRequestAttributes(); 。attrs.getRequest()的getSession(真);可能不是最干净的做事方式,但它应该起作用 – dardo

0

我碰到了确切的问题。

问题似乎是RequestAttributes未绑定到当前线程。为了使它工作,我必须明确地将它绑定到当前线程。

CustomUsernamePasswordAuthenticationFilter,会后声明 request.getSession().setAttribute("CUSTOM_FIELD", myCustomField);

地址: RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

这个工作对我。

相关问题