React User Authentication Using JWT

In this article, we will learn how to use JWT authentication in react js

To authenticate a user, a client application must send a JSON Web Token (JWT) in the permission header of an HTTP request to your backend API.

You don’t have to create any code to handle authentication in your API because API Gateway validates the token on your behalf.

1. Make a configuration file for the API to utilise.

The file contains a list of all the constants that are utilised in various places and scenarios. For the time being, we only require the API SERVER address:

export const DUMMY_API = "http://localhost:5000/api/";

2. In the src folder, create a new folder called api.

3. Create an index.js file containing API settings.

import Axios from "axios";
import { DUMMY_API } from "../config/constant";

const axios = Axios.create({
  baseURL: `${DUMMY_API }`,
  headers: { "Content-Type": "application/json" },
});

axios.interceptors.request.use(
  (config) => {
    return Promise.resolve(config);
  },
  (error) => Promise.reject(error)
);

axios.interceptors.response.use(
  (response) => Promise.resolve(response),
  (error) => {
    return Promise.reject(error);
  }
);

export default axios;
});

4. Create a file called auth.js that contains all of the API requests.

import axios from "./index";

class AuthApi {

  static Login = (logindata) => {
    return axios.post(`users/login`, logindata);
  };

  // don't forget to add the register and logout methods
}

export default AuthApi;

5. Create a new context folder in the src directory.

const AuthContext = React.createContext(null);

export const AuthProvider = ({ userDummyData, children }) => {
  let [userFlag, setUserFlag] = React.useState(userDummyData);

  return (
    <AuthContext.Provider value={{ userFlag, setUserFlag }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => React.useContext(AuthContext);

6. The Context Provider and the App object must be connected.

const App = () => {
  // we get the user from the localStorage because that's where we will save their account on the login process
  let userData = localStorage.getItem("userData");
  userData = JSON.parse(userData);

  return (
    <AuthProvider userData={userData}>
      <Routes />
    </AuthProvider>
  );
};

export default App;

7. Protected Routes should be defined.

export const ProtectedRoute = ({..rest }) => {
  let { userData } = useAuth();

  if (!userData || !userData.token || userData.token === "") {
    return (
      // component which inform the user that they must be logged in
    );
  }

  // let user through if they're logged in
  return <Route {..rest} />;
};

8. The Auth Flow should be coded.

After you’ve identified the Auth Components, you can start working on the Authentication process. Consider the Login Component as an example:

const loginHandler = async (loginevent) => {
   if (loginevent) {
     event.preventDefault();
   }

   //handle exceptions like: no email entered, no password entered, here.

   try {
     let response = await AuthApi.Login({
       email,
       password,
     });
     if (response.data && response.data.success === false) {
       //display error coming from server
       return setLoginError(response.data.msg);
     }
     return setProfile(response);
   } catch (error) {
     //display error originating from server / other sources
     console.log(error);
     if (err.response) {
       return setLoginError(err.response.data.msg);
     }
     return setLoginError("There has been an error.");
   }
 };

SetProfile helper is called if the user credentials are valid, and the user information is saved in the app store.

const setProfile = (response) => {
  let userdummydata = { ...response.data.user };
  userdummydata.token = response.data.token;
  userdummydata = JSON.stringify(userdummydata);
  //setUser is imported from the useAuth React Context
  setUser(userdummydata);
  //also set the user in local storage
  localStorage.setItem("user", userdummydata);
  return history.push("/admin/dashboard");
};

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories