How to access a custom parameter from the login page in spring security?

1.6k views Asked by At

I have a custom field along with "j_username" and "j_password" on my login.jsp, that I need to authenticate the user. I am using a CustomUsernamePasswordAuthenticationFilter to access the custom field as follows.

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); 
    }
}

I tried accessing the session in loadByUsername method of UserDetailsService class but I get an error. Here is the code for my custom UserDetailsService.

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);
    }

Is there any way where I can access this custom parameter for authentication? Sending it through the session doesn't seem to be working.

2

There are 2 answers

2
dardo On

Wouldn't the session be created AFTER the authentication takes place. So a new authenticated session might be created after your call to attemptAuthentication

Here's the spring doc on the Abstract class you're implementing

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

You might be losing the session attribute by the time loadByUsername is called.

0
vutbao On

I ran into the exact problem.

The problem appeared to be that the RequestAttributes was not bound to the current thread. To make it work, I had to explicitly bind it to the current thread.

In CustomUsernamePasswordAuthenticationFilter, after the statement request.getSession().setAttribute("CUSTOM_FIELD", myCustomField);

Add: RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

This worked for for me.