Skip to content

Commit

Permalink
Merge pull request #130 from ECN/fix-access-token-refresh
Browse files Browse the repository at this point in the history
Fix access token refresh
  • Loading branch information
campb303 authored Nov 25, 2020
2 parents 951e795 + 2d60fef commit 45037b9
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 16 deletions.
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@testing-library/user-event": "^7.2.1",
"clsx": "^1.1.1",
"history": "^5.0.0",
"jwt-decode": "^3.1.2",
"material-table": "^1.63.1",
"react": "^16.13.1",
"react-cookie": "^4.0.3",
Expand Down
55 changes: 39 additions & 16 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,24 +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){
console.log("CSRF Token", 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 45037b9

Please sign in to comment.