Understanding the React/SpringBoot Authentication Flow – Explained

In this tutorial, you will understand the how authentication works between React UI and SpringBoot backend.

What You will Learn

  • How users are authenticated from React to SpringBoot
  • User login with a React form
  • User registration in a React form
  • User logout
  • Adding credentials to request header using interceptors
  • Adding and removing data from local storage (cookies or session variable)

Content

  1. The User Registration Flow
  2. The User Login Flow
  3. Accessing Protected Resources
  4. User Logout Flow

Here are the Step below:

1. User Registration Flow

  • User fills and submits the registration form (Sign Up form).
  • Registration data (firstname, lastname, username and password) is sent via the request body to the /register endpoint.
  • The UserRepository saves the data to the Users table in the database
  • A  registration success response with a status code of 200(Ok) or 201(created is sent back to React
  • The Registration page redirects to a RegistrationSuccessful page with a link to the login page
  • User clicks on the link to go back to the login page

 

2. User Login Flow

Now that the user has been registered:

  • he now has a username and password to be able to login. Here are the steps:
  • User enters his username and password to the login form
  • The username and password is send via the Request body to the /login endpoint
  • The authenticate function is called which checks the user details against the database record
  • If authentication is successful, an authentication successful message is sent back with a 200(ok) status code
  • The user credentials is saved to local storage (cookie or session storage)
  • (Optionally) A global state called isUserAuthenticated is set to true.

 

3. Accessing Protected Resources

Since the user is now logged in,

  • he now tries to access the protected page which should display a list of products
  • The page triggers an effect hook which makes a request to the /products endpoint
  • The interceptor intercepts this request, checks for the user credentials in the local storage, retrieves and attaches this credential to the request before it is sent
  • List of products is received as a response and then displayed on the page.

 

4. User Logout Flow

  • User clicks on the logout button.
  • The user credentials is removed from the local storage (session or cookie)
  • Set the isUserAuthenticated global state to false

 

The flow is given below

React Spring Boot Authentication Workflow
User Avatar

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

Leave a Reply

Your email address will not be published. Required fields are marked *