In this tutorial, I will show you how to build a full stack Angular 8 + Spring Boot JWT Authentication example. The back-end server uses Spring Boot with Spring Security for JWT authentication and Spring Data JPA for interacting with database. The front-end will be built using Angular 8 with HttpInterceptor & Form validation.
Newer versions:
– Angular 10 + Spring Boot: JWT Authentication & Authorization example
– Angular 11 + Spring Boot: JWT Authentication & Authorization example
– Angular 12 + Spring Boot: JWT Authentication & Authorization example
– Angular 13 + Spring Boot: JWT Authentication & Authorization example
– Angular 14 + Spring Boot: JWT Authentication & Authorization example
– Angular 15 + Spring Boot: JWT Authentication & Authorization example
Related Posts:
– Angular 8 + Spring Boot + MySQL CRUD example
– Angular 8 + Spring Boot + PostgreSQL CRUD example
– Angular 8 + Spring Boot + MongoDB CRUD example
– Spring Boot, MongoDB: JWT Authentication with Spring Security
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 8 Spring Boot Authentication example
It will be a full stack, with Spring Boot for back-end and Angular 8 for front-end. The system is secured by Spring Security with JWT Authentication.
- User can signup new account, login with username & password.
- Authorization by the role of the User (admin, moderator, user)
Screenshots
Here are UI screenshots of our system.
– Anyone can access a public page before logging in:
– New user signups:
– 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 8 + Spring Boot JWT authentication demo (with form validation, check signup username/email duplicates, test authorization with 3 roles: Admin, Moderator, User):
Flow for User Registration and User Login
The diagram shows flow for User Registration process and User Login process.
I think 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.1.8.RELEASE (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 8 for Front-end
Overview
Our Angular 8 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 8
– RxJS 6
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 8 App in the post:
Angular 8 JWT Authentication with HttpInterceptor and Router
Newer versions:
– Angular 10 JWT Authentication example with Web Api
– Angular 11 JWT Authentication example with Web Api
– Angular 12 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
- Angular 8 + Spring Boot: File upload example
Fullstack CRUD App:
– Angular 8 + Spring Boot + MySQL example
– Angular 8 + Spring Boot + PostgreSQL example
– Angular 8 + Spring Boot + MongoDB example
Newer versions:
– Angular 10 + Spring Boot: JWT Authentication & Authorization example
– Angular 11 + Spring Boot: JWT Authentication & Authorization example
– Angular 12 + Spring Boot: JWT Authentication & Authorization example
– Angular 13 + Spring Boot: JWT Authentication & Authorization example
– Angular 14 + Spring Boot: JWT Authentication & Authorization example
– Angular 15 + Spring Boot: JWT Authentication & Authorization 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 8 Spring Boot Authentication 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 with Spring Boot Rest API
Happy learning, see you again!
Good tutorial, keep up the pleasant work.
Hi there, I enjoy reading through your tutorial. Thanks!
I read this tutorial fully, it’s awesome article.
I was able to find good practice from your tutorials!
hi, i want to set role from angular but it keep showing this error :
Cannot deserialize instance of `java.util.HashSet` out of VALUE_STRING token
I know role shouldn’t be a String but couldn’t find a solution to pass
I have found this tutorial useful and it has helped me a lot. Great job!
java.lang.RuntimeException: Error: Role is not found.
I am getting null for the role in java server side controller class, and i am unable to register any user
Hi, you need to use SQL to create 3 roles first 🙂
Hi, could you help me please? How can i do to the user choose the role while while signing up?
Hi, you can make an input and add
role
array to the payload of HTTP request.hi, i want to set role from angular but it keep showing this error :
Cannot deserialize instance of `java.util.HashSet` out of VALUE_STRING token
I know role shouldn’t be a String but couldn’t find a solution to pass : “role”: [“admin”]
any tips ?
got it thank you anyway
Hi, how did you do it?
When I try to signup it show null pointer exception. Can you help me please?
Good morning, when i try to delete a user by his id
it shows me this error msg: Cannot delete or update a parent row: a foreign key constraint fails..
any solutions pls ?
Hi,
Can you please help me:
I run your project and it still ok. But I found on my eclipse log that:
io.jsonwebtoken.SignatureException: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
It has this error. Can you help me fix this
Hi,
Wonderful tutorial. Very helpful for beginners like me
Thanks a lot
Hi,
Imagine this application in a production environment. Apache for Frontend (Angular) and Wildfly for Backend (Springboot). My doubt is who makes the api REST calls to Backend, browser or Web Server (Apache)? Do you know some article to go deeper into the subject?
Congrats and thanks by the post.
Cheers.
Please send source code to
[email protected]
Hi, you can find Github source code in the posts mentioned at Conclusion section 🙂
I’m getting this error can u help me out,plz
“Validation failed for object=’loginRequest’. Error count: 1”
Hi,
The JWT token that I receive in UI, is not the full token That I receive on calling the REST api through POSTMAN.
For example :
POSTMAN token : “accessToken”: “eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzb20iLCJpYXQiOjE1OTY5ODI5MTQsImV4cCI6MTU5NzA2OTMxNH0.Vx7915pjE96cJ9KQ_kAOtfgnmysED5wPYCkIR6582nDvxuBjWF3yo34ZajIxosI6kCimS1kZ5NauO8MLsv0MwQ”
Token in UI : eyJhbGciOiJIUzUxMiJ9 … ZkoK_Y00wEmYwCvzQRJQ
How to display the full token in UI.
Hi, you can change these lines of code:
to:
{{ currentUser.accessToken }}
hi guys In Angular when i register with username, email, password So i want to set role for account but not defaut . How can I do it?
Hii.. How to change the role of the user from user to admin.
Admin can chance a user role as admin.. How it is possible?
Hello, I have a little problem with Swagger Integration. If I go to http://localhost:8080/swagger-ui.html , my console show this problem:
javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup!
Any suggestion please? thanks
When i try to open user board i will get Unauthorized error: Full authentication is required to access this resource.
This user has role ROLE_USER
is it possible to change my jwt token in a specific interval using access token and refresh token (with remember me feature ) concept in this existing project.
How can i add the feature to “keep me logged in” even after closing the browser.
Hi, you can use local Storage instead of session Storage.
could you please share the source code to add the “remember me” feature in the existing project.
Hey when I run the code, Im getting an unauthorized access error. Any advice
hi there could you please send the source code, my name is Melany Cordova and my email address is [email protected]
Here you are:
– https://github.com/bezkoder/spring-boot-spring-security-jwt-authentication
– https://github.com/bezkoder/angular-8-jwt-authentication
ERROR 11876 — [nio-8080-exec-7] c.b.s.security.jwt.AuthEntryPointJwt : Unauthorized error: Full authentication is required to access this resource
what might be wrong?
Hi, maybe the HTTP request Header was wrong.
Notice that you need to modify the code in
app/_helpers/auth.interceptor.js
to work with Spring Boot Server:Hi BezKoder,
You are great man. Its save a lot of time to the base project. I have followed your tutorials. It gives me a clear picture that how can I make more secure my application with Angular 8. I have subscribed to your youtube channel and I see a lot of good content over there. Good job man.
Hi, Very good tutorial about this topic. Congrats.
Where I can find source code? Is there any GitHub repo? Thx
Hi, you can find github source code for backend and frontend in the tutorials I mentioned in Conclusion section 🙂
cool i need your help !!! [email protected]
Hi, please write your issue here 🙂
Hi, can you please tell me how to signup ADMIN or Mod ADMIN just like the Users
Hi, you can add
role: ["admin"]
in payload for signup new Admin 🙂Hello, where can we find the source code on GitHub ?
Hi, there are links I embed in the tutorial for backend and frontend.
Bonjour,
j’ai obtient le problème suivant
Access to XMLHttpRequest at ‘http://localhost:8080/api/auth/signin’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
Malgré que j’ai ajouté au niveau de l’api rest le code suivant;@CrossOrigin(origins = “http://localhost:4200” ,allowedHeaders = “*”,allowCredentials = “true”)
Quelqu’un peut m’aider?
Hi, the server you used configures CORS for port 8081, so you have to run this Angular client with command:
ng serve --port 8081
instead.I like the app, but by no means do I register constantly I get the following message: “Signup failed!
Error: Role is not found. “The roll table is populated.
Thanks
Hi, did you insert 3 rows into roles table using SQL command?
send the source plz [email protected]
Hi, you can find source code in these tutorials:
– Frontend
– Backend
What if we are using MongoDB ?
Hi, I’ll write a tutorial for Spring JWT with MongoDB when having time.
thanks for this tutorial. this is so good :3
How can I develop this with some functions CRUD ?
Could you give me advices
Hi, you can read this article:
Angular 8 + Spring Boot example: Build a CRUD App
In controller methods, use
@PreAuthorize
annotation.More details at: Spring Boot Token based Authentication with Spring Security & JWT
Hi bezkoder,
Your tutorial really help a lot. I just want to ask about the database design because I don’t think if I made it correctly. It always says “error”: “Unsupported Media Type”,
Could help me with this.
Hi, which content-type did you send to the server?
Thank you for replying on my need bezkoder. I just want to see how to design the database clearly with a UI like dbeaver or sql management studio because I’m confused because I always work on frontend.Could you help me with this,like sending screenshots or snippets? (Database design for the 3 tables)
What are the columns, foreign keys, and relationships? Thanks.
Here you are 🙂
Thank you bezkoder for the help.
You’re welcome 🙂
Hi , can you please share the source code ? want to run it once…
Hi, you can find them from links I embeded in the tutorials (Implementation sections).
thanks a lot bezkoder… i liked your source code…its running as mentioned in the tutorials…
do you have anything good with search like amazon???
I will write the tutorial when having time. Thanks for your suggestion 🙂
Also, file upload, save it to file system, keep the reference in db and then fetch and show using angular & spring boot 🙂
Hi, thank you for this Spring Boot & Angular 8 Authentication tutorial. Please make a Tutorial for OAuth2.
Very nice tutorial. Subscribed and liked in your youtube chanel. Please send me source code [email protected].
Tnx
Hi, you can visit the links in this tutorial for explanation and source code.
Thank you!