Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let AUTHORIZATION_URL = 'http://localhost:8010/Sitefinity/Authenticate/OpenID/connect/authorize';
- let PRESS_RELEASES_URL = 'http://localhost:8010/api/default/pressreleases';
- let ACCESS_TOKEN_KEY = 'access_token';
- let ACCESS_TOKEN_EXP_KEY = 'access_token_exp';
- window.onload = () => {
- // STS redirect URI. Access token is being received here
- if (window.location.hash) {
- let tokenResponse = getTokenResponse();
- saveToLocalStorage(tokenResponse.access_token);
- }
- // Token has expired or is not present. Requests new access token
- else if (hasExpired()) {
- let authFrame = appendAuthFrame();
- getToken(authFrame, () => {
- let token = localStorage[ACCESS_TOKEN_KEY];
- logPressReleases(token);
- authFrame.remove();
- });
- }
- // Token is available for use
- else {
- let token = localStorage[ACCESS_TOKEN_KEY];
- logPressReleases(token);
- }
- }
- function getToken(authFrame, callback) {
- // Prevents CSRF (Cross-Site Request Forgery) attacks
- let state = rand();
- let nonce = rand();
- localStorage['state'] = state;
- localStorage['nonce'] = nonce;
- let authorizationUrl = AUTHORIZATION_URL;
- let clientId = 'sitefinity';
- let redirectUri = getCurrentUri();
- let responseType = 'id_token token';
- let scope = 'openid email profile';
- let url = authorizationUrl + '?' +
- 'client_id=' + encodeURI(clientId) + '&' +
- 'redirect_uri=' + encodeURI(redirectUri) + '&' +
- 'response_type=' + encodeURI(responseType) + '&' +
- 'scope=' + encodeURI(scope) + '&' +
- 'state=' + encodeURI(state) + '&' +
- 'nonce=' + encodeURI(nonce);
- authFrame.src = url;
- authFrame.addEventListener('load', () => {
- callback();
- });
- }
- function getTokenResponse() {
- let hash = window.location.hash.substr(1);
- let result = hash.split('&').reduce((result, item) => {
- let parts = item.split('=');
- result[parts[0]] = parts[1];
- return result;
- }, {});
- return result;
- }
- function appendAuthFrame() {
- let authFrame = document.createElement('iframe');
- authFrame.style.display = 'none';
- document.body.appendChild(authFrame);
- return authFrame;
- }
- function hasExpired() {
- if (!localStorage[ACCESS_TOKEN_KEY] || !localStorage[ACCESS_TOKEN_EXP_KEY]) {
- return true;
- }
- let currentDate = new Date();
- let expirationDate = new Date(localStorage[ACCESS_TOKEN_EXP_KEY]);
- return currentDate > expirationDate;
- }
- function decodeJwt(token) {
- let base64Url = token.split('.')[1];
- let base64 = base64Url.replace('-', '+').replace('_', '/');
- return JSON.parse(window.atob(base64));
- }
- function getExpirationDate(token) {
- let tokenInfo = decodeJwt(token);
- let expirationDate = new Date(tokenInfo.exp * 1000);
- return expirationDate;
- }
- function saveToLocalStorage(token) {
- localStorage[ACCESS_TOKEN_KEY] = token;
- localStorage[ACCESS_TOKEN_EXP_KEY] = getExpirationDate(token);
- }
- function logPressReleases(token) {
- getJSON(PRESS_RELEASES_URL, token)
- .then(console.log)
- .catch(console.log);
- }
- function getJSON(url, token) {
- return new Promise((resolve, reject) => {
- let xhr = new XMLHttpRequest();
- xhr.responseType = 'json';
- xhr.onload = () => {
- try {
- if (xhr.status === 200) {
- let response = xhr.response;
- if (typeof response === 'string') {
- response = JSON.parse(response);
- }
- resolve(response);
- }
- else {
- reject(Error(`${xhr.statusText} (${xhr.status})`));
- }
- }
- catch (err) {
- reject(err);
- }
- }
- xhr.onerror = () => {
- reject(Error('Network error'));
- }
- xhr.open('GET', url);
- xhr.setRequestHeader('Authorization', `Bearer ${token}`);
- xhr.send();
- });
- }
- function getCurrentUri() {
- return window.location.href.split('?')[0];
- }
- function rand() {
- return (Date.now() + '' + Math.random()).replace('.', '');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement