I just announced the newSpring Security 5 modules (primarily focused on OAuth2) in the course:


1. Overview

In this tutorial, we’re going to implement Two Factor Authentication functionality with a Soft Token and Spring Security.

We’re going to be adding the new functionality into an existing, simple login flow and use the Google Authenticator app to generate the tokens.

Simply put, two factor authentication is a verification process which follows the well known principle of “something the user knows and something the user has”.

And so, users provide an extra “verification token” during authentication – a one-time password verification code based on Time-based One-time Password TOTP algorithm.

2. Maven Configuration

First, in order to use Google Authenticator in our app we need to:

  • Generate secret key
  • Provide secret key to the user via QR-code
  • Verify token entered by the user using this secret key.

We will use a simple server-side library to generate/verify one-time password by adding the following dependency to our pom.xml:


3. User Entity

Next, we will modify our user entity to hold extra information – as follows:

public class User {
    private boolean isUsing2FA;
    private String secret;

    public User() {
        this.secret = Base32.random();

Note that:

  • We save a random secret code for each user to be used later in generating verification code
  • Our 2-step verification is optional

4. Extra Login Parameter

First, we will need to adjust our security configuration to accept extra parameter – verification token. We can accomplish that by using custom AuthenticationDetailsSource:

Here is our CustomWebAuthenticationDetailsSource:

public class CustomWebAuthenticationDetailsSource implements 
  AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {
    public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
        return new CustomWebAuthenticationDetails(context);

and here is CustomWebAuthenticationDetails:

public class CustomWebAuthenticationDetails extends WebAuthenticationDetails {

    private String verificationCode;

    public CustomWebAuthenticationDetails(HttpServletRequest request) {
        verificationCode = request.getParameter("code");

    public String getVerificationCode() {
        return verificationCode;

And our security configuration:

public class LssSecurityConfig extends WebSecurityConfigurerAdapter {

    private CustomWebAuthenticationDetailsSource authenticationDetailsSource;

    protected void configure(HttpSecurity http) throws Exception {

And finally add the extra parameter to our login form:

    Google Authenticator Verification Code
<input type='text' name='code'/>

Note: We need to set our custom AuthenticationDetailsSource in our security configuration.

5. Custom Authentication Provider

Next, we’ll need a custom AuthenticationProvider to handle extra parameter validation:

public class CustomAuthenticationProvider extends DaoAuthenticationProvider {

    private UserRepository userRepository;

    public Authentication authenticate(Authentication auth)
      throws AuthenticationException {
        String verificationCode 
          = ((CustomWebAuthenticationDetails) auth.getDetails())
        User user = userRepository.findByEmail(auth.getName());
        if ((user == null)) {
            throw new BadCredentialsException("Invalid username or password");
        if (user.isUsing2FA()) {
            Totp totp = new Totp(user.getSecret());
            if (!isValidLong(verificationCode) || !totp.verify(verificationCode)) {
                throw new BadCredentialsException("Invalid verfication code");
        Authentication result = super.authenticate(auth);
        return new UsernamePasswordAuthenticationToken(
          user, result.getCredentials(), result.getAuthorities());

    private boolean isValidLong(String code) {
        try {
        } catch (NumberFormatException e) {
            return false;
        return true;

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

Note that – after we verified the one-time-password verification code, we simply delegated authentication downstream.

Here is our Authentication Provider bean

public DaoAuthenticationProvider authProvider() {
    CustomAuthenticationProvider authProvider = new CustomAuthenticationProvider();
    return authProvider;

6. Registration Process

Now, in order for users to be able to use the application to generate the tokens, they’ll need to set things up properly when they register.

And so, we’ll need to do few simple modifications to the registration process – to allow users who have chosen to use 2-step verification to scan the QR-code they need to login later.

First, we add this simple input to our registration form:

Use Two step verification <input type="checkbox" name="using2FA" value="true"/>

Then, in our RegistrationController – we redirect users based on their choices after confirming registration:

@RequestMapping(value = "/registrationConfirm", method = RequestMethod.GET)
public String confirmRegistration(@RequestParam("token") String token, ...) {
    String result = userService.validateVerificationToken(token);
    if(result.equals("valid")) {
        User user = userService.getUser(token);
        if (user.isUsing2FA()) {
            model.addAttribute("qr", userService.generateQRUrl(user));
            return "redirect:/qrcode.html?lang=" + locale.getLanguage();
          "message", messages.getMessage("message.accountVerified", null, locale));
        return "redirect:/login?lang=" + locale.getLanguage();

And here is our method generateQRUrl():

public static String QR_PREFIX = 

public String generateQRUrl(User user) {
    return QR_PREFIX + URLEncoder.encode(String.format(
      APP_NAME, user.getEmail(), user.getSecret(), APP_NAME),

And here is our qrcode.html:

<div id="qr">
        Scan this Barcode using Google Authenticator app on your phone 
        to use it later in login
    <img th:src="${param.qr[0]}"/>
<a href="/login" class="btn btn-primary">Go to login page</a>

Note that:

  • generateQRUrl() method is used to generate QR-code URL
  • This QR-code will be scanned by users mobile phones using Google Authenticator app
  • The app will generate a 6-digit code that is valid for only 30 seconds which is desired verification code
  • This verification code will be verified while login using our custom AuthenticationProvider

7. Enable Two Step Verification

Next, we will make sure that users can change their login preferences at any time – as follows:

@RequestMapping(value = "/user/update/2fa", method = RequestMethod.POST)
public GenericResponse modifyUser2FA(@RequestParam("use2FA") boolean use2FA) 
  throws UnsupportedEncodingException {
    User user = userService.updateUser2FA(use2FA);
    if (use2FA) {
        return new GenericResponse(userService.generateQRUrl(user));
    return null;

And here is updateUser2FA():

public User updateUser2FA(boolean use2FA) {
    Authentication curAuth = SecurityContextHolder.getContext().getAuthentication();
    User currentUser = (User) curAuth.getPrincipal();
    currentUser = repository.save(currentUser);
    Authentication auth = new UsernamePasswordAuthenticationToken(
      currentUser, currentUser.getPassword(), curAuth.getAuthorities());
    return currentUser;

And here is the front-end:

<div th:if="${#authentication.principal.using2FA}">
    You are using Two-step authentication 
    <a href="#" onclick="disable2FA()">Disable 2FA</a> 
<div th:if="${! #authentication.principal.using2FA}">
    You are not using Two-step authentication 
    <a href="#" onclick="enable2FA()">Enable 2FA</a> 
<div id="qr" style="display:none;">
    <p>Scan this Barcode using Google Authenticator app on your phone </p>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function enable2FA(){
function disable2FA(){
function set2FA(use2FA){
    $.post( "/user/update/2fa", { use2FA: use2FA } , function( data ) {
        	$("#qr").append('<img src="'+data.message+'" />').show();

8. Conclusion

In this quick tutorial, we illustrated how to do a two-factor authentication implementation using a Soft Token with Spring Security.

The full source code can be found – as always – over on GitHub.

I just announced the new Spring Security 5 modules (primarily focused on OAuth2) in the course:


newest oldest most voted
Notify of


By the way, is there a way to use this solution with Spring Social? What are the benefits of using social instead this?

Eugen Paraschiv

Hey Hinotori,
By Spring Social I assume you mean authenticating with an Auth server belonging to a third party (Facebook, Twitter, etc). Sure – that’s a good way to go as well, because most of these third-parties already have two-step auth as an option.

Simplify Technovations
Simplify Technovations

Hi Thanks a lot for your great explanation,
I have a problem with verification code which generated by Google Authenticator,
the verification code contains whitespace such as 503 543, 582 523.
so when it parse into Long, it will generate NumberFormatException.

Eugen Paraschiv

That looks like a very implementation specific problem – you’ll have to either not assume it’s a Long and look at it as a raw String, or see if the library can be tuned to generate a specific format. Either way should be fine.
Hope that helps. Cheers,