One Time Token With Jwt

How we can use One Time Token with JWT in spring boot security

We often use JWT for the security in spring application. Since by default, one-time token only work with HTML pages.

So here is the example of how we can use it with the rest APIs and the JWT token.

  • We will be securing our application with JWT token, for that, we will use Ouath2ResourceServer.

  • We will be use basic auth for login and issue jwt.

  • We will create a separate endpoint for generating token and validating them, and after successful validation a jwt token is issues successfully.

Classes Needed

  1. JDBCTokenGeneratorService

  2. JwtTokenService

  3. OneTimeTokenSuccessHandler

  4. SecurityConfiguration & RestController

JWT Token Generation

  • For jwt token generation spring-boot-starter-oauth2-resource-server is being used.

  • It internally used nimbus jose jwt jar.

  • JwtEncoder and JwtDecoder beans to jwt security along with public and private keys.

RSA Keys generation

  • To create a public and private key, we will use OpenSSL.

  • It will generate public and private pem file that we will store at /src/main/resources/cers .

  • After creation of keys, delete keypair.pem file.

  • Define path in properties file and create record to hold them.

To bind the properties, we need to tell spring by adding this in any configuration or main class.

JWT encoder and decoder bean

In security configuration class, define jwt encode and decoder bean

JWT Token Service

JDBCOneTimeTokenService

This class is responsible for generating token and validates them. It uses OneTimeToken entity to store token in database and deleted them after use.

This service is copy of JdbcOneTimeTokenService defined in package org.springframework.security.authentication.ott in spring security.

We also need to schedule a cron to cleanup expired tokens.

SecurityConfiguration

This security configuration has to separate filter chain methods.

One is required to do login with username and password, that only executes when request comes from url as /token

Another one is used for all other application security and ott.

OneTimeTokenSuccessHandler

This class will verify user , get email and send generated token with mail or sms

AuthenticationSuccessHandler

RestController

Last updated