Spring Boot Token based Authentication with Spring Security & JWT
In this tutorial, we’re gonna build a Spring Boot Application that supports Token based Authentication with JWT. You’ll know:
- Appropriate Flow for User Signup & User Login with JWT Authentication
- Spring Boot Application Architecture with Spring Security
- How to configure Spring Security to work with JWT
- How to define Data Models and association for Authentication and Authorization
- Way to use Spring Data JPA to interact with PostgreSQL/MySQL Database
Lots of interesting things ahead, let’s explore together.
– Related Posts:
- Spring Boot Refresh Token with JWT example
- Spring Boot, Spring Data JPA – Building Rest CRUD API example
- Spring Boot File upload example with Multipart File
- @RestControllerAdvice example in Spring Boot
- Spring Boot @ControllerAdvice & @ExceptionHandler example
- @DataJpaTest example for Spring Data Repository Unit Test
- Spring Boot Unit Test for Rest Controller
- Using MongoDB: Spring Boot JWT Auth with MongoDB
- The example that uses HttpOnly Cookies instead.
- Documentation: Spring Boot Swagger 3 example
- Caching: Spring Boot Redis Cache example
– Deployment:
Contents [hide]
- Overview of Spring Boot JWT Authentication example
- Spring Boot Signup & Login with JWT Authentication Flow
- Spring Boot Server Architecture with Spring Security
- Technology
- Project Structure
- Setup new Spring Boot project
- Configure Spring Datasource, JPA, App properties
- Create the models
- Implement Repositories
- Configure Spring Security
- Implement UserDetails & UserDetailsService
- Filter the Requests
- Create JWT Utility class
- Handle Authentication Exception
- Define payloads for Spring RestController
- Create Spring RestAPIs Controllers
- Run & Test
- Conclusion
- Source Code
- Further Reading
Overview of Spring Boot JWT Authentication example
We will build a Spring Boot application in that:
- User can signup new account, or login with username & password.
- By User’s role (admin, moderator, user), we authorize the User to access resources
These are APIs that we need to provide:
https://googleads.g.doubleclick.net/pagead/ads?gdpr=0&us_privacy=1—&client=ca-pub-9222145312954144&output=html&h=250&slotname=9066284388&adk=1103493481&adf=601653482&pi=t.ma~as.9066284388&w=300&lmt=1681154232&format=300×250&url=https%3A%2F%2Fwww.bezkoder.com%2Fspring-boot-jwt-authentication%2F&wgl=1&uach=WyJXaW5kb3dzIiwiMTAuMC4wIiwieDg2IiwiIiwiMTEyLjAuMTcyMi4zNCIsW10sZmFsc2UsbnVsbCwiNjQiLFtbIkNocm9taXVtIiwiMTEyLjAuNTYxNS40OSJdLFsiTWljcm9zb2Z0IEVkZ2UiLCIxMTIuMC4xNzIyLjM0Il0sWyJOb3Q6QS1CcmFuZCIsIjk5LjAuMC4wIl1dLGZhbHNlXQ..&dt=1681154231562&bpp=2&bdt=1255&idt=901&shv=r20230405&mjsv=m202304060101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Ddcc8d41266a4a43f-220acb3ce27f0060%3AT%3D1681153926%3ART%3D1681153926%3AS%3DALNI_Mb6-sovY-FCcl6I6QICeP_E5x5D-A&gpic=UID%3D00000a47dd1fbd4e%3AT%3D1681153926%3ART%3D1681153926%3AS%3DALNI_MbXXGqrpHKljS_v4NC2CHLsVk9zEQ&prev_fmts=0x0&nras=1&correlator=2718983404809&frm=20&pv=1&ga_vid=730179837.1681153925&ga_sid=1681154232&ga_hid=1267126296&ga_fc=1&ga_cid=1557657401.1681153926&u_tz=-180&u_his=1&u_h=900&u_w=1600&u_ah=860&u_aw=1600&u_cd=24&u_sd=1&dmc=8&adx=263&ady=1665&biw=1526&bih=789&scr_x=0&scr_y=0&eid=44759875%2C44759926%2C44759837%2C42532186%2C42532090%2C31071258%2C31073584%2C31073710%2C42531706&oid=2&pvsid=824841505076684&tmod=1288999789&wsm=1&uas=0&nvt=1&fc=1920&brdim=1537%2C1%2C1537%2C1%2C1600%2C0%2C1598%2C858%2C1543%2C789&vis=1&rsz=%7C%7ClevEbr%7C&abl=CS&pfx=0&fu=0&bc=31&ifi=2&uci=a!2&btvi=1&fsb=1&xpc=kJ1gKdZKx9&p=https%3A//www.bezkoder.com&dtd=910
https://googleads.g.doubleclick.net/pagead/ads?gdpr=0&us_privacy=1—&client=ca-pub-9222145312954144&output=html&h=250&slotname=1209584201&adk=3077205280&adf=139614164&pi=t.ma~as.1209584201&w=300&lmt=1681154232&format=300×250&url=https%3A%2F%2Fwww.bezkoder.com%2Fspring-boot-jwt-authentication%2F&wgl=1&uach=WyJXaW5kb3dzIiwiMTAuMC4wIiwieDg2IiwiIiwiMTEyLjAuMTcyMi4zNCIsW10sZmFsc2UsbnVsbCwiNjQiLFtbIkNocm9taXVtIiwiMTEyLjAuNTYxNS40OSJdLFsiTWljcm9zb2Z0IEVkZ2UiLCIxMTIuMC4xNzIyLjM0Il0sWyJOb3Q6QS1CcmFuZCIsIjk5LjAuMC4wIl1dLGZhbHNlXQ..&dt=1681154231564&bpp=3&bdt=1257&idt=932&shv=r20230405&mjsv=m202304060101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Ddcc8d41266a4a43f-220acb3ce27f0060%3AT%3D1681153926%3ART%3D1681153926%3AS%3DALNI_Mb6-sovY-FCcl6I6QICeP_E5x5D-A&gpic=UID%3D00000a47dd1fbd4e%3AT%3D1681153926%3ART%3D1681153926%3AS%3DALNI_MbXXGqrpHKljS_v4NC2CHLsVk9zEQ&prev_fmts=0x0%2C300x250&nras=1&correlator=2718983404809&frm=20&pv=1&ga_vid=730179837.1681153925&ga_sid=1681154232&ga_hid=1267126296&ga_fc=1&ga_cid=1557657401.1681153926&u_tz=-180&u_his=1&u_h=900&u_w=1600&u_ah=860&u_aw=1600&u_cd=24&u_sd=1&dmc=8&adx=578&ady=1665&biw=1526&bih=789&scr_x=0&scr_y=0&eid=44759875%2C44759926%2C44759837%2C42532186%2C42532090%2C31071258%2C31073584%2C31073710%2C42531706&oid=2&pvsid=824841505076684&tmod=1288999789&wsm=1&uas=0&nvt=1&fc=1920&brdim=1537%2C1%2C1537%2C1%2C1600%2C0%2C1598%2C858%2C1543%2C789&vis=1&rsz=%7C%7ClevEbr%7C&abl=CS&pfx=0&fu=0&bc=31&ifi=3&uci=a!3&btvi=2&fsb=1&xpc=ZeK9V114SR&p=https%3A//www.bezkoder.com&dtd=940
| Methods | Urls | Actions |
|---|---|---|
| POST | /api/auth/signup | signup new account |
| POST | /api/auth/signin | login an account |
| GET | /api/test/all | retrieve public content |
| GET | /api/test/user | access User’s content |
| GET | /api/test/mod | access Moderator’s content |
| GET | /api/test/admin | access Admin’s content |
The database we will use could be PostgreSQL or MySQL depending on the way we configure project dependency & datasource.
This is our Spring Boot application demo running with MySQL database and test Rest Apis with Postman.
For Fullstack, please visit:
- Spring Boot + Vuejs: JWT Authentication Example
- Spring Boot + Angular 8: JWT Authentication Example
- Spring Boot + Angular 10: JWT Authentication Example
- Spring Boot + Angular 11: JWT Authentication Example
- Spring Boot + Angular 12: JWT Authentication example
- Spring Boot + Angular 13: JWT Authentication example
- Spring Boot + Angular 14: JWT Authentication example
- Spring Boot + React.js: JWT Authentication example
Spring Boot Signup & Login with JWT Authentication Flow
The diagram shows flow of how we implement User Registration, User Login and Authorization process.

A legal JWT must be added to HTTP Authorization Header if Client accesses protected resources.
https://googleads.g.doubleclick.net/pagead/ads?gdpr=0&us_privacy=1—&client=ca-pub-9222145312954144&output=html&h=158&slotname=8580577265&adk=2474542750&adf=1097030119&pi=t.ma~as.8580577265&w=630&fwrn=4&lmt=1681154234&rafmt=11&format=630×158&url=https%3A%2F%2Fwww.bezkoder.com%2Fspring-boot-jwt-authentication%2F&wgl=1&uach=WyJXaW5kb3dzIiwiMTAuMC4wIiwieDg2IiwiIiwiMTEyLjAuMTcyMi4zNCIsW10sZmFsc2UsbnVsbCwiNjQiLFtbIkNocm9taXVtIiwiMTEyLjAuNTYxNS40OSJdLFsiTWljcm9zb2Z0IEVkZ2UiLCIxMTIuMC4xNzIyLjM0Il0sWyJOb3Q6QS1CcmFuZCIsIjk5LjAuMC4wIl1dLGZhbHNlXQ..&dt=1681154231567&bpp=5&bdt=1259&idt=949&shv=r20230405&mjsv=m202304060101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Ddcc8d41266a4a43f-220acb3ce27f0060%3AT%3D1681153926%3ART%3D1681153926%3AS%3DALNI_Mb6-sovY-FCcl6I6QICeP_E5x5D-A&gpic=UID%3D00000a47dd1fbd4e%3AT%3D1681153926%3ART%3D1681153926%3AS%3DALNI_MbXXGqrpHKljS_v4NC2CHLsVk9zEQ&prev_fmts=0x0%2C300x250%2C300x250%2C300x600%2C300x600%2C300x600%2C120x600%2C728x90&nras=1&correlator=2718983404809&frm=20&pv=1&ga_vid=730179837.1681153925&ga_sid=1681154232&ga_hid=1267126296&ga_fc=1&ga_cid=1557657401.1681153926&rplot=4&u_tz=-180&u_his=1&u_h=900&u_w=1600&u_ah=860&u_aw=1600&u_cd=24&u_sd=1&dmc=8&adx=263&ady=3935&biw=1526&bih=789&scr_x=0&scr_y=828&eid=44759875%2C44759926%2C44759837%2C42532186%2C42532090%2C31071258%2C31073584%2C31073710%2C42531706&oid=2&psts=AHQMDFdvoG3r6llV3hp_KquTaZG3P-yuvOGhn8cXU75u2JzEOpMcdKS9bYxuYUYIWKummqIahVJR5wJxYm4kn-9cbrsMyiJ8%2CAHQMDFdfOM9cyllnXY6egkWcuWPvDe8IdCs6hpoEk049uJ5BeffeR5WXhFhSJ6PxIYmQVipQHNUDl0L-I2WXBjB0KNm7GG-K&pvsid=824841505076684&tmod=1288999789&wsm=1&uas=0&nvt=1&fc=1920&brdim=1537%2C1%2C1537%2C1%2C1600%2C0%2C1598%2C858%2C1543%2C789&vis=1&rsz=%7C%7CeEbr%7C&abl=CS&pfx=0&fu=128&bc=31&ifi=4&uci=a!4&btvi=6&fsb=1&xpc=AtGwr1P9V6&p=https%3A//www.bezkoder.com&dtd=2836
You will need to implement Refresh Token:

More details at: Spring Boot Refresh Token with JWT example
You can also visit The example that uses HttpOnly Cookies instead.
Spring Boot Server Architecture with Spring Security
You can have an overview of our Spring Boot Server with the diagram below:
https://googleads.g.doubleclick.net/pagead/ads?gdpr=0&us_privacy=1—&client=ca-pub-9222145312954144&output=html&h=158&slotname=4842295194&adk=1464654937&adf=172974155&pi=t.ma~as.4842295194&w=630&fwrn=4&lmt=1681154241&rafmt=11&format=630×158&url=https%3A%2F%2Fwww.bezkoder.com%2Fspring-boot-jwt-authentication%2F&wgl=1&uach=WyJXaW5kb3dzIiwiMTAuMC4wIiwieDg2IiwiIiwiMTEyLjAuMTcyMi4zNCIsW10sZmFsc2UsbnVsbCwiNjQiLFtbIkNocm9taXVtIiwiMTEyLjAuNTYxNS40OSJdLFsiTWljcm9zb2Z0IEVkZ2UiLCIxMTIuMC4xNzIyLjM0Il0sWyJOb3Q6QS1CcmFuZCIsIjk5LjAuMC4wIl1dLGZhbHNlXQ..&dt=1681154231572&bpp=4&bdt=1264&idt=945&shv=r20230405&mjsv=m202304060101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Ddcc8d41266a4a43f-220acb3ce27f0060%3AT%3D1681153926%3ART%3D1681153926%3AS%3DALNI_Mb6-sovY-FCcl6I6QICeP_E5x5D-A&gpic=UID%3D00000a47dd1fbd4e%3AT%3D1681153926%3ART%3D1681153926%3AS%3DALNI_MbXXGqrpHKljS_v4NC2CHLsVk9zEQ&prev_fmts=0x0%2C300x250%2C300x250%2C300x600%2C300x600%2C300x600%2C120x600%2C728x90%2C630x158%2C1526x789%2C160x600&nras=3&correlator=2718983404809&frm=20&pv=1&ga_vid=730179837.1681153925&ga_sid=1681154232&ga_hid=1267126296&ga_fc=1&ga_cid=1557657401.1681153926&rplot=4&u_tz=-180&u_his=1&u_h=900&u_w=1600&u_ah=860&u_aw=1600&u_cd=24&u_sd=1&dmc=8&adx=263&ady=4984&biw=1526&bih=789&scr_x=0&scr_y=1833&eid=44759875%2C44759926%2C44759837%2C42532186%2C42532090%2C31071258%2C31073584%2C31073710%2C42531706&oid=2&psts=AHQMDFdvoG3r6llV3hp_KquTaZG3P-yuvOGhn8cXU75u2JzEOpMcdKS9bYxuYUYIWKummqIahVJR5wJxYm4kn-9cbrsMyiJ8%2CAHQMDFdfOM9cyllnXY6egkWcuWPvDe8IdCs6hpoEk049uJ5BeffeR5WXhFhSJ6PxIYmQVipQHNUDl0L-I2WXBjB0KNm7GG-K%2CAHQMDFcIEORLW_JZtxHTlulmtvup4c8JYyQEjXSOfRA3D869T_CHhBzJZmDg_nRDHcTs8gjrYfyT2RyJJzcX5GfvgytTBg%2CAHQMDFePlw2NyneDFAD1JfRiKEJdDeh-HOjlG41Xxqs9iFF1OGBwM4tG6u13yC0w325FGR-dqhEZ2_W02XL9DKgOPhNIAA%2CAHQMDFc_KDOwGznnlReALUQec1UUE-irKyW75VGcsJiflp8Dcb3vBia8otP7l8YnTKH-4MXd-KRX5aIU6X0WqMI715MjGw%2CAHQMDFegD4Lp72NX7qBD13VjEcoHCoPxvjsXZmqOsmbSQVUIUu2_lc6bc1L2rkKD0O99qWQ8vn317QEqC-U2X81pwMxwBZQV%2CAHQMDFdXSqUWUsV4Csv_G4hqAF7plMqzT9Z2LI5DLjMRfFjm-ZP_3bgnVpzcqeYA4LKDoCJw4_aHxgRDsYPQxsTQWvaWpA%2CAHQMDFftZJJnl6U7P1mpl9Pqp2sEULDaTobUOMp5zkVpi75h0YEBD47y6B1QkxiQVszSGQUBK66GW5kEcqo3Un4rfXcbEw&pvsid=824841505076684&tmod=1288999789&wsm=1&uas=0&nvt=1&fc=1920&brdim=1537%2C1%2C1537%2C1%2C1600%2C0%2C1598%2C858%2C1543%2C789&vis=1&rsz=%7C%7CeEbr%7C&abl=CS&pfx=0&fu=128&bc=31&ifi=5&uci=a!5&btvi=8&fsb=1&xpc=7c1NlxK7Df&p=https%3A//www.bezkoder.com&dtd=9958

Now I will explain it briefly.
Spring Security
– WebSecurityConfig is the crux of our security implementation. It configures cors, csrf, session management, rules for protected resources. We can also extend and customize the default configuration that contains the elements below.
(WebSecurityConfigurerAdapter is deprecated from Spring 2.7.0, you can check the source code for update. More details at:
WebSecurityConfigurerAdapter Deprecated in Spring Boot)
– UserDetailsService interface has a method to load User by username and returns a UserDetails object that Spring Security can use for authentication and validation.
– UserDetails contains necessary information (such as: username, password, authorities) to build an Authentication object.
– UsernamePasswordAuthenticationToken gets {username, password} from login Request, AuthenticationManager will use it to authenticate a login account.
– AuthenticationManager has a DaoAuthenticationProvider (with help of UserDetailsService & PasswordEncoder) to validate UsernamePasswordAuthenticationToken object. If successful, AuthenticationManager returns a fully populated Authentication object (including granted authorities).
– OncePerRequestFilter makes a single execution for each request to our API. It provides a doFilterInternal() method that we will implement parsing & validating JWT, loading User details (using UserDetailsService), checking Authorizaion (using UsernamePasswordAuthenticationToken).
– AuthenticationEntryPoint will catch authentication error.
Repository contains UserRepository & RoleRepository to work with Database, will be imported into Controller.
Controller receives and handles request after it was filtered by OncePerRequestFilter.
– AuthController handles signup/login requests
– TestController has accessing protected resource methods with role based validations.
Understand the architecture deeply and grasp the overview more easier:
Spring Boot Architecture for JWT with Spring Security
Technology
- Java 8
- Spring Boot 2 (with Spring Security, Spring Web, Spring Data JPA)
- jjwt 0.9.1
- PostgreSQL/MySQL
- Maven 3.6.1
Project Structure
This is folders & files structure for our Spring Boot application:

security: we configure Spring Security & implement Security Objects here.
WebSecurityConfigUserDetailsServiceImplimplementsUserDetailsServiceUserDetailsImplimplementsUserDetailsAuthEntryPointJwtimplementsAuthenticationEntryPointAuthTokenFilterextendsOncePerRequestFilterJwtUtilsprovides methods for generating, parsing, validating JWT
controllers handle signup/login requests & authorized requests.
AuthController: @PostMapping(‘/signin’), @PostMapping(‘/signup’)TestController: @GetMapping(‘/api/test/all’), @GetMapping(‘/api/test/[role]’)
repository has intefaces that extend Spring Data JPA JpaRepository to interact with Database.
UserRepositoryextendsJpaRepository<User, Long>RoleRepositoryextendsJpaRepository<Role, Long>
models defines two main models for Authentication (User) & Authorization (Role). They have many-to-many relationship.
User: id, username, email, password, rolesRole: id, name
payload defines classes for Request and Response objects
We also have application.properties for configuring Spring Datasource, Spring Data JPA and App properties (such as JWT Secret string or Token expiration time).
Setup new Spring Boot project
Use Spring web tool or your development tool (Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project.
Then open pom.xml and add these dependencies:
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
We also need to add one more dependency.
– If you want to use PostgreSQL:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
– or MySQL is your choice:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
Configure Spring Datasource, JPA, App properties
Under src/main/resources folder, open application.properties, add some new lines.
For PostgreSQL
spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
spring.datasource.username= postgres
spring.datasource.password= 123
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
# App Properties
bezkoder.app.jwtSecret= bezKoderSecretKey
bezkoder.app.jwtExpirationMs= 86400000
For MySQL
spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto= update
# App Properties
bezkoder.app.jwtSecret= bezKoderSecretKey
bezkoder.app.jwtExpirationMs= 86400000
Create the models
We’re gonna have 3 tables in database: users, roles and user_roles for many-to-many relationship.
Let’s define these models.
In models package, create 3 files:
ERole enum in ERole.java.
In this example, we have 3 roles corresponding to 3 enum.
package com.bezkoder.springjwt.models;
public enum ERole {
ROLE_USER,
ROLE_MODERATOR,
ROLE_ADMIN
}
Role model in Role.java
package com.bezkoder.springjwt.models;
import javax.persistence.*;
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Enumerated(EnumType.STRING)
@Column(length = 20)
private ERole name;
public Role() {
}
public Role(ERole name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public ERole getName() {
return name;
}
public void setName(ERole name) {
this.name = name;
}
}
User model in User.java.
It has 5 fields: id, username, email, password, roles.
package com.bezkoder.springjwt.models;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Entity
@Table( name = "users",
uniqueConstraints = {
@UniqueConstraint(columnNames = "username"),
@UniqueConstraint(columnNames = "email")
})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(max = 20)
private String username;
@NotBlank
@Size(max = 50)
@Email
private String email;
@NotBlank
@Size(max = 120)
private String password;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable( name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public User() {
}
public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
Implement Repositories
Now, each model above needs a repository for persisting and accessing data. In repository package, let’s create 2 repositories.
UserRepository
There are 3 necessary methods that JpaRepository supports.
package com.bezkoder.springjwt.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bezkoder.springjwt.models.User;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
}
RoleRepository
This repository also extends JpaRepository and provides a finder method.
package com.bezkoder.springjwt.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bezkoder.springjwt.models.ERole;
import com.bezkoder.springjwt.models.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(ERole name);
}
Configure Spring Security
Without WebSecurityConfigurerAdapter
WebSecurityConfigurerAdapter is deprecated from Spring 2.7.0. More details at:
WebSecurityConfigurerAdapter Deprecated in Spring Boot.
In security package, create WebSecurityConfig class.
WebSecurityConfig.java
package com.bezkoder.springjwt.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.bezkoder.springjwt.security.jwt.AuthEntryPointJwt;
import com.bezkoder.springjwt.security.jwt.AuthTokenFilter;
import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl;
@Configuration
@EnableGlobalMethodSecurity(
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true)
public class WebSecurityConfig {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated();
http.authenticationProvider(authenticationProvider());
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
With WebSecurityConfigurerAdapter
In security package, create WebSecurityConfig class that extends WebSecurityConfigurerAdapter.
WebSecurityConfig.java
package com.bezkoder.springjwt.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.bezkoder.springjwt.security.jwt.AuthEntryPointJwt;
import com.bezkoder.springjwt.security.jwt.AuthTokenFilter;
import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
Let me explain the code above.
– @EnableWebSecurity allows Spring to find and automatically apply the class to the global Web Security.
– @EnableGlobalMethodSecurity provides AOP security on methods. It enables @PreAuthorize, @PostAuthorize, it also supports JSR-250. You can find more parameters in configuration in Method Security Expressions.
– We override the configure(HttpSecurity http) method from WebSecurityConfigurerAdapter interface. It tells Spring Security how we configure CORS and CSRF, when we want to require all users to be authenticated or not, which filter (AuthTokenFilter) and when we want it to work (filter before UsernamePasswordAuthenticationFilter), which Exception Handler is chosen (AuthEntryPointJwt).
– Spring Security will load User details to perform authentication & authorization. So it has UserDetailsService interface that we need to implement.
– The implementation of UserDetailsService will be used for configuring DaoAuthenticationProvider by AuthenticationManagerBuilder.userDetailsService() method.
– We also need a PasswordEncoder for the DaoAuthenticationProvider. If we don’t specify, it will use plain text.
Implement UserDetails & UserDetailsService
If the authentication process is successful, we can get User’s information such as username, password, authorities from an Authentication object.
Authentication authentication =
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password)
);
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// userDetails.getUsername()
// userDetails.getPassword()
// userDetails.getAuthorities()
If we want to get more data (id, email…), we can create an implementation of this UserDetails interface.
security/services/UserDetailsImpl.java
package com.bezkoder.springjwt.security.services;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.bezkoder.springjwt.models.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String email;
@JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserDetailsImpl(Long id, String username, String email, String password,
Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static UserDetailsImpl build(User user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toList());
return new UserDetailsImpl(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getPassword(),
authorities);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
}
Look at the code above, you can notice that we convert Set<Role> into List<GrantedAuthority>. It is important to work with Spring Security and Authentication object later.
As I have said before, we need UserDetailsService for getting UserDetails object. You can look at UserDetailsService interface that has only one method:
public interface UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
So we implement it and override loadUserByUsername() method.
security/services/UserDetailsServiceImpl.java
package com.bezkoder.springjwt.security.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bezkoder.springjwt.models.User;
import com.bezkoder.springjwt.repository.UserRepository;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return UserDetailsImpl.build(user);
}
}
In the code above, we get full custom User object using UserRepository, then we build a UserDetails object using static build() method.
Filter the Requests
Let’s define a filter that executes once per request. So we create AuthTokenFilter class that extends OncePerRequestFilter and override doFilterInternal() method.
security/jwt/AuthTokenFilter.java
package com.bezkoder.springjwt.security.jwt;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl;
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtils jwtUtils;
@Autowired
private UserDetailsServiceImpl userDetailsService;
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
String username = jwtUtils.getUserNameFromJwtToken(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception e) {
logger.error("Cannot set user authentication: {}", e);
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) {
String headerAuth = request.getHeader("Authorization");
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring(7, headerAuth.length());
}
return null;
}
}
What we do inside doFilterInternal():
– get JWT from the Authorization header (by removing Bearer prefix)
– if the request has JWT, validate it, parse username from it
– from username, get UserDetails to create an Authentication object
– set the current UserDetails in SecurityContext using setAuthentication(authentication) method.
After this, everytime you want to get UserDetails, just use SecurityContext like this:
UserDetails userDetails =
(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// userDetails.getUsername()
// userDetails.getPassword()
// userDetails.getAuthorities()
Create JWT Utility class
This class has 3 funtions:
- generate a
JWTfrom username, date, expiration, secret - get username from
JWT - validate a
JWT
security/jwt/JwtUtils.java
package com.bezkoder.springjwt.security.jwt;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.bezkoder.springjwt.security.services.UserDetailsImpl;
import io.jsonwebtoken.*;
@Component
public class JwtUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
@Value("${bezkoder.app.jwtSecret}")
private String jwtSecret;
@Value("${bezkoder.app.jwtExpirationMs}")
private int jwtExpirationMs;
public String generateJwtToken(Authentication authentication) {
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
return Jwts.builder()
.setSubject((userPrincipal.getUsername()))
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public String getUserNameFromJwtToken(String token) {
return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
}
Remember that we’ve added bezkoder.app.jwtSecret and bezkoder.app.jwtExpirationMs properties in application.properties file.
Handle Authentication Exception
Now we create AuthEntryPointJwt class that implements AuthenticationEntryPoint interface. Then we override the commence() method. This method will be triggerd anytime unauthenticated User requests a secured HTTP resource and an AuthenticationException is thrown.
security/jwt/AuthEntryPointJwt.java
package com.bezkoder.springjwt.security.jwt;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized");
}
}
HttpServletResponse.SC_UNAUTHORIZED is the 401 Status code. It indicates that the request requires HTTP authentication.
We’ve already built all things for Spring Security. The next sections of this tutorial will show you how to implement Controllers for our RestAPIs.
Define payloads for Spring RestController
Let me summarize the payloads for our RestAPIs:
– Requests:
- LoginRequest: { username, password }
- SignupRequest: { username, email, password }
– Responses:
- JwtResponse: { token, type, id, username, email, roles }
- MessageResponse: { message }
To keep the tutorial not so long, I don’t show these POJOs here.
You can find details for payload classes in source code of the project on Github.
Create Spring RestAPIs Controllers
Controller for Authentication
This controller provides APIs for register and login actions.
– /api/auth/signup
- check existing
username/email - create new
User(withROLE_USERif not specifying role) - save
Userto database usingUserRepository
– /api/auth/signin
- authenticate { username, pasword }
- update
SecurityContextusingAuthenticationobject - generate
JWT - get
UserDetailsfromAuthenticationobject - response contains
JWTandUserDetailsdata
controllers/AuthController.java
package com.bezkoder.springjwt.controllers;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bezkoder.springjwt.models.ERole;
import com.bezkoder.springjwt.models.Role;
import com.bezkoder.springjwt.models.User;
import com.bezkoder.springjwt.payload.request.LoginRequest;
import com.bezkoder.springjwt.payload.request.SignupRequest;
import com.bezkoder.springjwt.payload.response.JwtResponse;
import com.bezkoder.springjwt.payload.response.MessageResponse;
import com.bezkoder.springjwt.repository.RoleRepository;
import com.bezkoder.springjwt.repository.UserRepository;
import com.bezkoder.springjwt.security.jwt.JwtUtils;
import com.bezkoder.springjwt.security.services.UserDetailsImpl;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Username is already taken!"));
}
if (userRepository.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: Email is already in use!"));
}
// Create new user's account
User user = new User(signUpRequest.getUsername(),
signUpRequest.getEmail(),
encoder.encode(signUpRequest.getPassword()));
Set<String> strRoles = signUpRequest.getRole();
Set<Role> roles = new HashSet<>();
if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
} else {
strRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new RuntimeException("Error: Role is not found."));
roles.add(userRole);
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}
Controller for testing Authorization
There are 4 APIs:
– /api/test/all for public access
– /api/test/user for users has ROLE_USER or ROLE_MODERATOR or ROLE_ADMIN
– /api/test/mod for users has ROLE_MODERATOR
– /api/test/admin for users has ROLE_ADMIN
Do you remember that we used @EnableGlobalMethodSecurity(prePostEnabled = true) for WebSecurityConfig class?
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig { ... }
Now we can secure methods in our Apis with @PreAuthorize annotation easily.
controllers/TestController.java
package com.bezkoder.springjwt.controllers;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/test")
public class TestController {
@GetMapping("/all")
public String allAccess() {
return "Public Content.";
}
@GetMapping("/user")
@PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
public String userAccess() {
return "User Content.";
}
@GetMapping("/mod")
@PreAuthorize("hasRole('MODERATOR')")
public String moderatorAccess() {
return "Moderator Board.";
}
@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String adminAccess() {
return "Admin Board.";
}
}
Run & Test
Run Spring Boot application with command: mvn spring-boot:run
Tables that we define in models package will be automatically generated in Database.
If you check MySQL database for example, you can see things like this:
mysql> describe users;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| email | varchar(50) | YES | UNI | NULL | |
| password | varchar(120) | YES | | NULL | |
| username | varchar(20) | YES | UNI | NULL | |
+----------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql> describe roles;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
mysql> describe user_roles;
+---------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------+------+-----+---------+-------+
| user_id | bigint(20) | NO | PRI | NULL | |
| role_id | int(11) | NO | PRI | NULL | |
+---------+------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
We also need to add some rows into roles table before assigning any role to User.
Run following SQL insert statements:
INSERT INTO roles(name) VALUES('ROLE_USER');
INSERT INTO roles(name) VALUES('ROLE_MODERATOR');
INSERT INTO roles(name) VALUES('ROLE_ADMIN');
Then check the tables:
mysql> select * from roles;
+----+----------------+
| id | name |
+----+----------------+
| 1 | ROLE_USER |
| 2 | ROLE_MODERATOR |
| 3 | ROLE_ADMIN |
+----+----------------+
3 rows in set (0.00 sec)
Register some users with /signup API:
- admin with
ROLE_ADMIN - mod with
ROLE_MODERATORandROLE_USER - zkoder with
ROLE_USER

Our tables after signup could look like this.
mysql> select * from users;
+----+--------------------+--------------------------------------------------------------+----------+
| id | email | password | username |
+----+--------------------+--------------------------------------------------------------+----------+
| 1 | admin@bezkoder.com | $2a$10$mR4MU5esBbUd6JWuwWKTA.tRy.jo4d4XRkgnamcOJfw5pJ8Ao/RDS | admin |
| 2 | mod@bezkoder.com | $2a$10$VcdzH8Q.o4KEo6df.XesdOmXdXQwT5ugNQvu1Pl0390rmfOeA1bhS | mod |
| 3 | user@bezkoder.com | $2a$10$c/cAdrKfiLLCDcnXvdI6MumFMthIxVCDcWjp2XcRqkRfdzba5P5.. | user |
+----+--------------------+--------------------------------------------------------------+----------+
3 rows in set (0.00 sec)
mysql> select * from roles;
+----+----------------+
| id | name |
+----+----------------+
| 1 | ROLE_USER |
| 2 | ROLE_MODERATOR |
| 3 | ROLE_ADMIN |
+----+----------------+
3 rows in set (0.00 sec)
mysql> select * from user_roles;
+---------+---------+
| user_id | role_id |
+---------+---------+
| 2 | 1 |
| 3 | 1 |
| 2 | 2 |
| 1 | 3 |
+---------+---------+
4 rows in set (0.00 sec)
Access public resource: GET /api/test/all

Access protected resource: GET /api/test/user

Login an account: POST /api/auth/signin

Access ROLE_USER resource: GET /api/test/user

Access ROLE_MODERATOR resource: GET /api/test/mod

Access ROLE_ADMIN resource: GET /api/test/admin

Solve Problem: javax.validation cannot be resolved
For Spring Boot 2.3 and later, you can see the compile error:The import javax.validation cannot be resolved
It is because Validation Starter no longer included in web starters. So you need to add the starter yourself.
– For Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
– For Gradle:
dependencies {
...
implementation 'org.springframework.boot:spring-boot-starter-validation'
}
Solve Problem with JDK 14
If you run this Spring Boot App with JDK 14 and get following error when trying to authenticate:
FilterChain java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter
Just add following dependency to pom.xml:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
</dependency>
Everything’s gonna work fine.
Conclusion
Congratulation!
Today we’ve learned so many interesting things about Spring Security and JWT Token based Authentication in just a Spring Boot example.
Despite we wrote a lot of code, I hope you will understand the overall architecture of the application, and apply it in your project at ease.
For understanding the architecture deeply and grasp the overview more easier:
Spring Boot Architecture for JWT with Spring Security
You should continue to know how to implement Refresh Token:
Spring Boot Refresh Token with JWT example
Or visit The example that uses HttpOnly Cookies instead.
You can also know how to deploy Spring Boot App on AWS (for free) with this tutorial.
Happy learning! See you again.
Fonte: Spring Boot Token based Authentication with Spring Security & JWT – BezKoder
