Skip to content

Code example of adding 2FA to a Spring Boot app.

Notifications You must be signed in to change notification settings

neerajshandilya/Spring-Boot-2FA-1

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A Stripped-Down Example of TOTP 2FA with Spring Boot

This example uses Austin Delamar's JOTP: https://github.com/amdelamar/jotp I found it to be the easiest to use, but others should produce the same results.

Run the app with ./mvnw spring-boot:run then browse to http://localhost:8080. When the app is running, the in-memory DB can be inspected at http://localhost:8080/h2-console (credentials). This is, of course, a proof of concept and should not be deployed publicly.

Changes made over the basic login flow

TOTP-based 2FA works like this:

  • Each user needs a secret key which is generated when they create their account.
  • After the account is created, the key is shared with the user in the form of a QR code which creates an account in their authenticator app.
  • When a user tries to log in they have to provide the 6-digit number from their app, which is calculated from the secret and the current time.
  • The same calculation happens server-side to verify that the user possesses the secret key.

Changes made, in detail

The version of this app which does not have 2FA is in this repo, tagged without-2fa. The 2FA-enabled version (ie this version) is in the totp-2fa tag

Account Registration

  1. Add a superSecretSecret field to UserDto. [source]
  2. Set the superSecretSecret in UserService#createNewUser by calling OTP.randomBase32(20). [source]
  3. Add steps to the account creation flow, with a new page showing the QR code, and configuration in WebController. [source] [template]

User Login

  1. Create TwoFAAuthenticationProvider extends DaoAuthenticationProvider, which checks the auth details in the authenticate method. [source]
  2. Create a TwoFAAuthenticationDetailsSource, which implements AuthenticationDetailsSource, essentially just a factory for the above. [source]
  3. Add that into WebSecurityConfig (which extends WebSecurityConfigurerAdapter and is annotated @Configuraion and @EnableWebSecurity). [source]
  4. Make sure to require .authenticated() on any resources that need a logged-in user. [source]

About

Code example of adding 2FA to a Spring Boot app.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 78.6%
  • HTML 19.1%
  • TSQL 2.3%