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:

<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency><dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency><dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency><dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>

For gradle based projects:

dependencies {
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.2',
'io.jsonwebtoken:jjwt-jackson:0.11.2',
'org.apache.commons:commons-lang3:3.0'
}

5. Project Structure

6. Configuration

7. Request Filter

8. Model and Repository

9. UserDetailsService

10. Controllers

Authentication authentication = SecurityContextHolder
.getContext().getAuthentication();
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