authentication-adal-pkg
Advanced tools
Comparing version 1.0.44 to 1.0.45
844
index.js
@@ -299,9 +299,10 @@ 'use strict'; | ||
var index = items.length - 1; | ||
var token = (items[index] && items[index].accessToken) || getTokenFromCache(); | ||
var token = items[index] && items[index].accessToken; | ||
if (token && isValidToken(token)) { | ||
resolve(token); | ||
} else { | ||
// No token found | ||
authenticateMobile(resolve, reject); | ||
// reject(new Error('No token found')); | ||
authenticateMobile(function(authResult) { | ||
var token = authResult && authResult.accessToken; | ||
resolve(token); | ||
}, reject); | ||
} | ||
@@ -427,782 +428,73 @@ }); | ||
var authenticateSSO = function(resolve, reject) { | ||
var refreshToken = ''; | ||
// Check if MS ADAL cordova library is installed | ||
Microsoft.ADAL.AuthenticationSettings.setUseBroker(true).then(function() { | ||
initAuthenticationContext(constants.MOBILE); | ||
setPlatformRedirectUri(getPlatform()); | ||
// Check if token already exist. If so, take the tenant where the token came from. | ||
// This prevents an additional prompt | ||
authContext.tokenCache.readItems().then(function(items) { | ||
if (items.length > 0) { | ||
var index = items.length - 1; | ||
authority = items[index].authority; | ||
var token = items[index].accessToken; | ||
// if valid token | ||
if (isValidToken(token)) { | ||
resolve(items[index]); | ||
return; | ||
} | ||
initAuthenticationContext(constants.MOBILE); | ||
} | ||
// Attempt to authorize user silently | ||
authContext.acquireTokenSilentAsync(resourceUri, clientIdNative, userId).then( | ||
function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, | ||
function() { | ||
// We require user credentials so triggers authentication dialog | ||
// acquireTokenAsyncMobile(resolve, reject); | ||
authContext.acquireTokenAsync(resourceUri, clientIdNative, platformRedirectUri).then(function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
var token = authResult.accessToken; | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, reject); | ||
} | ||
); | ||
}, reject); | ||
}, reject); | ||
}; | ||
var authenticateCodeGrant = function(resolve, reject) { | ||
var token = null; | ||
var _getCachedToken = getCachedToken(), | ||
token = _getCachedToken.response; | ||
if (!token && !isInProgress() && !localError) { | ||
storage.set(constants.IN_PROGRESS, true); | ||
setStateAndNonce(); | ||
window.location.replace(getLoginUrl()); | ||
return Promise.resolve({ token: null, error: null }); | ||
} | ||
return Promise.resolve({ token: token, error: null }); | ||
}; | ||
var authenticateMobile = function(resolve, reject) { | ||
if (oAuthFlow === oAuthFlows.CODE_GRANT) { | ||
authenticateCodeGrant(resolve, reject); | ||
} else { | ||
authenticateSSO(resolve, reject); | ||
} | ||
}; | ||
var authenticateBrowser = function authenticateBrowser(resolve, reject) { | ||
initAuthenticationContext(constants.BROWSER); | ||
var _getCachedToken = getCachedToken(), | ||
token = _getCachedToken.response; | ||
if (!token && !isInProgress() && !localError) { | ||
storage.set(constants.IN_PROGRESS, false); | ||
localStorage.setItem(constants.REDIRECT_SUB_ROUTE, window.location.href.split('#')[1]); | ||
loginTried = true; | ||
var error = getParameter('error'); | ||
if (error) { | ||
reject({ error: error }); | ||
} else { | ||
auth.login(); | ||
resolve({ | ||
token: null, | ||
error: null | ||
Microsoft.ADAL.AuthenticationSettings.setUseBroker(true) | ||
.then(() => Microsoft.ADAL.AuthenticationSettings.setLogLevel(0)) | ||
.then(function() { | ||
initAuthenticationContext(constants.MOBILE); | ||
Microsoft.ADAL.AuthenticationSettings.setLogger(function logger(logItem) { | ||
console.log(logItem); | ||
}); | ||
} | ||
} else { | ||
auth.saveTokenFromHash(auth.getRequestInfo(window.location.hash)); | ||
// window.location.href = 'http://localhost:4200/#/blabla'; | ||
var redirectSubroute = localStorage.getItem(constants.REDIRECT_SUB_ROUTE); | ||
localStorage.removeItem(constants.REDIRECT_SUB_ROUTE); | ||
if (!!redirectSubroute && redirectSubroute !== '/') { | ||
// window.location.href = window.location.origin + '/#' + redirectSubroute; | ||
window.location.replace(window.location.origin + '/#' + redirectSubroute); | ||
// window.location.replace('http://localhost:4200/tester'); | ||
} | ||
resolve({ | ||
token: token, | ||
error: null | ||
}); | ||
} | ||
}; | ||
var authenticate = function authenticate(resolve, reject) { | ||
try { | ||
// Check platformId | ||
if (getPlatform() === constants.BROWSER) { | ||
authenticateBrowser(resolve, reject); | ||
} else { | ||
authenticateMobile(resolve, reject); | ||
} | ||
} catch (err) { | ||
reject(err); | ||
} | ||
}; | ||
var decodeTokenPayload = function decodeTokenPayload(token) { | ||
try { | ||
return jwtDecode(token); | ||
} catch (e) { | ||
console.error('unable to decode token', e); | ||
return {}; | ||
} | ||
}; | ||
var getUser = function getUser() { | ||
if (!Object.keys(user).length) { | ||
return acquireToken(getUser).then(function(token) { | ||
var _decodeTokenPayload = decodeTokenPayload(token), | ||
family_name = _decodeTokenPayload.family_name, | ||
given_name = _decodeTokenPayload.given_name, | ||
name = _decodeTokenPayload.name, | ||
upn = _decodeTokenPayload.upn; | ||
if (!upn) { | ||
upn = decodeTokenPayload(token).email; | ||
} | ||
user = createUser(family_name, given_name, name, upn); | ||
return user; | ||
}); | ||
} | ||
return Promise.resolve(user); | ||
}; | ||
var isValidToken = function(token) { | ||
if (!token) { | ||
return false; | ||
} | ||
var expiration = storage.get(constants.TOKEN_EXPIRATION); | ||
if (expiration && expiration.toString() && expiration.toString().length < 13) { | ||
return expiration && parseInt(expiration, 10) > Date.now() / 1000; | ||
} | ||
return expiration && parseInt(expiration, 10) > Date.now(); | ||
}; | ||
var getTokenFromCache = function getTokenFromCache() { | ||
var token = storage.get(constants.TOKEN); | ||
if (!isValidToken(token)) { | ||
storage.remove(constants.TOKEN); | ||
storage.remove(constants.TOKEN_EXPIRATION); | ||
return null; | ||
} | ||
return token; | ||
}; | ||
var getUserFromCache = function getUserFromCache() { | ||
var token = storage.get(constants.TOKEN); | ||
if (isValidToken(token)) { | ||
var _decodeTokenPayload2 = decodeTokenPayload(token), | ||
family_name = _decodeTokenPayload2.family_name, | ||
given_name = _decodeTokenPayload2.given_name, | ||
name = _decodeTokenPayload2.name, | ||
upn = _decodeTokenPayload2.upn; | ||
if (!upn) { | ||
upn = decodeTokenPayload(token).email; | ||
} | ||
user = createUser(family_name, given_name, name, upn); | ||
return user; | ||
} | ||
}; | ||
var createUser = function createUser(familyName, givenName, name, upn) { | ||
return { | ||
familyName: familyName, | ||
givenName: givenName, | ||
name: name, | ||
upn: upn | ||
}; | ||
}; | ||
var getUrlParameters = function getUrlParameters(hash) { | ||
function deserializeHash(query) { | ||
var match; | ||
var pl = /\+/g; // Regex for replacing addition symbol with a space | ||
var search = /([^&=]+)=?([^&]*)/g; | ||
var decode = function(s) { | ||
return decodeURIComponent(s.replace(pl, ' ')); | ||
}; | ||
var parameters = {}; | ||
match = search.exec(query); | ||
while (match) { | ||
parameters[decode(match[1])] = decode(match[2]); | ||
match = search.exec(query); | ||
} | ||
return parameters; | ||
} | ||
function getHash(hash) { | ||
var hashString = ''; | ||
if (hash.indexOf('#/') > -1) { | ||
hashString = hash.substring(hash.indexOf('#/') + 2); | ||
} else if (hash.indexOf('#') > -1) { | ||
hashString = hash.substring(1); | ||
} | ||
return (hashString && deserializeHash(hashString)) || null; | ||
} | ||
function getQueryParams(url) { | ||
return url | ||
.substr(1) | ||
.split('&') | ||
.reduce(function(params, item) { | ||
var _item$split = item.split('='), | ||
_item$split2 = _slicedToArray(_item$split, 2), | ||
key = _item$split2[0], | ||
value = _item$split2[1]; | ||
if (!params.hasOwnProperty(key)) { | ||
// eslint-disable-line no-prototype-builtins | ||
return Object.assign({}, params, _defineProperty({}, key, decodeURIComponent(value))); | ||
setPlatformRedirectUri(getPlatform()); | ||
// Check if token already exist. If so, take the tenant where the token came from. | ||
// This prevents an additional prompt | ||
authContext.tokenCache.readItems().then(function(items) { | ||
if (items.length > 0) { | ||
var index = items.length - 1; | ||
authority = items[index].authority; | ||
refreshToken = items[index].refreshToken; | ||
var token = items[index].accessToken; | ||
// if valid token | ||
if (isValidToken(token)) { | ||
resolve(items[index]); | ||
return; | ||
} | ||
// initAuthenticationContext(constants.MOBILE); | ||
} | ||
return params; | ||
}, {}); | ||
} | ||
return getHash(hash || window.location.hash) || getQueryParams(window.location.search); | ||
}; | ||
var getParameter = function getParameter(key) { | ||
var parameters = getUrlParameters(); | ||
return parameters[key]; | ||
}; | ||
var requestAccessToken = function(code) { | ||
// const url = config. | ||
}; | ||
var handleSuccessCallBack = function(token) { | ||
if (token) { | ||
var validToken = true; | ||
var _decodeTokenPayload3 = decodeTokenPayload(token), | ||
nonce = _decodeTokenPayload3.nonce, | ||
aud = _decodeTokenPayload3.aud, | ||
exp = _decodeTokenPayload3.exp, | ||
family_name = _decodeTokenPayload3.family_name, | ||
given_name = _decodeTokenPayload3.given_name, | ||
name = _decodeTokenPayload3.name, | ||
upn = _decodeTokenPayload3.upn; | ||
// TODO: validate token | ||
if (validToken) { | ||
storage.set(constants.IN_PROGRESS, false); | ||
storage.set(constants.TOKEN, token); | ||
storage.set(constants.TOKEN_EXPIRATION, exp); | ||
} | ||
var redirectSubroute = localStorage.getItem(constants.REDIRECT_SUB_ROUTE); | ||
// localStorage.removeItem(constants.REDIRECT_SUB_ROUTE); | ||
if (!!redirectSubroute && redirectSubroute !== '/') { | ||
window.location = window.location.origin + '/#' + redirectSubroute; | ||
// // window.location.replace(window.location.origin + '/#' + redirectSubroute); | ||
// window.location.replace('http://localhost:4200/#id_token=' + token); | ||
} | ||
} | ||
}; | ||
var handleErrorCallback = function(error) { | ||
storage.set(constants.ERROR, constants.ACCESS_DENIED); | ||
this.localError = (error && error.message) || 'Could not get access token'; | ||
}; | ||
var handleWindowCallback = function handleWindowCallback() { | ||
//get token from parameter and push to session storage | ||
var token = getParameter('id_token'); | ||
var state = getParameter('state'); | ||
var code = getParameter('code'); | ||
var error = getParameter('error'); | ||
// if auth flow is code grant -> request access token | ||
if (oAuthFlow === oAuthFlows.CODE_GRANT && code) { | ||
requestAccessToken() | ||
.then(accessToken => { | ||
handleSuccessCallBack(accessToken); | ||
}) | ||
.catch(err => { | ||
handleErrorCallback(err); | ||
}); | ||
} | ||
// if auth flow is implicit grant -> store token | ||
if (token) { | ||
handleSuccessCallBack(token); | ||
} else if (error) { | ||
handleErrorCallback(error); | ||
} | ||
}; | ||
handleWindowCallback(); | ||
return { | ||
signIn: signIn, | ||
signOut: signOut, | ||
acquireToken: acquireToken, | ||
getError: getError, | ||
setError: setError, | ||
initialize: initialize, | ||
getUser: getUser, | ||
getUserFromCache: getUserFromCache, | ||
getTokenFromCache: getTokenFromCache | ||
}; | ||
})(); | ||
module.exports = { | ||
authentication: eandisAuthenticator | ||
}; | ||
('use strict'); | ||
var _slicedToArray = (function() { | ||
function sliceIterator(arr, i) { | ||
var _arr = []; | ||
var _n = true; | ||
var _d = false; | ||
var _e = undefined; | ||
try { | ||
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { | ||
_arr.push(_s.value); | ||
if (i && _arr.length === i) break; | ||
} | ||
} catch (err) { | ||
_d = true; | ||
_e = err; | ||
} finally { | ||
try { | ||
if (!_n && _i['return']) _i['return'](); | ||
} finally { | ||
if (_d) throw _e; | ||
} | ||
} | ||
return _arr; | ||
} | ||
return function(arr, i) { | ||
if (Array.isArray(arr)) { | ||
return arr; | ||
} else if (Symbol.iterator in Object(arr)) { | ||
return sliceIterator(arr, i); | ||
} else { | ||
throw new TypeError('Invalid attempt to destructure non-iterable instance'); | ||
} | ||
}; | ||
})(); | ||
function _defineProperty(obj, key, value) { | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
} | ||
return obj; | ||
} | ||
window.AuthenticationContext = require('adal-angular'); | ||
var jwtDecode = require('jwt-decode'); | ||
var eandisAuthenticator = (function auth(config) { | ||
var constants = { | ||
MOBILE: 'mobile', | ||
BROWSER: 'browser', | ||
STATE: 'state', | ||
NONCE: 'nonce', | ||
TOKEN: 'token', | ||
TOKEN_EXPIRATION: 'token.expiration', | ||
IN_PROGRESS: 'progess', | ||
REDIRECT_SUB_ROUTE: 'redirectSubRoute', | ||
ACCESS_DENIED: 'access_denied', | ||
ERROR: 'adal.error' | ||
}; | ||
var oAuthFlows = { | ||
IMPLICIT_GRANT: 'IMPLICIT_GRANT', | ||
CODE_GRANT: 'CODE_GRANT' | ||
}; | ||
var authority = null; | ||
var tenant = null; | ||
var redirectUriWeb = null; | ||
var redirectUriIOS = null; | ||
var redirectUriAndroid = null; | ||
var redirectUriWindows = null; | ||
var resourceUri = null; | ||
var loginResource = null; | ||
var clientIdNative = null; | ||
var clientIdWeb = null; | ||
var userId = null; | ||
var loginPolicy = null; | ||
var editProfilePolicy = null; | ||
var changePasswordPolicy = null; | ||
var authenticationResult = null; | ||
var auth = null; | ||
var authContext = null; | ||
var platformRedirectUri = null; | ||
var localError = ''; | ||
var user = {}; | ||
var loginTried = false; | ||
var oAuthFlow = oAuthFlows.IMPLICIT_GRANT; | ||
var baseUrl = 'https://login.microsoftonline.com'; | ||
var authorizeUrl = 'oauth2/authorize'; | ||
var codeUrl = 'oauth2/code'; | ||
var initialize = function initialize(config) { | ||
authority = config.authority; | ||
tenant = config.tenant; | ||
redirectUriWeb = config.redirectUriWeb; | ||
redirectUriIOS = config.redirectUriIOS; | ||
redirectUriAndroid = config.redirectUriAndroid; | ||
redirectUriWindows = config.redirectUriWindows; | ||
resourceUri = config.resourceUri; | ||
clientIdWeb = config.clientIdWeb; | ||
clientIdNative = config.clientIdNative; | ||
userId = config.userId; | ||
loginResource = config.loginResource; | ||
loginPolicy = config.loginPolicy; | ||
editProfilePolicy = config.editProfilePolicy; | ||
changePasswordPolicy = config.changePasswordPolicy; | ||
oAuthFlow = config.oAuthFlow; | ||
}; | ||
var initAuthenticationContext = function initAuthenticationContext(platform) { | ||
if (platform === constants.BROWSER) { | ||
var config = { | ||
tenant: tenant, | ||
clientId: clientIdWeb, | ||
redirectUri: redirectUriWeb, | ||
loginResource: loginResource | ||
}; | ||
if (!!loginPolicy) { | ||
config = Object.assign(config, { | ||
extraQueryParameter: loginPolicy | ||
}); | ||
} | ||
if (!!editProfilePolicy) { | ||
config = Object.assign(config, { | ||
extraQueryParameter: editProfilePolicy | ||
}); | ||
} | ||
if (!!changePasswordPolicy) { | ||
config = Object.assign(config, { | ||
extraQueryParameter: changePasswordPolicy | ||
}); | ||
} | ||
auth = new AuthenticationContext(config); | ||
} else { | ||
authContext = new Microsoft.ADAL.AuthenticationContext(authority); | ||
} | ||
}; | ||
var storage = { | ||
prefix: 'auth', | ||
set: function set(key, value) { | ||
localStorage.setItem(this.prefix + '-' + key, value); | ||
}, | ||
get: function get(key) { | ||
return localStorage.getItem(this.prefix + '-' + key); | ||
}, | ||
remove: function remove(key) { | ||
localStorage.removeItem(this.prefix + '-' + key); | ||
} | ||
}; | ||
storage.set(constants.IN_PROGRESS, false); | ||
var getPlatform = function getPlatform() { | ||
return (window.cordova && window.cordova.platformId) || 'browser'; | ||
}; | ||
var signIn = function signIn() { | ||
return new Promise(function(resolve, reject) { | ||
authenticate(resolve, reject); | ||
}); | ||
}; | ||
var signoutServer = function signoutServer() { | ||
var xhr = new XMLHttpRequest(); | ||
setPlatformRedirectUri(getPlatform()); | ||
var url = 'https://login.windows.net/' + tenant + '/oauth2/logout?post_logout_redirect_uri=' + platformRedirectUri; | ||
xhr.open('GET', url, true); | ||
xhr.onreadystatechange = function() { | ||
if (xhr.readyState == 4) { | ||
} | ||
}; | ||
xhr.send(); | ||
}; | ||
var signOutMobile = function signOutMobile() { | ||
return new Promise(function(resolve, reject) { | ||
try { | ||
if (!authContext) { | ||
initAuthenticationContext(constants.MOBILE); | ||
} | ||
authContext.tokenCache.clear(); | ||
signoutServer(); | ||
resolve(); | ||
} catch (err) { | ||
reject(err); | ||
} | ||
// request naar https://login.windows.net/{tenantid or "common"}/oauth2/logout?post_logout_redirect_uri={URL} | ||
}); | ||
}; | ||
var signOutBrowser = function signOutBrowser() { | ||
return new Promise(function(resolve, reject) { | ||
try { | ||
if (!auth) { | ||
initAuthenticationContext(constants.BROWSER); | ||
} | ||
auth.logOut(); | ||
resolve(); | ||
} catch (err) { | ||
reject(err); | ||
} | ||
}); | ||
}; | ||
var signOut = function signOut() { | ||
storage.remove(constants.TOKEN); | ||
storage.remove(constants.TOKEN_EXPIRATION); | ||
storage.remove(constants.ERROR); | ||
if (getPlatform() === constants.BROWSER) { | ||
return signOutBrowser(); | ||
} else { | ||
return signOutMobile(); | ||
} | ||
}; | ||
var onAcquireToken = function onAcquireToken(errorDesc, token, error) { | ||
return new Promise(function(resolve, reject) { | ||
var acquireTokenCallback = function acquireTokenCallback(desc, token, err) { | ||
if (err) reject(err); | ||
else resolve(token); | ||
}; | ||
if (error) { | ||
if (!auth) { | ||
initAuthenticationContext(constants.BROWSER); | ||
} | ||
auth.acquireTokenPopup(clientIdWeb, null, null, acquireTokenCallback); | ||
} else { | ||
resolve(token); | ||
} | ||
}); | ||
}; | ||
var getLoginError = function() { | ||
var errorText = window.location.href.split('#')[1]; | ||
var splittedErrorText = errorText && errorText.split('='); | ||
var type = splittedErrorText && splittedErrorText[1] && splittedErrorText[1].split('&')[0]; | ||
return type; | ||
}; | ||
var getError = function() { | ||
return storage.get(constants.ERROR); | ||
}; | ||
var setError = function(msg) { | ||
return storage.set(constants.ERROR, msg); | ||
}; | ||
var acquireTokenBrowser = function acquireTokenBrowser(resolve, reject, cb) { | ||
var token = storage.get(constants.TOKEN); | ||
if (token && isValidToken(token)) { | ||
resolve(token); | ||
return; | ||
} | ||
if (!auth) { | ||
initAuthenticationContext(constants.BROWSER); | ||
} | ||
// Saves the token in the cache and calls the callback method (onAcquireToken) with error or token | ||
auth.handleWindowCallback(); | ||
var acquireTokenCallback = function acquireTokenCallback(errorDesc, token, error) { | ||
onAcquireToken(errorDesc, token, error) | ||
.then(resolve) | ||
.catch(function(msg) { | ||
var loginError = getLoginError(); | ||
var loginWasTriedButFailed = loginTried && loginError === constants.ACCESS_DENIED; | ||
if (loginWasTriedButFailed) { | ||
storage.set(constants.ERROR, constants.ACCESS_DENIED); | ||
reject({ message: 'Access denied' }); | ||
} else if (msg === 'login required') { | ||
authenticateBrowser(resolve, reject); | ||
} else { | ||
reject(msg); | ||
} | ||
// if (e === 'login required') { | ||
// // FIXME: | ||
// // var authPromise = new Promise(function(resolve, reject) { | ||
// // // authenticate(resolve, reject); | ||
// // }); | ||
// authenticateBrowser(resolve, reject); | ||
// // reject('Error while logging in'); | ||
// } else { | ||
// reject(e); | ||
// } | ||
}); | ||
}; | ||
auth.acquireToken(clientIdWeb, acquireTokenCallback); | ||
}; | ||
var acquireTokenMobile = function acquireTokenMobile(resolve, reject) { | ||
if (!authContext) { | ||
initAuthenticationContext(constants.MOBILE); | ||
} | ||
authContext.tokenCache.readItems().then(function(items) { | ||
var index = items.length - 1; | ||
var token = (items[index] && items[index].accessToken) || getTokenFromCache(); | ||
if (token && isValidToken(token)) { | ||
resolve(token); | ||
} else { | ||
// No token found | ||
authenticateMobile(resolve, reject); | ||
// reject(new Error('No token found')); | ||
} | ||
}); | ||
}; | ||
var acquireToken = function acquireToken(cb) { | ||
return new Promise(function(resolve, reject) { | ||
try { | ||
if (getPlatform() === constants.BROWSER) { | ||
acquireTokenBrowser(resolve, reject, cb); | ||
} else { | ||
acquireTokenMobile(resolve, reject); | ||
} | ||
} catch (err) { | ||
reject(err); | ||
} | ||
}); | ||
}; | ||
var setPlatformRedirectUri = function setPlatformRedirectUri(platform) { | ||
switch (platform.toLowerCase()) { | ||
case 'android': | ||
platformRedirectUri = redirectUriAndroid; | ||
break; | ||
case 'ios': | ||
platformRedirectUri = redirectUriIOS; | ||
break; | ||
case 'windows': | ||
platformRedirectUri = redirectUriWindows; | ||
break; | ||
} | ||
}; | ||
var isInProgress = function isInProgress() { | ||
return storage.get(constants.IN_PROGRESS) === 'true'; | ||
}; | ||
var getCachedToken = function getCachedToken() { | ||
var token = storage.get(constants.TOKEN); | ||
var expiration = storage.get(constants.TOKEN_EXPIRATION); | ||
if (expiration && parseInt(expiration, 10) > Date.now() / 1000) { | ||
// log.info('valid cached token'); | ||
return { | ||
response: token, | ||
error: null | ||
}; | ||
} else if (localError) { | ||
return { | ||
response: null, | ||
error: localError | ||
}; | ||
} | ||
return { | ||
response: null, | ||
error: null | ||
}; | ||
}; | ||
var setStateAndNonce = function() { | ||
var state = uuidv4(); | ||
var nonce = uuidv4(); | ||
storage.set(constants.STATE, state); | ||
storage.set(constants.NONCE, nonce); | ||
return { state: state, nonce: nonce }; | ||
}; | ||
var getUrlOptions = function() { | ||
const { config } = authConfig; | ||
// var commonOptions = [ | ||
// 'response_type=' + config.responseType, | ||
// 'client_id=' + encodeURIComponent(config.clientId), | ||
// 'redirect_uri=' + encodeURIComponent(config.redirectUri), | ||
// 'nonce=' + encodeURIComponent(storage.get(constants.NONCE)), | ||
// 'state=' + encodeURIComponent(storage.get(constants.STATE)), | ||
// ]; | ||
var commonOptions = [ | ||
'response_type='.concat(config.responseType), | ||
'client_id='.concat(encodeURIComponent(config.clientId)), | ||
'redirect_uri='.concat(encodeURIComponent(config.redirectUri)), | ||
'nonce='.concat(encodeURIComponent(storage.get(constants.NONCE))), | ||
'state='.concat(encodeURIComponent(storage.get(constants.STATE))) | ||
]; | ||
var optionsV1 = [ | ||
'scope='.concat(encodeURIComponent(config.scopeV1)), | ||
''.concat(config.resource ? 'resource='.concat(encodeURIComponent(config.resource)) : ''), | ||
'client-request-id='.concat(encodeURIComponent(config.clientRequestId)) | ||
]; | ||
var optionsV2 = ['scope='.concat(encodeURIComponent(config.scopeV2))]; | ||
let options = commonOptions; | ||
if (config.oAuthVersion === constants.V1) { | ||
options = commonOptions.concat(optionsV1); | ||
} else { | ||
options = commonOptions.concat(optionsV2); | ||
} | ||
return options.join('&'); | ||
}; | ||
var getLoginUrl = function() { | ||
return config.baseUrl + '/' + config.tenant + '/' + config.authorizeUrl + '/' + getUrlOptions(); | ||
}; | ||
var acquireTokenAsyncMobile = function(resolve, reject) { | ||
authContext.acquireTokenAsync(resourceUri, clientIdNative, platformRedirectUri).then(function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, reject); | ||
}; | ||
var storeToken = function(token, exp) { | ||
storage.set(constants.IN_PROGRESS, false); | ||
storage.set(constants.TOKEN, token); | ||
storage.set(constants.TOKEN_EXPIRATION, exp); | ||
}; | ||
var authenticateSSO = function(resolve, reject) { | ||
// Check if MS ADAL cordova library is installed | ||
Microsoft.ADAL.AuthenticationSettings.setUseBroker(true).then(function() { | ||
initAuthenticationContext(constants.MOBILE); | ||
setPlatformRedirectUri(getPlatform()); | ||
// Check if token already exist. If so, take the tenant where the token came from. | ||
// This prevents an additional prompt | ||
authContext.tokenCache.readItems().then(function(items) { | ||
if (items.length > 0) { | ||
var index = items.length - 1; | ||
authority = items[index].authority; | ||
var token = items[index].accessToken; | ||
// if valid token | ||
if (isValidToken(token)) { | ||
resolve(items[index]); | ||
return; | ||
} | ||
initAuthenticationContext(constants.MOBILE); | ||
} | ||
// Attempt to authorize user silently | ||
authContext.acquireTokenSilentAsync(resourceUri, clientIdNative, userId).then( | ||
function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, | ||
function() { | ||
// We require user credentials so triggers authentication dialog | ||
// acquireTokenAsyncMobile(resolve, reject); | ||
authContext.acquireTokenAsync(resourceUri, clientIdNative, platformRedirectUri).then(function(authResult) { | ||
// Attempt to authorize user silently | ||
authContext.acquireTokenSilentAsync(resourceUri, clientIdNative, userId).then( | ||
function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
var token = authResult.accessToken; | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, reject); | ||
} | ||
); | ||
}, | ||
function() { | ||
if (refreshToken && resourceUri && clientIdNative) { | ||
authContext | ||
.acquireTokenByRefreshToken(refreshToken, resourceUri, clientIdNative, userId) | ||
.then(function(refreshAuthResult) { | ||
var token = refreshAuthResult.accessToken; | ||
var exp = new Date(refreshAuthResult.expiresOn).getTime(); | ||
storeToken(token, exp); | ||
resolve(refreshAuthResult); | ||
}) | ||
.catch(function(err) { | ||
// We require user credentials so triggers authentication dialog | ||
// acquireTokenAsyncMobile(resolve, reject); | ||
authContext | ||
.acquireTokenAsync(resourceUri, clientIdNative, platformRedirectUri) | ||
.then(function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
var token = authResult.accessToken; | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, reject); | ||
}); | ||
} else { | ||
authContext | ||
.acquireTokenAsync(resourceUri, clientIdNative, platformRedirectUri) | ||
.then(function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
var token = authResult.accessToken; | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, reject); | ||
} | ||
} | ||
); | ||
}, reject); | ||
}, reject); | ||
}, reject); | ||
}; | ||
@@ -1209,0 +501,0 @@ |
106
lib/index.js
@@ -299,9 +299,10 @@ 'use strict'; | ||
var index = items.length - 1; | ||
var token = (items[index] && items[index].accessToken) || getTokenFromCache(); | ||
var token = items[index] && items[index].accessToken; | ||
if (token && isValidToken(token)) { | ||
resolve(token); | ||
} else { | ||
// No token found | ||
authenticateMobile(resolve, reject); | ||
// reject(new Error('No token found')); | ||
authenticateMobile(function(authResult) { | ||
var token = authResult && authResult.accessToken; | ||
resolve(token); | ||
}, reject); | ||
} | ||
@@ -427,42 +428,73 @@ }); | ||
var authenticateSSO = function(resolve, reject) { | ||
var refreshToken = ''; | ||
// Check if MS ADAL cordova library is installed | ||
Microsoft.ADAL.AuthenticationSettings.setUseBroker(true).then(function() { | ||
initAuthenticationContext(constants.MOBILE); | ||
setPlatformRedirectUri(getPlatform()); | ||
// Check if token already exist. If so, take the tenant where the token came from. | ||
// This prevents an additional prompt | ||
authContext.tokenCache.readItems().then(function(items) { | ||
if (items.length > 0) { | ||
var index = items.length - 1; | ||
authority = items[index].authority; | ||
var token = items[index].accessToken; | ||
// if valid token | ||
if (isValidToken(token)) { | ||
resolve(items[index]); | ||
return; | ||
Microsoft.ADAL.AuthenticationSettings.setUseBroker(true) | ||
.then(() => Microsoft.ADAL.AuthenticationSettings.setLogLevel(0)) | ||
.then(function() { | ||
initAuthenticationContext(constants.MOBILE); | ||
Microsoft.ADAL.AuthenticationSettings.setLogger(function logger(logItem) { | ||
console.log(logItem); | ||
}); | ||
setPlatformRedirectUri(getPlatform()); | ||
// Check if token already exist. If so, take the tenant where the token came from. | ||
// This prevents an additional prompt | ||
authContext.tokenCache.readItems().then(function(items) { | ||
if (items.length > 0) { | ||
var index = items.length - 1; | ||
authority = items[index].authority; | ||
refreshToken = items[index].refreshToken; | ||
var token = items[index].accessToken; | ||
// if valid token | ||
if (isValidToken(token)) { | ||
resolve(items[index]); | ||
return; | ||
} | ||
// initAuthenticationContext(constants.MOBILE); | ||
} | ||
initAuthenticationContext(constants.MOBILE); | ||
} | ||
// Attempt to authorize user silently | ||
authContext.acquireTokenSilentAsync(resourceUri, clientIdNative, userId).then( | ||
function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, | ||
function() { | ||
// We require user credentials so triggers authentication dialog | ||
// acquireTokenAsyncMobile(resolve, reject); | ||
authContext.acquireTokenAsync(resourceUri, clientIdNative, platformRedirectUri).then(function(authResult) { | ||
// Attempt to authorize user silently | ||
authContext.acquireTokenSilentAsync(resourceUri, clientIdNative, userId).then( | ||
function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
var token = authResult.accessToken; | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, reject); | ||
} | ||
); | ||
}, | ||
function() { | ||
if (refreshToken && resourceUri && clientIdNative) { | ||
authContext | ||
.acquireTokenByRefreshToken(refreshToken, resourceUri, clientIdNative, userId) | ||
.then(function(refreshAuthResult) { | ||
var token = refreshAuthResult.accessToken; | ||
var exp = new Date(refreshAuthResult.expiresOn).getTime(); | ||
storeToken(token, exp); | ||
resolve(refreshAuthResult); | ||
}) | ||
.catch(function(err) { | ||
// We require user credentials so triggers authentication dialog | ||
// acquireTokenAsyncMobile(resolve, reject); | ||
authContext | ||
.acquireTokenAsync(resourceUri, clientIdNative, platformRedirectUri) | ||
.then(function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
var token = authResult.accessToken; | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, reject); | ||
}); | ||
} else { | ||
authContext | ||
.acquireTokenAsync(resourceUri, clientIdNative, platformRedirectUri) | ||
.then(function(authResult) { | ||
var token = authResult.accessToken; | ||
var exp = new Date(authResult.expiresOn).getTime(); | ||
var token = authResult.accessToken; | ||
storeToken(token, exp); | ||
resolve(authResult); | ||
}, reject); | ||
} | ||
} | ||
); | ||
}, reject); | ||
}, reject); | ||
}, reject); | ||
}; | ||
@@ -469,0 +501,0 @@ |
{ | ||
"name": "authentication-adal-pkg", | ||
"version": "1.0.44", | ||
"version": "1.0.45", | ||
"description": "An authentication SDK based on MS ADAL ", | ||
@@ -5,0 +5,0 @@ "main": "lib/index.js", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
89951
2655