Skip to content

Instantly share code, notes, and snippets.

@leebrandt
Created January 18, 2018 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leebrandt/1dc210ca12deb91d70cc44f28978b482 to your computer and use it in GitHub Desktop.
Save leebrandt/1dc210ca12deb91d70cc44f28978b482 to your computer and use it in GitHub Desktop.
import config from '../app.config.js';
export default async (uri, options) => {
options = options || {};
let token = JSON.parse(localStorage.getItem('token'));
if (!token || (new Date()) - (new Date(token.expiresAt)) < 30) {
await getAccessToken();
token = JSON.parse(localStorage.getItem('token'));
}
// make the call with the access token
if(token){
const optionHeaders = Object.assign({}, options.headers, { 'Authorization': 'Bearer ' + token.access_token });
const optsWithAuthHeader = Object.assign({}, options, { headers: optionHeaders });
return fetch(uri, optsWithAuthHeader);
}else{
return fetch(uri, options);
}
};
const getAccessToken = () => {
let formData = new FormData();
formData.append('grant_type', 'client_credentials');
formData.append('scope', 'access_token');
fetch(config.okta.tokenUrl, {
method: 'POST',
headers: {
Authorization: 'Basic ' + btoa(config.okta.clientId+':'+config.okta.clientSecret),
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData
})
.then(res => res.json())
.then(token => {
token.expiresAt = new Date() + token.expires_in;
localStorage.setItem('token', JSON.stringify(token));
})
.catch(err => console.error(err));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment