Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two factor authentication with Spring Security like Gmail

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.

like image 288
Robert Avatar asked Dec 29 '25 10:12

Robert


2 Answers

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 !!!

like image 165
Robert Avatar answered Jan 04 '26 21:01

Robert


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.

like image 24
Angular University Avatar answered Jan 04 '26 21:01

Angular University



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!