jwt-auth-react
Authenticate users in React app with JWT based authentication
React Context and Hooks
based Authentication
Package for React Apps
Install
npm install --save jwt-auth-react
Usage
1. AuthProvider
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 "jwt-auth-react"; ... <AuthProvider> <RouteComponent /></AuthProvider>
2. PrivateRoute
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 "jwt-auth-react"; ... <BrowserRouter> <Route = = /> ... <PrivateRoute = = =/></BrowserRouter>
3. loginAuth
loginAuth
is a function api, relies on React Hooks.
It logs in the user and stores the JWT token
and expiresIn
time in minutes
.
Impliment the loginAuth
function on login pipeline i.e in login api response
.
You can learn more about this in the API section.
Example with fetch
:
import loginAuth from "jwt-auth-react"; const do_login = const res = await ; if resstatus === 200 const res_json = res const jit_token = res_jsonjit; const expiresIn = res_jsonexpiresIn; ;
Example with axios
:
import axios from 'axios'import loginAuth from "jwt-auth-react"; const do_login = const res = await axios; if resstatus === 200 const res_json = resdata; const jit_token = res_jsonjit; const expiresIn = res_jsonexpiresIn; ;
4. logoutAuth
logoutAuth
is a function api, relies on React Hooks.
It logouts the current user and clear all token.
Impliment the logoutAuth
function on logout pipeline ex. on Logout Button Click.
You can learn more about this in the API section.
import react from 'react';import logoutAuth from "jwt-auth-react"; const logoutComponent = const logoutPipeline = return <button =>Logout</button>
5. authHeader
logoutAuth
is a function api. It produces the authentication header
string for logged in user.
It returns Bearer: xxxxxx
string
Example with fetch
:
import authHeader from "jwt-auth-react"; const do_something = const myInit = method: 'GET' headers: 'Authentication': const res = await ; if resstatus === 200 const res_json = res ...
Example with axios
:
import axios from "axios";import authHeader from "jwt-auth-react"; const do_something = const res = await axios; if resstatus === 200 const res_json = res ...
Maintainer
Need help? Feel free to contact me @ in2arkadipb13@gmail.com
License
Apache-2.0 © darkmatter18