Authenticate users in React app with JWT based authentication
React Context and Hooks based Authentication
Package for React Apps
npm install --save react-auth-jwt
AuthProvider
relies on the context feature of React to pass the Auth
down to the components, so you need to make sure that AuthProvider
is a parent of the Routing components
. You can learn more about this in the API section.
import {AuthProvider} from "react-auth-jwt"
...
<AuthProvider authCookieName={"cookie"}
authTimeCookieName={"timecookie"}
stateCookieName={"statecookie"}
cookieDomain={window.location.hostname}
cookieSecure={window.location.protocol === "https:"}>
<RouteComponent />
</AuthProvider>
PrivateRoute
relies on react-router-dom same as the Route
component of React Router. It creates a Route to an Authentication
based component. If the user is not authenticated, it will redirect to login
Page. You can learn more about this in the API section.
import {BrowserRouter, Route} from "react-router-dom"
import {PrivateRoute} from "react-auth-jwt"
...
<BrowserRouter>
<Route component={LoginComponent} path={LOGIN_URL} exact/>
...
<PrivateRoute Component={DashboardComponent} path={DASHBOARD_URL} loginPath={LOGIN_URL} exact/>
</BrowserRouter>
useSignIn
is a function api, relies on React Hooks. It logs in the user and stores the JWT token
and expiresIn
time in minutes
. Implement the useSignIn
function on login pipeline i.e in login api response
. You can learn more about this in the API section.
Example with fetch
:
import React from 'react'
import {useSignIn} from "react-auth-jwt"
const AnyComponent = () => {
const signIn = useSignIn()
const do_login = async () => {
const res = await fetch("https://api.abc.xyz/login")
if (res.status === 200){
const res_json = res.json()
const jit_token = res_json.jit
const expiresIn = res_json.expiresIn
signIn(jit_token, expiresIn, {})
}
}
return (
<React.Fragment>
...
</React.Fragment>
)
}
Example with axios
:
import React from 'react'
import axios from 'axios'
import {useSignIn} from "react-auth-jwt"
const AnyComponent = () => {
const signIn = useSignIn()
const do_login = async () => {
const res = await axios.post("https://api.abc.xyz/login");
if (res.status === 200){
const res_json = res.data;
const jit_token = res_json.jit;
const expiresIn = res_json.expiresIn;
signIn(jit_token, expiresIn, {});
}
}
return (
<React.Fragment>
...
</React.Fragment>
)
}
useSignOut
is a function api, relies on React Hooks. It logouts the current user and clear all token. Implement the useSignOut
function on logout pipeline ex. on Logout Button Click. You can learn more about this in the API section.
import React from 'react';
import {useSignOut} from "react-auth-jwt";
const LogoutComponent = () => {
const signOut = useSignOut()
const logoutPipeline = () => {
signOut()
}
return (
<React.Fragment>
<button onClick={logoutPipeline}>Logout</button>
</React.Fragment>
)
}
logoutAuth
is a function api. It produces the authentication header
string for logged in user.
It returns Bearer: xxxxxx
string
Example with fetch
:
import React from "react";
import {useAuthHeader} from "react-auth-jwt";
const AnyComponent = async () => {
const authHeader = useAuthHeader()
const myInit = {
method: 'GET',
headers: {
'Authentication': authHeader()
}
}
const res = await fetch("https://api.abc.xyz/something", myInit);
if (res.status === 200){
const res_json = res.json()
...
}
return (
<React.Fragment>
...
</React.Fragment>
)
}
Example with axios
:
import React from "react";
import axios from "axios";
import {useAuthHeader} from "react-auth-jwt";
const AnyComponent = async () => {
const authHeader = useAuthHeader()
const do_something = async () => {
const res = await axios.get("https://api.abc.xyz/something",
headers: {
'Authentication': authHeader()
});
if (res.status === 200){
const res_json = res.json()
...
}
}
return (
<React.Fragment>
...
</React.Fragment>
)
}
Author: darkmatter18
Source Code: https://github.com/darkmatter18/react-auth-jwt
#reactjs #react #javascript