Created
January 18, 2018 19:24
-
-
Save leebrandt/1dc210ca12deb91d70cc44f28978b482 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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