In this sample code, I am making use of JWT authentication for securing REST API.
In this sample code, Two REST API endpoints have been implemented to facilitate this use-case
-
Register user (This API endpoint is whitelisted in "WebSecurityConfig")
[POST]/register -
Validate user credentials and generate JWT Token
[POST]/authenticate -
Validating JWT Token and allowing access to the desired endpoint if Request has valid JWT Token
[GET]/hello
+ Java 11
+ Spring Boot 2.5.1.RELEASE
+ Spring Boot Rest API
+ Spring security
+ JWT
+ MySQL
<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>
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
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