Reputation: 374
Here, my scenario is bit similar to two-factor authentication of Gmail. When a user logs in successfully(SMS code is send to user) then he is challenged with another page to enter the SMS code. If user gets the SMS code correctly he is shown the secured page(like Gmail Inbox).
I did this bit of research on this and suggestion is to rather than giving ROLE_USER upon login, gave him PRE_AUTH_USER and show the second page where he enters the SMS code; upon success give them ROLE_USER.
However, my question is Spring has InsufficientAuthenticationException and in this scenario we won't make use of it. Will there be other better ways of implementing two factor authentication in my scenario?
P.S. I have bit of customized spring security configuration. In my Login page apart from username and password I have Recaptcha validation as well, also my authenticationProviderm authenticationSuccessHandler, logoutSuccessHandler, accessDeniedHandler all are customized.
Upvotes: 2
Views: 6796
Reputation: 374
Upon SMS code validation success, you could grant ROLE_USER authority as follows.
private void grantAuthority() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(auth.getAuthorities());
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
Authentication newAuth =
new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(),
authorities);
SecurityContextHolder.getContext().setAuthentication(newAuth);
}
The code is from copied from a blog post ,and sample application which has implemented two-factor authentication. If I had found it bit earlier it would save a lot of time !!!
Upvotes: 6
Reputation: 43097
Try to throw InsufficientAuthenticationException
if the first level of authentication passes, then catch it with ExceptionTranslationFilter
and forward to the second level of authentication page.
The two factor authentication page can resubmit the user name and password in hidden fields, together with the two factor token. In this second time the custom authentication provider would be able to authenticate successfully the user.
Upvotes: 3