Refresh the Auth Token periodically¶
Often JWT comes with a new challenge.
You have to refresh
the JWT token periodically using a token, named Refresh token.
A refresh token is a special kind of token used to obtain a renewed access token. You can request new access tokens until the refresh token is on the DenyList. Applications must store refresh tokens securely because they essentially allow a user to remain authenticated forever.
React Auth Kit implements an easy approach to integrate the refresh token.
You can either use the refresh token in your application or you can leave it.
API Builder¶
To build the refresh token API, you have to use createRefresh
function.
It is an identity function. It is mainly used for typechecking and mobility.
createRefresh¶
createRefresh(options) => refreshApi
Generate a refreshApi based on the options received
Arguments¶
options
(object): Takes a refresh object. It has 2 parameters
refreshApiCallback
(function): This is an API function. Inside this function, you have to add a network request API. See the detailsinterval
(number): The time interval in minutes, by which therefreshApiCallback
is called and the state is updated
Returns¶
A complete object of refresh token API. Add this object in the AuthProvider
as a prop to implement the feature.
import {createRefresh} from 'react-auth-kit'
const refreshApi = asynccreateRefresh({
interval: 10, // Refreshs the token in every 10 minutes
refreshApiCallback: async (param) => { // API container function
return {
isSuccess: true,
}
}
})
export default refreshApi
refreshApiCallback¶
The container for refresh API
Arguments¶
The function has only one argument, which is the object
of the latest state.
The object contains:
authToken
(string): The Auth tokenauthTokenExpireAt
(Date) : Expiring time of the Auth tokenrefreshToken
(string): The Refresh tokenrefreshTokenExpiresAt
(Date): Expiring time of the refresh tokenauthUserState
(object): The current User state
Returns¶
In side the function you have to return an object
of new auth state fetched by the API.
The return object must contain:
isSuccess
(boolean): If the network request is successful, then make ittrue
, otherwise make it false. If the value of this variable is false then the state will not changed, and it'll wait for the next timenewAuthToken
(string): The value of this variable will be the new auth token. So pass the new auth token here.newAuthTokenExpireIn
(number)(optional): New time limit in minutes, after which the auth token will expire. If you leave it, the old time limit will not be changed. So if you want to add more 10 minutes, then pass 10 here.newRefreshToken
(string)(optional): Pass the new refresh token here, if you want to refresh the refresh token itself.newRefreshTokenExpiresIn
(number)(optional): New time limit in minutes, after which the refresh token will expire. Works same asnewAuthTokenExpireIn
newAuthUserState
(object)(optional): Pass the new user state. If your API updates the user state, then use this, else leave it.
refreshApiCallback Example¶
{refreshApiCallback: async (
{ // arguments
authToken,
authTokenExpireAt,
refreshToken,
refreshTokenExpiresAt,
authUserState
}) => {
try {
const response = await axios.post("/refresh", {'refresh': refreshToken}, {
headers: {'Authorization': `Bearer ${authToken}`}}
)
return {
isSuccess: true,
newAuthToken: response.data.token,
newAuthTokenExpireIn: 10,
newRefreshTokenExpiresIn: 60
}
}
catch(error){
console.error(error)
return {
isSuccess: false
}
}
}
}
API Builder Example¶
This is the overall example of how to use createRefresh
. The example uses axios to make network request.
import axios from 'axios'
import {useAuthHeader, createRefresh} from 'react-auth-kit'
const refreshApi = createRefresh({
interval: 10, // Refreshs the token in every 10 minutes
refreshApiCallback: async (
{ // arguments
authToken,
authTokenExpireAt,
refreshToken,
refreshTokenExpiresAt,
authUserState
}) => {
try {
const response = await axios.post("/refresh", {'refresh': refreshToken}, {
headers: {'Authorization': `Bearer ${authToken}`}}
)
return {
isSuccess: true,
newAuthToken: response.data.token,
newAuthTokenExpireIn: 10,
newRefreshTokenExpiresIn: 60
}
}
catch(error){
console.error(error)
return {
isSuccess: false
}
}
}
})
export default refreshApi
Integration in Auth Provider¶
To add the refresh token feature, simply add the return value of createRefresh
function in the AuthProvider
as a prop.
import {AuthProvider} from 'react-auth-kit'
import refreshApi from "./refreshApi";
function App() {
return (
<AuthProvider
authName={"_auth"}
authType={"cookie"}
refresh={refreshApi}
>
<Routes/>
</AuthProvider>
);
}
Only use the return from createRefresh as the prop value
Using values other than the return of createRefresh
will cause the application to break.
So only use the return of createRefresh
as the prop value.
— 🔑 —
React Auth Kit is Apache 2.0 License code