Spring Boot REST API authentication best practices using JWT (2022)

1. Overview

2. What is a JWT?

  1. Header: It contains signing algorithm like SHA256.
  2. Payload: It contains our user data.
  3. Signature: To verify the message wasn’t changed along the way, making it secure.

Combing all three will make our JWT look something like this xxxxx.yyyyy.zzzzz. To learn more about JWT please visit - https://jwt.io/

3. Project Initialization

Hit generate and import project in your favorite IDE. Also, don’t forget to add database properties in application.properties file.

spring.data.mongodb.database=your_db_name_here spring.data.mongodb.port=27017

4. Additional Dependencies

For maven based projects:


For gradle based projects:

dependencies {
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.2',

5. Project Structure

6. Configuration

In above configure(HttpSecurity httpSecurity) method we have defined to permit all request starting with /auth route that's where we will add our Authentication Controller. If the request is unauthorized our API will throw a 401 error message.

7. Request Filter

In this doFilterInternal() method we will fetch JWT token from the request header and process it by validating and obtaining username from token's payload. Further if token is valid we will fetch user from database and add it in SecurityContextHolder, we can further use it any of our service to perform various user related operations.

In JwtTokenUtil.java we will perform all JWT token related operations such as generating new token and Validating given token.

8. Model and Repository

We will use Lombok framework here to quickly create our User.java model. It is completely optional but it is my favorite way of defining a model class. Afterall life is too short to write getters and setters.

We will write our UserRepository.java interface and define a method to fetch user details from username.

9. UserDetailsService

In JwtUserDetailsService.java class we will customize default spring security way of getting user by implementing UserDetailsService interface.

10. Controllers

Last but not the least we will define controllers in order to communicate with our API.

AuthenticationController.java will deal with user login and register. In both the routes we will generate JWT tokens and send it in response to the user.

Example of response to our register request:

You can save this token from response in local storage of your client (Reactive web or Mobile app) and use this token later in protected routes of your API. If we provide invalid credentials to our login request we will get a response with error code 401:

Now its time to actually use our JWT token to identify user associated to a HTTP request. Following code snippet will help you get the authenticated user anywhere in your project:

Authentication authentication = SecurityContextHolder
String username = authentication.getName();

For testing we will define UserController.java. Here you can get the user we added earlier during request filter in SecurityContextHolder.

When we will send the newly created JWT token in Authorization header we will get a proper response as follows:

11. Conclusion

Complete code for this tutorial is committed in my Github repository. Don’t forget to hit the star button :p

Thank you for reading this post, please give your valuable feedback in comments section.

Originally published at https://blog.iamprafful.com.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store