Skip to content

Commit

Permalink
Add auto refresh for access tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
Justin Campbell committed Nov 25, 2020
1 parent 6c7b28e commit 2d60fef
Showing 1 changed file with 39 additions and 15 deletions.
54 changes: 39 additions & 15 deletions src/components/AuthProvider/AuthProvider.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState, createContext, useContext, useEffect } from "react";
import { useCookies } from "react-cookie";
import { refresh } from "../../auth/";
import decodeJWT from "jwt-decode";



Expand All @@ -22,23 +23,46 @@ export default function AuthProvider({ children }) {

const [cookies] = useCookies();

async function tryRefresh(csrf_refresh_token){
if (csrf_refresh_token === undefined){
return false;
}

const new_access_token = await refresh(csrf_refresh_token);
if (!new_access_token){
console.error("Failed to refresh access token.")
return false;
}

setToken(new_access_token);
setLoggedIn(true);
}

// Attempt to refresh token on page load
useEffect( _ => {
async function tryRefresh(csrf_refresh_token){
if (csrf_refresh_token === undefined){
return false;
}

let new_access_token = await refresh(csrf_refresh_token);
if (!new_access_token){
console.error("Failed to refresh access token.")
return false;
}

setToken(new_access_token);
setLoggedIn(true);
(async () => {
await tryRefresh(cookies.csrf_refresh_token);
})();
}, [cookies]);

// Auto update token
useEffect( () => {
if (token === null) {
return undefined;
}
tryRefresh(cookies.csrf_refresh_token);
}, []);

// 5 second buffer for access token refresh
const refersh_buffer_time = 5000;
const access_token_expiration_claim = decodeJWT(token).exp
const access_token_expiration_time = new Date(0).setUTCSeconds(access_token_expiration_claim);
const miliseconds_to_access_token_expiration = (access_token_expiration_time - Date.now())

const timer = setTimeout( async () => {
await tryRefresh(cookies.csrf_refresh_token);
}, miliseconds_to_access_token_expiration - refersh_buffer_time);

return () => clearTimeout(timer);
}, [token, cookies]);

return (
<LoginContext.Provider value={loggedIn}>
Expand Down

0 comments on commit 2d60fef

Please sign in to comment.