Spring Security 4 2FA

2019-05-22 17:49发布

问题:

so I am trying to secure a web application that I built using spring mvc and security. I currently have the basic username and password from a normal custom login page working using a custom authentication provider to provide the populated authentication object that is verified against a database. What I am wondering is how do I implement a second phase of logging in that uses TOTP? I can get the the TOTP issuing and verification to work, but am unsure how to modify spring security to accept a change to authorization via a form submission of the token on a page other then the login page I've specified.

回答1:

So basically what I ended up doing was using the authy api(http://docs.authy.com/) to do the TOTP delivery and verification. After the initial login I grant them ROLE_PRE_AUTH and then send them to a protected page to process the TOTP. I then used

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

to update the roles for the user once I verified that they had a valid TOTP.