Skip to content

This example shows how to make use of JWT authentication for securing an exposed REST API in a Spring Boot application.

License

Notifications You must be signed in to change notification settings

rowishva/Spring-Boot-Security-JWT-MySQL

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Spring-Boot-Security-JWT-MySQL

In this sample code, I am making use of JWT authentication for securing REST API.

This integration flow diagram is an illustrated API call between layers.

image

In this sample code, Two REST API endpoints have been implemented to facilitate this use-case

  1. Register user (This API endpoint is whitelisted in "WebSecurityConfig")
    [POST]/register

  2. Validate user credentials and generate JWT Token
    [POST]/authenticate

  3. Validating JWT Token and allowing access to the desired endpoint if Request has valid JWT Token
    [GET]/hello

Technology Stack
+ Java 11
+ Spring Boot 2.5.1.RELEASE
+ Spring Boot Rest API
+ Spring security
+ JWT
+ MySQL
Dependency for Spring Boot
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>io.jsonwebtoken</groupId>
			<artifactId>jjwt</artifactId>
			<version>0.9.1</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
Configure Properties
spring.datasource.url=jdbc:mysql://<ip>:3306/jwtdb
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
#debug=true
server.port = 8090
jwt.secret=testjwtauth
Test using Postman
1. Register user

Jwt-create-user

2. Validate user credentials and get JWT Token

Jwt-authenticate-user

3. Call /hello with JWT Token append in Authorization header

Jwt-token-hello

JSON Web Token structure

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:

Header
Payload
Signature

Therefore, a JWT typically looks like the following.

xxxxx.yyyyy.zzzzz
Additional reading

https://jwt.io/introduction

Done !

Author

About

This example shows how to make use of JWT authentication for securing an exposed REST API in a Spring Boot application.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages