In this tutorial, we will learn how to build a full stack Spring Boot + React.js Authentication example. The back-end server uses Spring Boot with Spring Security for JWT authentication and Spring Data for interacting with database. The front-end will be created with React, React Router & Axios. We’ll also use Bootstrap and perform Form validation.
Related Post:
– Spring Boot + React + MySQL: CRUD example
– Spring Boot + React + PostgreSQL: CRUD example
– Spring Boot + React + MongoDB: CRUD example
– React Upload/Download Files to/from Spring Boot Server
– React + Spring Boot: Pagination example
Run both projects in one place:
How to integrate React.js with Spring Boot
Contents
JWT (JSON Web Token)
Nowaday, JWT is popular for Authentication and Information Exchange. Instead of creating a Session (Session-based Authentication), 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.
Comparing with Session-based Authentication that need to store Session on Cookie, 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
Spring Boot React Authentication example
It will be a full stack, with Spring Boot for back-end and React.js 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)
Here are the screenshots of our system:
– Anyone can access a public page before logging in:
– A new User can signup:
– Form Signup validation:
– After signup is successful, User can login:
– After login, App directs the User to Profile page:
– UI for Moderator login (the navigation bar will change by authorities):
– If a User who doesn’t have Admin role tries to access Admin/Moderator Board page:
Demo Video
This is full React + Spring Boot JWT Authentication & Authorization 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.
There are 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, it add legal JWT 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 17 /11 /8
– Spring Boot 3 / 2 (with Spring Security, Spring Web, Spring Data JPA)
– jjwt
– PostgreSQL/MySQL
– Maven
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
React, React Router for Front-end
Overview
Let’s look at the diagram below.
– The App
component is a container with React Router (BrowserRouter
). Basing on the state, the navbar can display its items.
– Login
& Register
components have form for data submission (with support of react-validation
library). They call methods from auth.service
to make login/register request.
– auth.service
methods use axios
to make HTTP requests. Its also store or get JWT from Browser Local Storage inside these methods.
– Home
component is public for all visitor.
– Profile
component displays user information after the login action is successful.
– BoardUser
, BoardModerator
, BoardAdmin
components will be displayed by state user.roles
. In these components, we use user.service
to access protected resources from Web API.
– user.service
uses auth-header()
helper function to add JWT to HTTP header. auth-header()
returns an object containing the JWT of the currently logged in user from Local Storage.
If you want to use HttpOnly Cookie for storing JWT, please visit:
React.js Login & Registration example – JWT & HttpOnly Cookie
Technology
We’re gonna use these modules:
- React 18/17
- react-router-dom 6
- axios 0.27.2
- react-validation 3.0.7
- Bootstrap 4
- validator 13.7.0
Project Structure<
This is folders & files structure for this React application:
With the explanation in diagram above, you can understand the project structure easily.
Implementation
You can find step by step to implement this React App in the post:
React JWT Authentication (without Redux) example
Typescript version: React Typescript JWT Authentication (without Redux) example
Using Hooks:
React Hooks: JWT Authentication (without Redux) example
Or Redux:
React Redux: JWT Authentication & Authorization example
Or Hooks + Redux:
React Hooks + Redux: JWT Authentication & Authorization example
Further Reading
Fullstack:
– Spring Boot + React + MySQL: CRUD example
– Spring Boot + React + PostgreSQL: CRUD example
– Spring Boot + React + MongoDB: CRUD example
– React Upload/Download Files to/from Spring Boot Server
– React + Spring Boot: Pagination example
Source code
You can find source code for this tutorial at Spring Boot React Login Github.
Conclusion
Now we have an overview of Spring Boot React Authentication example using JWT, Spring Security along with flow for login and registration.
We also take a look at Spring Boot server architecture for JWT Authentication using Spring Sercurity & Spring Data JPA, as well as React.js project structure (React Router, Axios, without Redux) 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:
- Without Redux (javascript)
- Without Redux (typescript)
- Using Redux
- Hooks (without Redux)
- React Hooks + Redux
You will want to know how to run both projects in one place:
How to integrate React.js with Spring Boot
Happy learning, see you again!
hello sir
great tutorial..
I am getting Request failed with status code 500 error in React application.
and in spring-boot
Error: Role is not found.
at com.bezkoder.springjwt.controllers.AuthController.lambda$1(AuthController.java:99) ~[classes/:na]
Please Help ASAP.
Hi, you need to run SQL script to create 3 rows in roles table first.
hi
I am getting a error
Could not resolve placeholder ‘bezkoder.app.jwtSecret’ in value “${bezkoder.app.jwtSecret}”
what does error mean
ı am searching internet but could not get an answer
Hi,
bezkoder.app.jwtSecret
is defined in application.properties file.Thanks! Nice article. Is there source code available for this?
Hi, you can find Github source code inside tutorials I mention at Conclusion section 🙂
Hello Sir, I would like to have some help. I have an error like following:
Access to XMLHttpRequest at ‘http://localhost:8080/api/test/all’ from origin ‘http://localhost:8081’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I have already looked for solutions but no result, always the same error
Thanks
Thanks a lot… Sir
Thanks a lot… Sir
Thanks a lot… Sir
Awsome tutorial….Thanks a lot…Sir
However, I am not able to http://localhost:8081/user, it is showing “Error: Unauthorized” . Any suggestions would be appreciated.
Thanks in Advanced!
Hi, you can check the Header with correct
Authorization
header with Bearer token (for Spring Boot Server) instead ofx-access-token
header (for Node Express Server).Super straight forward example with excellent explanation and everything works like a charm. You have taught me a lot of things. I owe you a virtual beer 🙂 God bless you.
Hi Sir, The tutorial was a life saver… Thanks a lot for this.
However, I am not able to signup , it is showing “Error:Role not found” . Any suggestions would be appreciated.
Hi, you need to run SQL script to create records in
roles
table first.Hi , Thanks for replying, It works perfectly now.Thanks again for the code. Wish you health and happiness 🙂
Can you please give me an example on microservices
standard way of handling cookies with session details acrooss multiple module in microservices.
thanks in advance
Can you please do an example of Spring Boot + React: JWT authentication using httponly cookie with Spring Security?
Hi, I will do it when having time 🙂 Thanks for your suggestion.
hi, your fullstack tutorial is amazing!!!
I had an important question. when you sign up in the login page, the user details already had been saved in the database???
and if I want to enter a new user, how can I do it?
I’m trying to understand how JWT authentication fits into the picture with OAuth/OIDC and third-party identity providers such as Amazon Cognito.
My understanding with the above example is that the identity management is independent of whether it’s done internally (i.e. within a backend service such as Spring Boot) or it can be done with a third-party provider. Is this correct?
Therefore it would be possible to extend your example to have Cognito specific settings in the application.yml and in Spring Boot with classes that subclass WebMvcConfigurer to support it. I’d like to confirm if this is true also?
Good fullstack tutorial. Keep up your work.
Awsome tutorial !! Very helpful for beginners
This fullstack tutorial is in fact awesome with comprehensive practice.
Sir, can you explain how to restrict pages according to user roles ? I am stuck with that point. in your code WebSecurityConfig.java file –
you’re give all permit to rest URL –
(.anytMatchers("/api/test/**").permitAll())
but sir, I need to divide that URL according to user roles. I tried like this way but didn’t work. –(.anytMatchers("/api/test/**").hasAnyAuthority("ROLE_USER"))
.would you mind giving me a solution for that sir!
Thank you!
Hi, you can look at
TestController.java
where we use@PreAuthorize("hasRole('USER')")
.yes sir it was there. but how did that come from? how spring security recognize that is ‘USER’?
Awesome Tutorial!
Having read this tutorial and I thought it is very enlightening.
I appreciate you taking the time and energy to write this.
Many thanks for the tutorial!
Thanks!
I am a beginner programmer and found it very difficult to implement JWT Authentication. Reviewed a lot of sites and videos. Your resource is the best, everything is told in steps and everything is clear. Thank you very much for your work! Greetings from Russia 🙂
Source code please
Hi, you can find Github source code in the posts at Conclusion section 🙂
Any github repository will appreciate!!!
Hi, you can find the github source code in the posts at Conclusion section.
Hi! Great tutorial! I have a question, I am new to this, I can’t login the admin or moderator only user, is it me doing something wrong or? And after login, when I want to pass data from backend to frontend, do I always have to send token or once logged in I am safe to send data like in normal apps without authorization? Because when I did it, it said error unauthorized (I only tried to pass some data about user to which subject he can attend at faculty)
Man, you are a life saver!! you really helped me out here… But forgive me if this is a stupid question, how does the admin signup/signin? (i’m new to this)
I believe you sign up like normal account and then change your role in the database to get ADMIN privileges or you can create an OWNER (you will change in the database only once) and when through the GUI you will be able to control all users and their roles.
thank you so much
Is it secure to use Local Storage instead of HTTP only cookies? If I were to use HTTP only cookies instead, what would the SpringBoot-React implementation look like? Thank you very much for this helpful resource.
Hi, cloud you send to me source code?
How to download this code package. I did not find a link to download it.
In conclusion section there is code for back end only.. i want the source code with React part. Please provide the github link.
Did you actually visit the Post for React front-end?
excellent code but why no redux? would be interesting to see the change by using redux.
Hi, I’ve just written a tutorial using Redux for Authentication:
React Redux: Token Authentication example with JWT & Axios
Hi, is there link on github available somewhere on this webpage? It would help me a lot.
Hi, here you are:
– Backend: https://github.com/bezkoder/spring-boot-spring-security-jwt-authentication
– Frontend: https://github.com/bezkoder/react-jwt-auth
hye please tell me
i was working with spring boot and thymeleaf i used to use spring security to add authentication to my application but i have never heard of JWT because i was working with full stack spring application (no client side thymeleaf pages are sent by server not like react)
what i want to know is that. is it necessary to use JWT to link spring security authentication with react or i can do it someway like with thymeleaf
I am able to run two seperate servers. But how to connect both of them. Please help fast.
Great job is see.
Can you help with the source code?
Hi, the github source code can be found at next tutorials in Conclusion section 🙂
Please share source code.