I have some code that's supposed to generate a new token if certain conditions are met.
In IE the token generator returns a 200
(and console logs the token) but in Chrome and Firefox I'm getting 401
errors (console logging the token shows null
).
I've been looking up reasons as to why this is, but for some reason most of the SO posts I've come across have issues with IE and tokens and not Chrome.
permissionToCallAPI = new Promise(function(resolve, reject) {
function sessionGet(key) {
let stringValue = window.sessionStorage.getItem(key);
if (stringValue !== null) {
try {
const { value, expirationDateStr } = JSON.parse(stringValue);
if (value && expirationDateStr) {
let expirationDate = new Date(value.expirationDateStr);
if (expirationDate > new Date()) {
return value;
}
isAuthorized(value)
.then(resp => {
console.log("Valid Token");
return value;
})
.catch(err => {
throw "Failed Authentication.";
});
}
} catch (e) {
console.log(e);
window.sessionStorage.removeItem(key);
return null;
}
}
return null;
} // sessionGet()
// add into session
function sessionSet(key, value, expirationInMin) {
if (!expirationInMin) {
expirationInMin = 59;
}
var expirationDate = new Date(
new Date().getTime() + 60000 * expirationInMin
);
var newValue = {
value: value,
expirationDate: expirationDate.toISOString()
};
window.sessionStorage.setItem(key, JSON.stringify(newValue));
}
let _token = sessionGet("tokenSet");
console.log(_token); // null in Chr (not IE)
if (_token == null) {
$.ajax({
url: _RestHost + "/User/GenerateToken",
method: "GET", // using POST gets an error
cache: false,
withCredentials: true,
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
"Authorization": _token
},
success: function(data) {
sessionSet("tokenSet", data.AuthToken);
resolve(data.AuthToken);
},
error: function(err) {
reject(err);
}
});
} else {
resolve(_token);
}
});