In this tutorial, I will show you how to build a full stack Angular 16 + Spring Boot Login and Registration with JWT example. The back-end server uses Spring Boot with Spring Security for JWT Authentication & Role based Authorization, Spring Data JPA for interacting with database. The front-end will be built using Angular 16 with HttpInterceptor & Form validation.
Related Posts:
– Angular 16 + Spring Boot: File upload/download example
– Spring Boot JWT Auth with MySQL/PostgreSQL
– Spring Boot JWT Auth with MongoDB
– Newer version: Angular 17 + Spring Boot: JWT Authentication & Authorization example
Fullstack CRUD Application:
– Angular 16 + Spring Boot + H2 example
– Angular 16 + Spring Boot + MySQL example
– Angular 16 + Spring Boot + PostgreSQL example
– Angular 16 + Spring Boot + MongoDB example
Contents
Angular 16 + Spring Boot JWT Authentication example
It will be a full stack, with Spring Boot for back-end and Angular 16 for front-end. The system is secured by Spring Security with JWT for Authentication and Authorization.
- User can signup new account, login with username & password.
- Role based Authorization (admin, moderator, user).
- Store JWT in HttpOnly Cookies.
Screenshots
Here are UI screenshots of our system.
– Anyone can access a public page before logging in:
– New user registration:
– Signup Form Validation:
More details about Form Validation at:
– Angular 16 Template Driven Forms Validation example
– Angular 16 Reactive Forms Validation example
– After signup is successful, User can login:
-Now User can access Profile page/ User page:
– HttpOnly Cookie sent automatically with HTTP Request:
– This is UI for mod:
– If a User who doesn’t have Admin role tries to access Admin Board page:
Demo
This is full Angular + Spring Boot JWT authentication demo (with form validation, check signup username/email duplicates, test authorization with 3 roles: Admin, Moderator, User).
In the video, we use Angular 10 and HTTP Authorization Header, but logic and UI are the same as this Angular version 16 and HttpOnly Cookie.
Flow for Authentication and Authorization
The diagram shows flow for User Registration process and User Login process.
It’s not too difficult to understand. We have 3 endpoints for authentication:
api/auth/signup
for User Registrationapi/auth/signin
for User Loginapi/auth/signout
for User Logout
This Angular Client uses JWT in Cookies while sending request to protected resources (Authorization).
Spring Boot & Spring Security Server
Overview
Our Spring Boot Application can be summarized in the diagram below:
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
To implement the server with concept above, we will use:
- Java 17 / 11 / 8
- Spring Boot 3 / 2 (with Spring Security, Spring Web, Spring Data JPA)
- jjwt
- MySQL/PostgreSQL/H2 – embedded database
- Maven
Project Structure
The structure of Spring Boot back-end project is pretty complicated:
security: we configure Spring Security & implement Security Objects here.
WebSecurityConfig
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 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, 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).
Implementation and Source code
You can find steps to implement this Spring Boot – Spring Security App (with Github) in the post:
Spring Boot JWT Auth example with JWT and H2 Database
For working with MySQL/PostgreSQL:
Spring Boot JWT Auth example with JWT and MySQL/PostgreSQL
Or MongoDB:
Spring Boot JWT Auth example with MongoDB
Before running the backend server, you need to add minor configuration:
/* In AuthController.java */
// @CrossOrigin(origins = "*", maxAge = 3600)
@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600, allowCredentials="true")
/* In TestController.java */
// @CrossOrigin(origins = "*", maxAge = 3600)
@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600, allowCredentials="true")
Angular 16 Client
Overview
Our Angular 16 App can be summarized in component diagram below:
Let’s try to understand it right now.
– The App
component is a container using Router
. It gets user user information from Browser Session Storage via storage.service
. Then the navbar now can display based on the user login state & roles.
– Login
& Register
components have form for submission data (with support of Form Validation). They use storage.service
for checking state and auth.service
for sending signin/signup requests.
– auth.service
uses Angular HttpClient ($http
service) to make authentication requests.
– every HTTP request by $http
service will be inspected and transformed before being sent by auth-interceptor
.
– Home
component is public for all visitor.
– Profile
component get user
data from Session Storage.
– BoardUser
, BoardModerator
, BoardAdmin
components will be displayed depending on roles
from Session Storage. In these components, we use user.service
to get protected resources from API (with JWT in HttpOnly Cookie).
Technology
- Angular 16
- RxJS 7
- Angular CLI 16
- Bootstrap 4
Project Structure
This is the folder structure of our Angular front-end project:
You can understand it properly without any explanation because we’ve looked at the overview before.
Implementation and Source code
You can find steps implement this Angular 16 Client (with Github) in the post:
Angular 16 JWT Authentication & Authorization example
Further Reading
Fullstack CRUD Application:
– Angular 16 + Spring Boot + H2 example
– Angular 16 + Spring Boot + MySQL example
– Angular 16 + Spring Boot + PostgreSQL example
– Angular 16 + Spring Boot + MongoDB example
Source Code
The complete source code for this tutorial can be found at Spring Boot + Angular Github.
Conclusion
Now we have an overview of Angular 16 Spring Boot Token based Authentication and Role based Authorization example using JWT, Spring Security, Angular HttpInterceptor along with flow for signup/login actions.
We also take a look at Spring Boot server architecture for JWT Authentication using Spring Sercurity & Spring Data JPA, as well as Angular project structure for building a front-end app working with JWT.
Next tutorials will show you more details about how to implement this interesting system (with Github):
– Back-end:
– Front-end: Angular 16 JWT Authentication & Authorization example
Happy learning, see you again!