Passing Extra Login Fields with Spring Security

In Spring Security, it just support to receive only 2 parameters i.e. user_name and password by default. Now, we have a scenario where login form includes login_type as well as a third field. We just want to pass more one parameter along with this login form.


There's a number of ways to achieve this. Most used method is by extending UsernamePasswordAuthenticationFilter class and creating your custom filters. However this is complex and long 
procedure, lot of code required.

In this article I am going to explore two easiest ways:

Method 1:


Add the following listener in web.xml.

Note: The order of listener should be first one, if are there many listener.

Step (i)
<listener>
    <listener-class>
        org.springframework.web.context.request.RequestContextListener
    </listener-class>
</listener>
<context-param>
    <param-name>loginType</param-name>
    <param-value></param-value>
</context-param>

Step(ii)


Now add below code snippet in your java code where you want to get this additional parameter. In my case I am getting it in AuthenticationProvider's Authentication authenticate() method as below:

RequestAttributes attribs = RequestContextHolder.getRequestAttributes();

HttpServletRequest request = null;
  
if (RequestContextHolder.getRequestAttributes() != null) {
    request = ((ServletRequestAttributes) attribs).getRequest();
}
  
System.out.println("extra param : "+ request.getParameter("loginType"));

Method 2:


Another easiest way if you are using Custom AuthenticationProvider. You can just inject HttpServletRequest and retrieve your extra parameter:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Autowired(required = false)
private HttpServletRequest request;

@Autowired
UserService userService;

@Override
public Authentication authenticate(Authentication authentication) 
{
   System.out.println("request testing= " + request.getParameter("loginType"));
}

@Override
public boolean supports(Class<?> authentication) {
 return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}


Hope You enjoy both above methods. :)

No comments:

Post a Comment