In this tutorial, we're gonna build a Spring Boot Login and Registration example (Rest API) that supports JWT with HttpOnly Cookies. You'll know:
- Appropriate Flow for User Login and Registration with JWT and Cookies
- Spring Boot Rest Api 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 MySQL Database
Full Article: Spring Boot Login example with JWT and MySQL
Overview of Spring Boot Login example
We will build a Spring Boot application in that:
- User can signup new account (registration), 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:
Methods | Urls | Actions |
---|---|---|
POST | /api/auth/signup | signup new account |
POST | /api/auth/signin | login an account |
POST | /api/auth/signout | logout the 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 is MySQL by configuring project dependency & datasource.
Flow of Spring Boot Login and Registration example
The diagram shows flow of how we implement User Registration, User Login and Authorization process.
A legal JWT must be stored in Cookies if Client accesses protected resources.
You will need to implement Refresh Token:
More details at: Spring Boot Refresh Token with JWT example
Spring Boot Rest API Server Architecture with Spring Security
You can have an overview of our Spring Boot Login example with the diagram below:
Now I will explain it briefly.
Spring Security
WebSecurityConfigurerAdapter
is the crux of our security implementation. It providesHttpSecurity
configurations to configure cors, csrf, session management, rules for protected resources. We can also extend and customize the default configuration that contains the elements below.UserDetailsService
interface has a method to load User by username and returns aUserDetails
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 aDaoAuthenticationProvider
(with help ofUserDetailsService
&PasswordEncoder
) to validateUsernamePasswordAuthenticationToken
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 adoFilterInternal()
method that we will implement parsing & validating JWT, loading User details (usingUserDetailsService
), checking Authorizaion (usingUsernamePasswordAuthenticationToken
).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 requestsTestController
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.6.1 (with Spring Security, Spring Web, Spring Data JPA)
- jjwt 0.9.1
- MySQL
- Maven 3.6.1
Project Structure
This is folders & files structure for our Spring Boot Login example:
security: we configure Spring Security & implement Security Objects here.
-
WebSecurityConfig
extendsWebSecurityConfigurerAdapter
-
UserDetailsServiceImpl
implementsUserDetailsService
-
UserDetailsImpl
implementsUserDetails
-
AuthEntryPointJwt
implementsAuthenticationEntryPoint
-
AuthTokenFilter
extendsOncePerRequestFilter
-
JwtUtils
provides methods for generating, parsing, validating JWT
controllers handle signup/login requests & authorized requests.
-
AuthController
: @PostMapping('/signup'), @PostMapping('/signin'), @PostMapping('/signout') -
TestController
: @GetMapping('/api/test/all'), @GetMapping('/api/test/[role]')
repository has interfaces that extend Spring Data JPA JpaRepository
to interact with MySQL Database.
-
UserRepository
extendsJpaRepository<User, Long>
-
RoleRepository
extendsJpaRepository<Role, Long>
models defines two main models for Authentication (User
) & Authorization (Role
). They have many-to-many relationship.
-
User
: id, username, email, password, roles -
Role
: 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).
For step by step instruction and Github, please visit:
Spring Boot Login example with JWT and MySQL
Further Reading
- Spring Security Reference
- In-depth Introduction to JWT-JSON Web Token
- Architecture: Spring Boot 2 JWT Authentication with Spring Security
Related Posts:
- Spring Boot, Spring Data JPA – Building Rest CRUD API example
- Spring Boot Pagination & Filter example | Spring JPA, Pageable
- CRUD GraphQL APIs example with Spring Boot, MySQL & Spring JPA
- Spring Boot Rest XML example – Web service with XML Response
- Spring Boot File upload example with Multipart File
- @RestControllerAdvice example in Spring Boot
- Spring Boot @ControllerAdvice & @ExceptionHandler example
- @DataJpaTest example for Spring Data Repositiory Unit Test
Deployment:
Fullstack CRUD App:
- Spring Boot + Vue.js example
- Angular 8 + Spring Boot example
- Angular 10 + Spring Boot example
- Angular 11 + Spring Boot example
- Angular 12 + Spring Boot example
- Angular 13 + Spring Boot example
- Angular 14 + Spring Boot example
- Angular 15 + Spring Boot example
- React + Spring Boot example
If you need a working front-end for this back-end, you can find Client App in the posts:
(just modify using Local Storage to HttpOnly Cookies)
- Vue
- Angular 8 / Angular 10 / Angular 11 / Angular 12 / Angular 13 / Angular 14 / Angular 15
- React / React Hooks / React + Redux