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.

3. Project Initialization

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

7. Request Filter

8. Model and Repository

9. UserDetailsService

10. Controllers

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

11. Conclusion



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