In this tutorial, I will show you how to build a full stack Angular 12 + Spring Boot JWT Authentication 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 12 with HttpInterceptor & Form validation.
Related Posts:
– Angular 12 + Spring Boot: CRUD example
– Angular 12 + Spring Boot: File upload example
– Spring Boot, MongoDB: JWT Authentication with Spring Security
Newer versions:
– Angular 13 + Spring Boot: JWT Authentication & Authorization example
– Angular 14 + Spring Boot: JWT Authentication & Authorization example
– Angular 15 + Spring Boot: JWT Authentication & Authorization example
Contents
JWT (JSON Web Token)
JWT is popular for Authentication and Information Exchange. Server encodes data into a JSON Web Token and send it to the Client. The Client saves the JWT, then every Request from Client to protected routes or resources should be attached that JWT (commonly at header). The Server will validate that JWT and return the Response.
The big advantage of JWT (Token-based Authentication) is that we store the Token on Client side: Local Storage for Browser, Keychain for IOS and SharedPreferences for Android… So we don’t need to build another backend project that supports Native Apps or an additional Authentication module for Native App users.
There are three important parts of a JWT: Header, Payload, Signature. Together they are combined to a standard structure: header.payload.signature
.
The Client typically attact JWT in Authorization header with Bearer prefix:
Authorization: Bearer [header].[payload].[signature]
For more details, you can visit:
In-depth Introduction to JWT-JSON Web Token
Angular 12 Spring Boot Authentication example
It will be a full stack, with Spring Boot for back-end and Angular 12 for front-end. The system is secured by Spring Security with JWT Authentication.
- User can signup new account, login with username & password.
- Role based Authorization (admin, moderator, user)
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 12 Form Validation example (Reactive Forms)
– After signup is successful, User can login:
-Loggedin User can access Profile page/ User page:
– This is UI for admin:
– If a User who doesn’t have Admin role tries to access Admin/Moderator 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 for Client, but logic and UI are the same as this Angular version 12.
Flow for User Registration and User Login
The diagram shows flow for User Registration process and User Login process.
It’s not too difficult to understand. We have 2 endpoints for authentication:
api/auth/signup
for User Registrationapi/auth/signin
for User Login
If Client wants to send request to protected data/endpoints, a legal JWT must be added to HTTP Authorization Header.
Spring Boot & Spring Security for Back-end
Overview
Our Spring Boot Application can be summarized in the diagram below:
Let me explain it.
Spring Security
– WebSecurityConfigurerAdapter
is the crux of our security implementation. It provides HttpSecurity
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 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 unauthorized error and return a 401 when Clients access protected resources without authentication.
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.
Technology
To implement the server with concept above, we will use:
– Java 8
– Spring Boot 2 (with Spring Security, Spring Web, Spring Data)
– jjwt 0.9.1
– PostgreSQL/MySQL
– Maven 3.6.1
Project Structure
The structure of Spring Boot back-end project is pretty complicated:
You can see that there are 5 packages:
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(‘/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.
UserRepository
extendsJpaRepository
RoleRepository
extendsJpaRepository
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
You can find step by step to implement this Spring Boot – Spring Security App in the post:
Secure Spring Boot App with Spring Security & JWT Authentication
For working with MongoDB:
Spring Boot, MongoDB: JWT Authentication with Spring Security
Or PostgreSQL:
Spring Boot, Spring Security, PostgreSQL: JWT Authentication example
Angular 12 for Front-end
Overview
Our Angular 12 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 token & user information from Browser Session Storage via token-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 token-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.
Technology
– Angular 12
– RxJS 6
– 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
You can find step by step to implement this Angular 12 App in the post:
Angular 12 JWT Authentication example with Web Api
If you want to store JWT in HttpOnly Cookie, please visit:
Angular 12 JWT Authentication & Authorization with HttpOnly Cookie
Other versions:
– Angular 8 JWT Authentication example with Web Api
– Angular 10 JWT Authentication example with Web Api
– Angular 11 JWT Authentication example with Web Api
– Angular 13 JWT Authentication example with Web Api
– Angular 14 JWT Authentication example with Web Api
– Angular 15 JWT Authentication example with Web Api
Further Reading
- Spring Boot: Spring Security
- In-depth Introduction to JWT-JSON Web Token
- Spring Boot + Angular 12 CRUD 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 12 Spring Boot 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:
– Back-end:
– Front-end:
You will want to know how to run both projects in one place:
How to Integrate Angular 12 with Spring Boot Rest API
Fullstack:
– Angular + Spring Boot + MySQL example
– Angular + Spring Boot + PostgreSQL example
– Angular + Spring Boot + MongoDB example
– Angular 12 + Spring Boot: File upload example
Newer versions:
– Angular 13 + Spring Boot: JWT Authentication & Authorization example
– Angular 14 + Spring Boot: JWT Authentication & Authorization example
– Angular 15 + Spring Boot: JWT Authentication & Authorization example
Happy learning, see you again!
hey please sir How can I get the data from a table that has two primary keys from two entity classes?
The data of table user_roles , because im not able to delete a line on table user without deleting it first on table user_roles .
Very good tutorial sir, very detailed. But can you please do CRUD with users within this project? Much appreciate!
Yess ive been suffering for almost 10 days trying to add the crud to this project , if u are in we can try to do it together i already did the add and search buttons , update too the request work on postman but it does not work with angular .
hey man this is really good and iam a bit new to this can you explain to me how to set the role when making a registration or you do it directly in the db ?
Hi, currently mod and admin roles are set directly using HTTP POST request (see backend tutorial for details). You can set the role when registering new user by adding a roles field (array) on client side submit form.
hello , can you help me i want that ADMIN can add mod ?
hello ,
i want to validate username and password from database using angular without jwt token.
Hi, thanks a lot. I want to know if i can use .netcore for the back-end. thanks
Hi before angular 12 I use this.userService.getUser(this.authService.decodedToken.nameid) but in angular 12 my token wasn’t decoded what can I do
Hi, you can read this tutorial: Angular 12 Login and Registration example with JWT & Web Api
Hi, thanks a lot for these tutorials and sharing your knowledge, truly appreciate it!
The tutorials are really hands on and few of the best I have seen!
For this particular one though, I couldn’t see the code repo attached, please could you share the github link?
Thanks
Hi, you can find Github link for backend and frontend in the tutorials that I mention at Conclution section.
Hi, sorry to bother you but i have a problem really don’t know how to do it.
for tutorial Angular + Jwt +SpingBoot, in auth.interceptor.ts file
you say that if use Sping Boot backend, it should be : const TOKEN_HEADER_KEY = ‘Authorization’;
and for Node.js back-end we need add this : const TOKEN_HEADER_KEY = ‘x-access-token’;
so i want to know how should i add in Django back-end
really really thank you!!!
Hi, it depends on which front-end header you use to shake hand with back-end.
For example, I check
x-access-token
in Node.js andx-access-token
for Spring Boot server.