Poster for article with title Using Sanctum for authentication in React SPA: What you need to know

Using Sanctum to authenticate a React SPA

Due to the active development of technology, SPA applications are replacing the classic websites and Web links. The main difference between SPA and traditional websites is that the user does not receive static information in the form of text, graphics or tables, but dynamically structured data. 


In a new article we tell what SPA is, explain the procedure of using Sanctum for authentication in React SPA, and also tell about protection against CSRF attack using React.


React SPA: nature and benefits 


SPA (Single Page Application) a one-page site, through which users can perform any actions in a short period of time without reloading the page. That is, SPA technology allows users to perform the actions on the site with the same speed and convenience, as in the application. 


SPA is not a set of HTML documents, but the whole program complex, which is loaded to the user's device after the preliminary calculations. Thanks to this approach, developers are able to quickly and safely run complicated software complexes on any user gadgets.


The wide functionality of SPA-applications is achieved not only through the implementation of the classic layout language and markup of web documents HTML / CSS, but also through the use of modern software technologies such as React.js.


Advantages of SPA-applications 


  1. Cross-platform. SPA applications run on all devices and operating systems, which saves money on writing software for different platforms. 
  2. Universality. The user had only to enter the necessary address into the address bar in order to launch the application. No installation or update is required for the productive work of the application.
  3. Speed. All complex calculations take place on the server side, and on the user side there is only fast work without additional reloads or page updates.


Authentication in React Spa: Sanctum Laravel define


There are many solutions available for secure authorization in applications. One of them is Laravel Sanctum, which offers a lightweight authentication system for SPA applications. It allows users to create multiple API tokens for their account. 


The validity period of these tokens is set on the backend: it can be either a year or 30 minutes, but it can also be revoked by the user himself at any time. 


Laravel Sanctum offers this functionality by storing user API tokens in a single database table and authenticating incoming HTTP requests via an Authorization header. It must contain a valid API token. 


Sanctum also provides a simple authentication method for single-page applications (SPAs) that interact with the Laravel API. These SPAs can exist in the same repository as your Laravel application, or can be a completely separate repository.


How to prevent a CSRF attack


CSRF is cross-site request forgery. A CSRF vulnerability involves attacking a site with another rogue site or script that causes the user's browser to perform an unwanted action on a site where the user is logged in. This could be sending messages, changing passwords, transferring money from account to account, etc. 


The simplest example of a CSRF attack is when an intruder sends a phishing link to the user and the user clicks on it, leaves his details, after which the information becomes available to hackers. For example, a person authorized on the bank's site can click a phishing link and request to transfer money to the fraudster's account. The authorization causes the transfer request to be processed.


CSRF protection works by adding a hidden value field to the form, which only you and the user know. This ensures that it is the user and not someone else who sends the data.


The Laravel Sanctum package gives you the ability to protect your SPA application from cross-site request forgery. Let's take a look at how to set up CSRF protection.       


1.To authenticate your SPA, the "login" page must make a request to /sanctum/csrf-cookie to initialize CSRF protection for the application:


axios.get('/sanctum/csrf-cookie').then(response => {
    // Login...
});


2.During this request, Laravel will set an XSRF-TOKEN cookie containing the current CSRF token. 


3.This token should be passed in the X-XSRF-TOKEN header in subsequent requests. Some HTTP client libraries, such as Axios and Angular HttpClient, will do this automatically for you.


4.If your JavaScript HTTP library does not automatically set the value, you will need to manually set the X-XSRF-TOKEN header to match the XSRF-TOKEN cookie value set by that route.


Implementing Authentication 


Important. During the implementation of SPA authentication it is necessary to configure the application so that when loading any of the SPA pages, the front-end will check the presence of the token in the storage (we will save it in Local Storage and write it to the axios configuration). Otherwise we need to redirect the user to the authorization page. 


Let's proceed to write the code.


In the example below we will use the following tools:


  • React (v.18);
  • the Axios package for executing HTTP requests; 
  • the react-router-dom navigation library (v.6).


Required axios configurations:


export const servicesApi = axios.create({
 baseURL: "https://api.link",
 withCredentials: true,
 headers: {
  common: {
   "Accept": "application/json",
  }
 }
})


XMLHttpRequest responses from another domain cannot set cookies for their own domain unless they are withCredentials set to "true" before executing the request. 


The function for sending the request looks like this: 


const logIn = (email: string, password: string) => {
 return servicesApi.get('/sanctum/csrf-cookie').then(() => {
   return axios.post('auth/login', {
     email,
     password,
   })
 })
}


 Log in function algorithm execution with entered data for user authorization:


  1. Sending a request to Sanctum's API to form a CSRF token. 
  2. If successful, a request is made to our API for authorization. 
  3. If successful, we get the Bearer token from the backend. This is the key we need for authorization. 
  4. We enter the Bearer token into the axios configuration in the Authorization field with the Bearer prefix and save it in the browser's localStorage API. Saving it is very important, because otherwise it will be lost on reloading the page. 


Thus all subsequent requests to the API will be executed with the key set, in its absence the backend will return an error and the request will not be processed. 


After all the necessary actions, the key will be received, written to the axios configuration and stored in LocalStorage. Now, after making sure the user has entered the correct data, you can grant access to the protected page.


import { useNavigate } from "react-router-dom";

const installToken = (token: string) => axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
const navigate = useNavigate();

API.logIn(email, password)
 .then(({{data: {token}}) => {
   installToken(token)

   localStorage.setItem("token", token);

   navigate("/main")
 })


Stay tuned and subscribe to the RVA blog's newsletter for useful articles! More interesting and up-to-date articles on development, design and testing are waiting for you. Stay in the flow of technological and advanced trends with RVA Fintech Solutions. 


You may also be interested in ...

Poster for article - Explaining the Virtual DOM in React. Why it is used in React
01.11.2022 8:59

Explaining the Virtual DOM in React. Why it is used in React

If you are using React or learning React, you must have heard of the "Virtual DOM". Now what is a Virtual DOM, and why does React use it

Ready to Discuss
Your Project?

Fill the form and we’ll get in touch with you within 24 hours.