diff --git a/README.md b/README.md
index 5879b0c8..8ff71284 100644
--- a/README.md
+++ b/README.md
@@ -6,13 +6,14 @@ Active Directory Authentication Library for JavaScript (ADAL JS) helps you to us
This library is optimized for working together with AngularJS.
## Versions
-Current version - 1.0.14
+Current version - 1.0.15
Minimum recommended version - 1.0.11
You can find the changes for each version in the [change log](https://github.com/AzureAD/azure-activedirectory-library-for-js/blob/master/changelog.txt).
## Samples and Documentation
-[We provide a full suite of sample applications and documentation on GitHub](https://github.com/azure-samples?query=active-directory) to help you get started with learning the Azure Identity system. This includes tutorials for native clients such as Windows, Windows Phone, iOS, OSX, Android, and Linux. We also provide full walkthroughs for authentication flows such as OAuth2, OpenID Connect, Graph API, and other awesome features.
+[We provide a full suite of sample applications and documentation on GitHub](https://github.com/azure-samples?query=active-directory) to help you get started with learning the Azure Identity system. This includes tutorials for native clients such as Windows, Windows Phone, iOS, OSX, Android, and Linux; and a detailed guide to registering your app with Azure Active Directory. We also provide full walkthroughs for authentication flows such as OAuth2, OpenID Connect, Graph API, and other awesome features.
+
## Community Help and Support
@@ -26,7 +27,7 @@ If you find a security issue with our libraries or services please report it to
## The Library
-This is a GA released version. The current version is **1.0.14**.
+This is a GA released version. The current version is **1.0.15**.
You have multiple ways of getting ADAL JS:
@@ -37,10 +38,10 @@ Via NPM:
Via CDN:
-
-
+
+
-CDN will be updated to latest version 1.0.14.
+CDN will be updated to latest version 1.0.15.
Via Bower:
@@ -92,14 +93,14 @@ Install grunt; call
grunt doc
-
+# Getting Started
**Quick usage guide**
-Below you can find a quick reference for the most common operations you need to perform to use adal js.
+Below you can find a quick reference for the most common operations you need to perform to use ADAL JS.
-1- Include references to angular.js libraries, adal.js, adal-angular.js in your main app page.
+1- Include references to angular.js libraries, adal.js, adal-angular.js in your main app page. The ADAL should be included after Angular, but before your application scripts as shown below.
-2- include a reference to adal module
+2- Include a reference to the ADAL module in your app module.
```js
var app = angular.module('demoApp', ['ngRoute', 'AdalAngular']);
```
@@ -113,7 +114,15 @@ var app = angular.module('demoApp', ['ngRoute', 'AdalAngular']);
Without the hashPrefix set, the AAD login will loop indefinitely as the callback URL from AAD (in the form of, {yourBaseUrl}/#{AADTokenAndState}) will be rewritten to remove the '#' causing the token parsing to fail and login sequence to occur again.
-4- Initialize adal with the AAD app coordinates at app config time
+4- Initialize ADAL with the AAD app coordinates at app config time. The minimum required object to initialize ADAL is:
+```js
+adalAuthenticationServiceProvider.init({
+ // clientId is the identifier assigned to your app by Azure Active Directory.
+ clientId: "e9a5a8b6-8af7-4719-9821-0deef255f68e"
+})
+```
+
+A single-tenant configuration, with CORS, looks like this:
```js
// endpoint to resource mapping(optional)
var endpoints = {
@@ -131,7 +140,8 @@ adalAuthenticationServiceProvider.init(
$httpProvider // pass http provider to inject request interceptor to attach tokens
);
```
-5- Define which routes you want to secure via adal - by adding `requireADLogin: true` to their definition
+
+5- Define which routes you want to secure via ADAL - by adding `requireADLogin: true` to their definition
```js
$routeProvider.
when("/todoList", {
@@ -141,10 +151,13 @@ $routeProvider.
});
```
-6- Any service invocation code you might have will remain unchanged. Adal's interceptor will automatically add tokens for every outgoing call.
+6- Any service invocation code you might have will remain unchanged. ADAL's interceptor will automatically add tokens for every outgoing call.
+
+Anonymous endpoints, introduced in version 1.0.10, is an array of values that will be ignored by the ADAL route/state change handlers. ADAL will not attach a token to outgoing requests that have these keywords or URI. Routes that *do not* specify the ```requireADLogin=true``` property are added to the ```anonymousEndpoints``` array automatically.
***Optional***
-7- If you so choose, in addition (or substitution) to route level protection you can add explicit login/logout UX elements. Furthermore, you can access properties of the currently signed in user directly form JavaScript (via userInfo and userInfo.profile):
+7- If you so choose, in addition (or substitution) to route level protection you can add explicit login/logout UX elements. Furthermore, you can access properties of the currently signed in user directly form JavaScript (via userInfo and userInfo.profile).
+The userInfo.profile property provides access to the claims in the ID token received from AAD. The claims can be used by the application for validation, to identify the subject's directory tenant, and so on. The complete list of claims with a brief description of each value is here, [Claims in Azure AD Security Tokens](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-scenarios):
```html
@@ -229,7 +242,9 @@ app.controller('homeController', ['$scope', '$location', 'adalAuthenticationServ
### Multi-Tenant
-By default, you have multi-tenant support. Adal will set tenant to 'common', if it is not specified in the config.
+By default, you have multi-tenant support. ADAL will set tenant to 'common', if it is not specified in the config. This allows any Microsoft account to authenticate to your application. If you are not interested in multi-tenant behavior, you will need to set the ```tenant``` property as shown above.
+
+If you allow multi-tenant authentication, and you do not wish to allow all Microsoft account users to use your application, you must provide your own method of filtering the token issuers to only those tenants who are allowed to login.
### Cache Location
Default storage location is sessionStorage. You can specify localStorage in the config as well.
@@ -246,14 +261,14 @@ adalAuthenticationServiceProvider.init(
```
### Security
-Tokens are accessible from javascript since Adal.JS is using HTML5 storage. Default storage option is sessionStorage, which keeps the tokens per session. You should ask user to login again for important operations on your app.
-You should protect your site for XSS. Please check the article here: https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
+Tokens are accessible from javascript since ADAL.JS is using HTML5 storage. Default storage option is sessionStorage, which keeps the tokens per session. You should ask user to login again for important operations on your app.
+You should protect your site for XSS. Please check the article here: [https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet](https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet)
### CORS API usage and IE
-Adal will get access token for given CORS API endpoints in the config. Access token is requested using Iframe. Iframe needs to access the cookies for the same domain that you did the initial sign in. IE does not allow to access cookies in IFrame for localhost. Your url needs to be fully qualified domain i.e http://yoursite.azurewebsites.com. Chrome does not have this restriction.
+ADAL will get access token for given CORS API endpoints in the config. Access token is requested using Iframe. Iframe needs to access the cookies for the same domain that you did the initial sign in. IE does not allow to access cookies in IFrame for localhost. Your url needs to be fully qualified domain i.e http://yoursite.azurewebsites.com. Chrome does not have this restriction.
-To make CORS API call, you need to specify endpoints in the config for your CORS API. Your service will be similar to this to make the call from JS. In your api project, you need to enable CORS api requests to receive flight requests. You can check the sample for that CORS API [sample ](https://github.com/AzureADSamples/SinglePageApp-WebAPI-AngularJS-DotNet).
+To make CORS API call, you need to specify endpoints in the config for your CORS API. Your service will be similar to this to make the call from JS. In your API project, you need to enable CORS API requests to receive flight requests. You can check the sample for CORS API [sample](https://github.com/AzureADSamples/SinglePageApp-WebAPI-AngularJS-DotNet).
```js
'use strict';
@@ -273,9 +288,13 @@ app.factory('contactService', ['$http', function ($http) {
```
You can read extended blogs for CORS API related to learn about Office365 usage.
-Andrew's related to Cors and office365 usage
+
+Andrew's related to CORS and Office365 usage
+
http://www.andrewconnell.com/blog/adal-js-cors-with-o365-apis-files-sharepoint
+
Vittorio's blog
+
http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/
http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/
diff --git a/bower.json b/bower.json
index 7b64defd..3124c570 100644
--- a/bower.json
+++ b/bower.json
@@ -1,6 +1,6 @@
{
"name": "adal-angular",
- "version": "1.0.14",
+ "version": "1.0.15",
"homepage": "https://github.com/AzureAD/azure-activedirectory-library-for-js",
"authors": [
"MSOpentech"
diff --git a/changelog.txt b/changelog.txt
index 8790d7ae..ccc58e04 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -1,3 +1,10 @@
+Version 1.0.15
+=========================
+* Added acquireTokenRedirect and acquireTokenPopup api's to acquire a token for resource interactively (MFA) and support conditional access.
+* Fixed a bug in acquireToken method that was happening when Adaljs was consumed as a module using loaders such as webpack.
+* Added custom event polyfill to support IE
+* Other bug fixes and updates
+
Version 1.0.14
=========================
* Adding ability to specify anonymous sub-urls for a configured endpoint
diff --git a/dist/adal-angular.min.js b/dist/adal-angular.min.js
index bc4d0724..e808abf1 100644
--- a/dist/adal-angular.min.js
+++ b/dist/adal-angular.min.js
@@ -1,2 +1,2 @@
-/*! adal-angular v1.0.14 2017-02-16 */
-!function(){"use strict";if("undefined"!=typeof module&&module.exports&&(module.exports.inject=function(a){return new AuthenticationContext(a)}),angular){var a=angular.module("AdalAngular",[]);a.provider("adalAuthenticationService",function(){var a=null,b={isAuthenticated:!1,userName:"",loginError:"",profile:""},c=function(c){var d=a.getCachedToken(c);b.isAuthenticated=null!==d&&d.length>0;var e=a.getCachedUser()||{userName:""};b.userName=e.userName,b.profile=e.profile,b.loginError=a.getLoginError()};this.init=function(b,d){if(!b)throw new Error("You must set configOptions, when calling init");b.isAngular=!0,d&&d.interceptors&&d.interceptors.push("ProtectedResourceInterceptor"),a=new AuthenticationContext(b),c(a.config.loginResource)},this.$get=["$rootScope","$window","$q","$location","$timeout","$injector",function(d,e,f,g,h,i){function j(a,b){return b.requireADLogin?a.requireADLogin!==!1:!!a.requireADLogin}function k(b){if(a.config&&a.config.anonymousEndpoints)for(var c=0;c-1)return!0;return!1}function l(a){var b=null,c=[];if(a.hasOwnProperty("parent"))for(b=a;b;)c.unshift(b),b=i.get("$state").get(b.parent);else for(var d=a.name.split("."),e=0,f=d[0];e-1&&g.url(l.substring(l.indexOf("#")+1)),e.location.href=l)}else g.$$html5?g.hash(""):g.path("")}else d.$broadcast("adal:stateMismatch",a._getItem(a.CONSTANTS.STORAGE.ERROR_DESCRIPTION),a._getItem(a.CONSTANTS.STORAGE.ERROR))}else if(c(a.config.loginResource),!b.isAuthenticated&&b.userName&&!a._renewActive){var m=i.get("adalAuthenticationService");m.acquireToken(a.config.loginResource).then(function(a){a&&(b.isAuthenticated=!0)},function(a){var b=a.split("|");d.$broadcast("adal:loginFailure",b[0],b[1])})}},o=function(){a.info("Login event for:"+g.$$url),a.config&&a.config.localLoginUrl?g.path(a.config.localLoginUrl):(a.info("Start login at:"+g.$$absUrl),d.$broadcast("adal:loginRedirect"),a.login(g.$$absUrl))},p=function(c,d){if(d&&d.$$route)if(j(d.$$route,a.config))b.isAuthenticated||a._renewActive||a.loginInProgress()||(a.info("Route change event for:"+g.$$url),o());else{var e;e="function"==typeof d.$$route.templateUrl?d.$$route.templateUrl(d.params):d.$$route.templateUrl,e&&!k(e)&&a.config.anonymousEndpoints.push(e)}},q=function(c,d,e,f,h){if(d)for(var i=l(d),m=null,n=0;n0;var e=a.getCachedUser()||{userName:""};b.userName=e.userName,b.profile=e.profile,b.loginError=a.getLoginError()};this.init=function(b,d){if(!b)throw new Error("You must set configOptions, when calling init");b.isAngular=!0,d&&d.interceptors&&d.interceptors.push("ProtectedResourceInterceptor"),a=new AuthenticationContext(b),c(a.config.loginResource)},this.$get=["$rootScope","$window","$q","$location","$timeout","$injector",function(d,e,f,g,h,i){function j(a,b){return b.requireADLogin?!1!==a.requireADLogin:!!a.requireADLogin}function k(b){if(a.config&&a.config.anonymousEndpoints)for(var c=0;c-1)return!0;return!1}function l(a){var b=null,c=[];if(a.hasOwnProperty("parent"))for(b=a;b;)c.unshift(b),b=i.get("$state").get(b.parent);else for(var d=a.name.split("."),e=0,f=d[0];e-1&&g.url(p.substring(p.indexOf("#")+1)),e.location.href=p)}else g.$$html5?g.hash(""):g.path("")}else d.$broadcast("adal:stateMismatch",a._getItem(a.CONSTANTS.STORAGE.ERROR_DESCRIPTION),a._getItem(a.CONSTANTS.STORAGE.ERROR))}else if(c(a.config.loginResource),!b.isAuthenticated&&b.userName&&!a._renewActive){var q=i.get("adalAuthenticationService");q.acquireToken(a.config.loginResource).then(function(a){a&&(b.isAuthenticated=!0)},function(a){var b=a.split("|");d.$broadcast("adal:loginFailure",b[0],b[1])})}},o=function(){a.info("Login event for:"+g.$$url),a.config&&a.config.localLoginUrl?g.path(a.config.localLoginUrl):(a.info("Start login at:"+g.$$absUrl),d.$broadcast("adal:loginRedirect"),a.login(g.$$absUrl))},p=function(c,d){if(d&&d.$$route)if(j(d.$$route,a.config))b.isAuthenticated||a._renewActive||a.loginInProgress()||(a.info("Route change event for:"+g.$$url),o());else{var e;e="function"==typeof d.$$route.templateUrl?d.$$route.templateUrl(d.params):d.$$route.templateUrl,e&&!k(e)&&a.config.anonymousEndpoints.push(e)}},q=function(c,d,e,f,h){if(d)for(var i=l(d),m=null,n=0;n-1},AuthenticationContext.prototype.getCachedToken=function(a){if(!this._hasResource(a))return null;var b=this._getItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY+a),c=this._getItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY+a),d=this.config.expireOffsetSeconds||300;return c&&c>this._now()+d?b:(this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY+a,""),this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY+a,0),null)},AuthenticationContext.prototype.getCachedUser=function(){if(this._user)return this._user;var a=this._getItem(this.CONSTANTS.STORAGE.IDTOKEN);return this._user=this._createUser(a),this._user},AuthenticationContext.prototype.registerCallback=function(a,b,c){this._activeRenewals[b]=a,window.callBacksMappedToRenewStates[a]||(window.callBacksMappedToRenewStates[a]=[]);var d=this;window.callBacksMappedToRenewStates[a].push(c),window.callBackMappedToRenewStates[a]||(window.callBackMappedToRenewStates[a]=function(c,e,f){for(var g=0;g-1)){var b=this._user.profile.upn.split("@");a+="&domain_hint="+encodeURIComponent(b[b.length-1])}return a},AuthenticationContext.prototype._createUser=function(a){var b=null,c=this._extractIdToken(a);return c&&c.hasOwnProperty("aud")&&(c.aud.toLowerCase()===this.config.clientId.toLowerCase()?(b={userName:"",profile:c},c.hasOwnProperty("upn")?b.userName=c.upn:c.hasOwnProperty("email")&&(b.userName=c.email)):this.warn("IdToken has invalid aud field")),b},AuthenticationContext.prototype._getHash=function(a){return a.indexOf("#/")>-1?a=a.substring(a.indexOf("#/")+2):a.indexOf("#")>-1&&(a=a.substring(1)),a},AuthenticationContext.prototype.isCallback=function(a){a=this._getHash(a);var b=this._deserialize(a);return b.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION)||b.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN)||b.hasOwnProperty(this.CONSTANTS.ID_TOKEN)},AuthenticationContext.prototype.getLoginError=function(){return this._getItem(this.CONSTANTS.STORAGE.LOGIN_ERROR)},AuthenticationContext.prototype.getRequestInfo=function(a){a=this._getHash(a);var b=this._deserialize(a),c={valid:!1,parameters:{},stateMatch:!1,stateResponse:"",requestType:this.REQUEST_TYPE.UNKNOWN};if(b&&(c.parameters=b,b.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION)||b.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN)||b.hasOwnProperty(this.CONSTANTS.ID_TOKEN))){c.valid=!0;var d="";if(!b.hasOwnProperty("state"))return this.warn("No state returned"),c;if(this.verbose("State: "+b.state),d=b.state,c.stateResponse=d,d===this._getItem(this.CONSTANTS.STORAGE.STATE_LOGIN))return c.requestType=this.REQUEST_TYPE.LOGIN,c.stateMatch=!0,c;if(!c.stateMatch&&window.parent&&window.parent.AuthenticationContext)for(var e=window.parent.AuthenticationContext()._renewStates,f=0;f-1&&b+1-1)return null;if(this.config&&this.config.endpoints)for(var c in this.config.endpoints)if(a.indexOf(c)>-1)return this.config.endpoints[c];return a.indexOf("http://")>-1||a.indexOf("https://")>-1?this._getHostFromUri(a)===this._getHostFromUri(this.config.redirectUri)?this.config.loginResource:null:this.config.loginResource},AuthenticationContext.prototype._getHostFromUri=function(a){var b=String(a).replace(/^(https?:)\/\//,"");return b=b.split("/")[0]},AuthenticationContext.prototype.handleWindowCallback=function(a){if(null==a&&(a=window.location.hash),this.isCallback(a)){var b=this.getRequestInfo(a);this.info("Returned from redirect url"),this.saveTokenFromHash(b);var c=null,d=null;b.requestType===this.REQUEST_TYPE.RENEW_TOKEN&&window.parent&&window.parent!==window?(this.verbose("Window is in iframe"),d=window.parent.callBackMappedToRenewStates[b.stateResponse],c=b.parameters[this.CONSTANTS.ACCESS_TOKEN]||b.parameters[this.CONSTANTS.ID_TOKEN]):b.requestType===this.REQUEST_TYPE.LOGIN&&(d=this.callback,c=b.parameters[this.CONSTANTS.ID_TOKEN]);try{d&&d(this._getItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION),c,this._getItem(this.CONSTANTS.STORAGE.ERROR))}catch(a){this.error("Error occurred in user defined callback function",a)}this.popUp||(window.location.hash="",this.config.navigateToLoginRequestUrl&&window.location.href.replace("#","")!==this._getItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST)&&(window.location.href=this._getItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST)))}},AuthenticationContext.prototype._getNavigateUrl=function(a,b){var c="common";this.config.tenant&&(c=this.config.tenant);var d=this.instance+c+"/oauth2/authorize"+this._serialize(a,this.config,b)+this._addLibMetadata();return this.info("Navigate url:"+d),d},AuthenticationContext.prototype._extractIdToken=function(a){var b=this._decodeJwt(a);if(!b)return null;try{var c=b.JWSPayload,d=this._base64DecodeStringUrlSafe(c);return d?JSON.parse(d):(this.info("The returned id_token could not be base64 url safe decoded."),null)}catch(a){this.error("The returned id_token could not be decoded",a)}return null},AuthenticationContext.prototype._base64DecodeStringUrlSafe=function(a){return a=a.replace(/-/g,"+").replace(/_/g,"/"),window.atob?decodeURIComponent(escape(window.atob(a))):decodeURIComponent(escape(this._decode(a)))},AuthenticationContext.prototype._decode=function(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";a=String(a).replace(/=+$/,"");var c=a.length;if(c%4===1)throw new Error("The token to be decoded is not correctly encoded.");for(var d,e,f,g,h,i,j,k,l="",m=0;m>16&255,j=h>>8&255,l+=String.fromCharCode(i,j);break}if(m+1===c-1){h=d<<18|e<<12,i=h>>16&255,l+=String.fromCharCode(i);break}h=d<<18|e<<12|f<<6|g,i=h>>16&255,j=h>>8&255,k=255&h,l+=String.fromCharCode(i,j,k)}return l},AuthenticationContext.prototype._decodeJwt=function(a){if(this._isEmpty(a))return null;var b=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/,c=b.exec(a);if(!c||c.length<4)return this.warn("The returned id_token is not parseable."),null;var d={header:c[1],JWSPayload:c[2],JWSSig:c[3]};return d},AuthenticationContext.prototype._convertUrlSafeToRegularBase64EncodedString=function(a){return a.replace("-","+").replace("_","/")},AuthenticationContext.prototype._serialize=function(a,b,c){var d=[];if(null!==b){d.push("?response_type="+a),d.push("client_id="+encodeURIComponent(b.clientId)),c&&d.push("resource="+encodeURIComponent(c)),d.push("redirect_uri="+encodeURIComponent(b.redirectUri)),d.push("state="+encodeURIComponent(b.state)),b.hasOwnProperty("slice")&&d.push("slice="+encodeURIComponent(b.slice)),b.hasOwnProperty("extraQueryParameter")&&d.push(b.extraQueryParameter);var e=b.correlationId?b.correlationId:this._guid();d.push("client-request-id="+encodeURIComponent(e))}return d.join("&")},AuthenticationContext.prototype._deserialize=function(a){var b,c=/\+/g,d=/([^&=]+)=([^&]*)/g,e=function(a){return decodeURIComponent(a.replace(c," "))},f={};for(b=d.exec(a);b;)f[e(b[1])]=e(b[2]),b=d.exec(a);return f},AuthenticationContext.prototype._decimalToHex=function(a){for(var b=a.toString(16);b.length<2;)b="0"+b;return b},AuthenticationContext.prototype._guid=function(){var a=window.crypto||window.msCrypto;if(a&&a.getRandomValues){var b=new Uint8Array(16);return a.getRandomValues(b),b[6]|=64,b[6]&=79,b[8]|=128,b[8]&=191,this._decimalToHex(b[0])+this._decimalToHex(b[1])+this._decimalToHex(b[2])+this._decimalToHex(b[3])+"-"+this._decimalToHex(b[4])+this._decimalToHex(b[5])+"-"+this._decimalToHex(b[6])+this._decimalToHex(b[7])+"-"+this._decimalToHex(b[8])+this._decimalToHex(b[9])+"-"+this._decimalToHex(b[10])+this._decimalToHex(b[11])+this._decimalToHex(b[12])+this._decimalToHex(b[13])+this._decimalToHex(b[14])+this._decimalToHex(b[15])}for(var c="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",d="0123456789abcdef",e=0,f="",g=0;g<36;g++)"-"!==c[g]&&"4"!==c[g]&&(e=16*Math.random()|0),"x"===c[g]?f+=d[e]:"y"===c[g]?(e&=3,e|=8,f+=d[e]):f+=c[g];return f},AuthenticationContext.prototype._expiresIn=function(a){return a||(a=3599),this._now()+parseInt(a,10)},AuthenticationContext.prototype._now=function(){return Math.round((new Date).getTime()/1e3)},AuthenticationContext.prototype._addAdalFrame=function(a){if("undefined"!=typeof a){this.info("Add adal frame to document:"+a);var b=document.getElementById(a);if(!b){if(document.createElement&&document.documentElement&&(window.opera||window.navigator.userAgent.indexOf("MSIE 5.0")===-1)){var c=document.createElement("iframe");c.setAttribute("id",a),c.style.visibility="hidden",c.style.position="absolute",c.style.width=c.style.height=c.borderWidth="0px",b=document.getElementsByTagName("body")[0].appendChild(c)}else document.body&&document.body.insertAdjacentHTML&&document.body.insertAdjacentHTML("beforeEnd",'');window.frames&&window.frames[a]&&(b=window.frames[a])}return b}},AuthenticationContext.prototype._saveItem=function(a,b){return this.config&&this.config.cacheLocation&&"localStorage"===this.config.cacheLocation?this._supportsLocalStorage()?(localStorage.setItem(a,b),!0):(this.info("Local storage is not supported"),!1):this._supportsSessionStorage()?(sessionStorage.setItem(a,b),!0):(this.info("Session storage is not supported"),!1)},AuthenticationContext.prototype._getItem=function(a){return this.config&&this.config.cacheLocation&&"localStorage"===this.config.cacheLocation?this._supportsLocalStorage()?localStorage.getItem(a):(this.info("Local storage is not supported"),null):this._supportsSessionStorage()?sessionStorage.getItem(a):(this.info("Session storage is not supported"),null)},AuthenticationContext.prototype._supportsLocalStorage=function(){try{var a="localStorage"in window&&window.localStorage;return a&&(window.localStorage.setItem("storageTest",""),window.localStorage.removeItem("storageTest")),a}catch(a){return!1}},AuthenticationContext.prototype._supportsSessionStorage=function(){try{var a="sessionStorage"in window&&window.sessionStorage;return a&&(window.sessionStorage.setItem("storageTest",""),window.sessionStorage.removeItem("storageTest")),a}catch(a){return!1}},AuthenticationContext.prototype._cloneConfig=function(a){if(null===a||"object"!=typeof a)return a;var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b},AuthenticationContext.prototype._addLibMetadata=function(){return"&x-client-SKU=Js&x-client-Ver="+this._libVersion()},AuthenticationContext.prototype.log=function(a,b,c){if(a<=Logging.level){var d=(new Date).toUTCString(),e="";e=this.config.correlationId?d+":"+this.config.correlationId+"-"+this._libVersion()+"-"+this.CONSTANTS.LEVEL_STRING_MAP[a]+" "+b:d+":"+this._libVersion()+"-"+this.CONSTANTS.LEVEL_STRING_MAP[a]+" "+b,c&&(e+="\nstack:\n"+c.stack),Logging.log(e)}},AuthenticationContext.prototype.error=function(a,b){this.log(this.CONSTANTS.LOGGING_LEVEL.ERROR,a,b)},AuthenticationContext.prototype.warn=function(a){this.log(this.CONSTANTS.LOGGING_LEVEL.WARN,a,null)},AuthenticationContext.prototype.info=function(a){this.log(this.CONSTANTS.LOGGING_LEVEL.INFO,a,null)},AuthenticationContext.prototype.verbose=function(a){this.log(this.CONSTANTS.LOGGING_LEVEL.VERBOSE,a,null)},AuthenticationContext.prototype._libVersion=function(){return"1.0.14"},"undefined"!=typeof module&&module.exports&&(module.exports=AuthenticationContext,module.exports.inject=function(a){return new AuthenticationContext(a)}),AuthenticationContext}();
\ No newline at end of file
+/*! adal-angular v1.0.15 2017-07-19 */
+var AuthenticationContext=function(){"use strict";return AuthenticationContext=function(a){if(this.REQUEST_TYPE={LOGIN:"LOGIN",RENEW_TOKEN:"RENEW_TOKEN",UNKNOWN:"UNKNOWN"},this.CONSTANTS={ACCESS_TOKEN:"access_token",EXPIRES_IN:"expires_in",ID_TOKEN:"id_token",ERROR_DESCRIPTION:"error_description",SESSION_STATE:"session_state",STORAGE:{TOKEN_KEYS:"adal.token.keys",ACCESS_TOKEN_KEY:"adal.access.token.key",EXPIRATION_KEY:"adal.expiration.key",STATE_LOGIN:"adal.state.login",STATE_RENEW:"adal.state.renew",NONCE_IDTOKEN:"adal.nonce.idtoken",SESSION_STATE:"adal.session.state",USERNAME:"adal.username",IDTOKEN:"adal.idtoken",ERROR:"adal.error",ERROR_DESCRIPTION:"adal.error.description",LOGIN_REQUEST:"adal.login.request",LOGIN_ERROR:"adal.login.error",RENEW_STATUS:"adal.token.renew.status"},RESOURCE_DELIMETER:"|",LOADFRAME_TIMEOUT:"6000",TOKEN_RENEW_STATUS_CANCELED:"Canceled",TOKEN_RENEW_STATUS_COMPLETED:"Completed",TOKEN_RENEW_STATUS_IN_PROGRESS:"In Progress",LOGGING_LEVEL:{ERROR:0,WARN:1,INFO:2,VERBOSE:3},LEVEL_STRING_MAP:{0:"ERROR:",1:"WARNING:",2:"INFO:",3:"VERBOSE:"},POPUP_WIDTH:483,POPUP_HEIGHT:600},AuthenticationContext.prototype._singletonInstance)return AuthenticationContext.prototype._singletonInstance;if(AuthenticationContext.prototype._singletonInstance=this,this.instance="https://login.microsoftonline.com/",this.config={},this.callback=null,this.popUp=!1,this.isAngular=!1,this._user=null,this._activeRenewals={},this._loginInProgress=!1,this._acquireTokenInProgress=!1,window.renewStates=[],window.callBackMappedToRenewStates={},window.callBacksMappedToRenewStates={},a.displayCall&&"function"!=typeof a.displayCall)throw new Error("displayCall is not a function");if(!a.clientId)throw new Error("clientId is required");this.config=this._cloneConfig(a),void 0===this.config.navigateToLoginRequestUrl&&(this.config.navigateToLoginRequestUrl=!0),this.config.popUp&&(this.popUp=!0),this.config.callback&&"function"==typeof this.config.callback&&(this.callback=this.config.callback),this.config.instance&&(this.instance=this.config.instance),this.config.loginResource||(this.config.loginResource=this.config.clientId),this.config.redirectUri||(this.config.redirectUri=window.location.href.split("?")[0].split("#")[0]),this.config.postLogoutRedirectUri||(this.config.postLogoutRedirectUri=window.location.href.split("?")[0].split("#")[0]),this.config.anonymousEndpoints||(this.config.anonymousEndpoints=[]),this.config.isAngular&&(this.isAngular=this.config.isAngular)},window.Logging={level:0,log:function(a){}},AuthenticationContext.prototype.login=function(a){if(this._loginInProgress)return void this.info("Login in progress");var b=this._guid();this.config.state=b,this._idTokenNonce=this._guid(),this.verbose("Expected state: "+b+" startPage:"+window.location.href),this._saveItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST,a||window.location.href),this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR,""),this._saveItem(this.CONSTANTS.STORAGE.STATE_LOGIN,b),this._saveItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN,this._idTokenNonce),this._saveItem(this.CONSTANTS.STORAGE.ERROR,""),this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION,"");var c=this._getNavigateUrl("id_token",null)+"&nonce="+encodeURIComponent(this._idTokenNonce);this._loginInProgress=!0,this.config.displayCall?this.config.displayCall(c):this.popUp?this._loginPopup(c):this.promptUser(c)},AuthenticationContext.prototype._openPopup=function(a,b,c,d){try{var e=window.screenLeft?window.screenLeft:window.screenX,f=window.screenTop?window.screenTop:window.screenY,g=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,h=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,i=g/2-c/2+e,j=h/2-d/2+f,k=window.open(a,b,"width="+c+", height="+d+", top="+j+", left="+i);return k.focus&&k.focus(),k}catch(a){return this.warn("Error opening popup, "+a.message),this._loginInProgress=!1,null}},AuthenticationContext.prototype._loginPopup=function(a,b,c){var d=this._openPopup(a,"login",this.CONSTANTS.POPUP_WIDTH,this.CONSTANTS.POPUP_HEIGHT),e=c||this.callback;if(null==d)return this.warn("Popup Window is null. This can happen if you are using IE"),this._saveItem(this.CONSTANTS.STORAGE.ERROR,"Error opening popup"),this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION,"Popup Window is null. This can happen if you are using IE"),this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR,"Popup Window is null. This can happen if you are using IE"),b&&this._activeRenewals[b]&&(this._activeRenewals[b]=null),this._loginInProgress=!1,this._acquireTokenInProgress=!1,void(e&&e(this._getItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION),null,this._getItem(this.CONSTANTS.STORAGE.ERROR)));if(-1!=this.config.redirectUri.indexOf("#"))var f=this.config.redirectUri.split("#")[0];else var f=this.config.redirectUri;var g=this,h=window.setInterval(function(){d&&!d.closed&&void 0!==d.closed||(g._loginInProgress=!1,g._acquireTokenInProgress=!1,b&&g._activeRenewals[b]&&(g._activeRenewals[b]=null),window.clearInterval(h));try{-1!=d.location.href.indexOf(f)&&(g.isAngular?g._onPopUpHashChanged(d.location.hash):g.handleWindowCallback(d.location.hash),window.clearInterval(h),g._loginInProgress=!1,g._acquireTokenInProgress=!1,g.info("Closing popup window"),d.close())}catch(a){}},1)},AuthenticationContext.prototype._onPopUpHashChanged=function(a){!function(){function a(a,b){b=b||{bubbles:!1,cancelable:!1,detail:void 0};var c=document.createEvent("CustomEvent");return c.initCustomEvent(a,b.bubbles,b.cancelable,b.detail),c}if("function"==typeof window.CustomEvent)return!1;a.prototype=window.Event.prototype,window.CustomEvent=a}();var b=new CustomEvent("adal:popUpHashChanged",{detail:a});window.dispatchEvent(b)},AuthenticationContext.prototype.loginInProgress=function(){return this._loginInProgress},AuthenticationContext.prototype._hasResource=function(a){var b=this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS);return b&&!this._isEmpty(b)&&b.indexOf(a+this.CONSTANTS.RESOURCE_DELIMETER)>-1},AuthenticationContext.prototype.getCachedToken=function(a){if(!this._hasResource(a))return null;var b=this._getItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY+a),c=this._getItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY+a),d=this.config.expireOffsetSeconds||300;return c&&c>this._now()+d?b:(this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY+a,""),this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY+a,0),null)},AuthenticationContext.prototype.getCachedUser=function(){if(this._user)return this._user;var a=this._getItem(this.CONSTANTS.STORAGE.IDTOKEN);return this._user=this._createUser(a),this._user},AuthenticationContext.prototype.registerCallback=function(a,b,c){this._activeRenewals[b]=a,window.callBacksMappedToRenewStates[a]||(window.callBacksMappedToRenewStates[a]=[]);var d=this;window.callBacksMappedToRenewStates[a].push(c),window.callBackMappedToRenewStates[a]||(window.callBackMappedToRenewStates[a]=function(c,e,f){d._activeRenewals[b]=null;for(var g=0;g-1)){var b=this._user.profile.upn.split("@");a+="&domain_hint="+encodeURIComponent(b[b.length-1])}return a},AuthenticationContext.prototype._createUser=function(a){var b=null,c=this._extractIdToken(a);return c&&c.hasOwnProperty("aud")&&(c.aud.toLowerCase()===this.config.clientId.toLowerCase()?(b={userName:"",profile:c},c.hasOwnProperty("upn")?b.userName=c.upn:c.hasOwnProperty("email")&&(b.userName=c.email)):this.warn("IdToken has invalid aud field")),b},AuthenticationContext.prototype._getHash=function(a){return a.indexOf("#/")>-1?a=a.substring(a.indexOf("#/")+2):a.indexOf("#")>-1&&(a=a.substring(1)),a},AuthenticationContext.prototype.isCallback=function(a){a=this._getHash(a);var b=this._deserialize(a);return b.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION)||b.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN)||b.hasOwnProperty(this.CONSTANTS.ID_TOKEN)},AuthenticationContext.prototype.getLoginError=function(){return this._getItem(this.CONSTANTS.STORAGE.LOGIN_ERROR)},AuthenticationContext.prototype.getRequestInfo=function(a){a=this._getHash(a);var b=this._deserialize(a),c={valid:!1,parameters:{},stateMatch:!1,stateResponse:"",requestType:this.REQUEST_TYPE.UNKNOWN};if(b&&(c.parameters=b,b.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION)||b.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN)||b.hasOwnProperty(this.CONSTANTS.ID_TOKEN))){c.valid=!0;var d="";if(!b.hasOwnProperty("state"))return this.warn("No state returned"),c;if(this.verbose("State: "+b.state),d=b.state,c.stateResponse=d,d===this._getItem(this.CONSTANTS.STORAGE.STATE_LOGIN))return c.requestType=this.REQUEST_TYPE.LOGIN,c.stateMatch=!0,c;if(d===this._getItem(this.CONSTANTS.STORAGE.STATE_RENEW))return c.requestType=this.REQUEST_TYPE.RENEW_TOKEN,c.stateMatch=!0,c;if(!c.stateMatch&&window.parent)for(var e=window.parent.renewStates,f=0;f-1&&b+1-1)return null;if(this.config&&this.config.endpoints)for(var c in this.config.endpoints)if(a.indexOf(c)>-1)return this.config.endpoints[c];return a.indexOf("http://")>-1||a.indexOf("https://")>-1?this._getHostFromUri(a)===this._getHostFromUri(this.config.redirectUri)?this.config.loginResource:null:this.config.loginResource},AuthenticationContext.prototype._getHostFromUri=function(a){var b=String(a).replace(/^(https?:)\/\//,"");return b=b.split("/")[0]},AuthenticationContext.prototype.handleWindowCallback=function(a){if(null==a&&(a=window.location.hash),this.isCallback(a)){var b=this.getRequestInfo(a);this.info("Returned from redirect url"),this.saveTokenFromHash(b);var c=null,d=null;b.requestType===this.REQUEST_TYPE.RENEW_TOKEN&&window.parent?(this.verbose("Window is in iframe"),d=window.parent.callBackMappedToRenewStates[b.stateResponse],c=b.parameters[this.CONSTANTS.ACCESS_TOKEN]||b.parameters[this.CONSTANTS.ID_TOKEN]):b.requestType===this.REQUEST_TYPE.LOGIN&&(d=this.callback,c=b.parameters[this.CONSTANTS.ID_TOKEN]);try{d&&d(this._getItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION),c,this._getItem(this.CONSTANTS.STORAGE.ERROR))}catch(a){this.error("Error occurred in user defined callback function",a)}this.popUp||(window.location.hash="",this.config.navigateToLoginRequestUrl&&(window.location.href=this._getItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST)))}},AuthenticationContext.prototype._getNavigateUrl=function(a,b){var c="common";this.config.tenant&&(c=this.config.tenant);var d=this.instance+c+"/oauth2/authorize"+this._serialize(a,this.config,b)+this._addLibMetadata();return this.info("Navigate url:"+d),d},AuthenticationContext.prototype._extractIdToken=function(a){var b=this._decodeJwt(a);if(!b)return null;try{var c=b.JWSPayload,d=this._base64DecodeStringUrlSafe(c);return d?JSON.parse(d):(this.info("The returned id_token could not be base64 url safe decoded."),null)}catch(a){this.error("The returned id_token could not be decoded",a)}return null},AuthenticationContext.prototype._base64DecodeStringUrlSafe=function(a){return a=a.replace(/-/g,"+").replace(/_/g,"/"),window.atob?decodeURIComponent(escape(window.atob(a))):decodeURIComponent(escape(this._decode(a)))},AuthenticationContext.prototype._decode=function(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";a=String(a).replace(/=+$/,"");var c=a.length;if(c%4==1)throw new Error("The token to be decoded is not correctly encoded.");for(var d,e,f,g,h,i,j,k,l="",m=0;m>16&255,j=h>>8&255,l+=String.fromCharCode(i,j);break}if(m+1===c-1){h=d<<18|e<<12,i=h>>16&255,l+=String.fromCharCode(i);break}h=d<<18|e<<12|f<<6|g,i=h>>16&255,j=h>>8&255,k=255&h,l+=String.fromCharCode(i,j,k)}return l},AuthenticationContext.prototype._decodeJwt=function(a){if(this._isEmpty(a))return null;var b=/^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/,c=b.exec(a);return!c||c.length<4?(this.warn("The returned id_token is not parseable."),null):{header:c[1],JWSPayload:c[2],JWSSig:c[3]}},AuthenticationContext.prototype._convertUrlSafeToRegularBase64EncodedString=function(a){return a.replace("-","+").replace("_","/")},AuthenticationContext.prototype._serialize=function(a,b,c){var d=[];if(null!==b){d.push("?response_type="+a),d.push("client_id="+encodeURIComponent(b.clientId)),c&&d.push("resource="+encodeURIComponent(c)),d.push("redirect_uri="+encodeURIComponent(b.redirectUri)),d.push("state="+encodeURIComponent(b.state)),b.hasOwnProperty("slice")&&d.push("slice="+encodeURIComponent(b.slice)),b.hasOwnProperty("extraQueryParameter")&&d.push(b.extraQueryParameter);var e=b.correlationId?b.correlationId:this._guid();d.push("client-request-id="+encodeURIComponent(e))}return d.join("&")},AuthenticationContext.prototype._deserialize=function(a){var b,c=/\+/g,d=/([^&=]+)=([^&]*)/g,e=function(a){return decodeURIComponent(a.replace(c," "))},f={};for(b=d.exec(a);b;)f[e(b[1])]=e(b[2]),b=d.exec(a);return f},AuthenticationContext.prototype._decimalToHex=function(a){for(var b=a.toString(16);b.length<2;)b="0"+b;return b},AuthenticationContext.prototype._guid=function(){var a=window.crypto||window.msCrypto;if(a&&a.getRandomValues){var b=new Uint8Array(16);return a.getRandomValues(b),b[6]|=64,b[6]&=79,b[8]|=128,b[8]&=191,this._decimalToHex(b[0])+this._decimalToHex(b[1])+this._decimalToHex(b[2])+this._decimalToHex(b[3])+"-"+this._decimalToHex(b[4])+this._decimalToHex(b[5])+"-"+this._decimalToHex(b[6])+this._decimalToHex(b[7])+"-"+this._decimalToHex(b[8])+this._decimalToHex(b[9])+"-"+this._decimalToHex(b[10])+this._decimalToHex(b[11])+this._decimalToHex(b[12])+this._decimalToHex(b[13])+this._decimalToHex(b[14])+this._decimalToHex(b[15])}for(var c="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx",d="0123456789abcdef",e=0,f="",g=0;g<36;g++)"-"!==c[g]&&"4"!==c[g]&&(e=16*Math.random()|0),"x"===c[g]?f+=d[e]:"y"===c[g]?(e&=3,e|=8,f+=d[e]):f+=c[g];return f},AuthenticationContext.prototype._expiresIn=function(a){return a||(a=3599),this._now()+parseInt(a,10)},AuthenticationContext.prototype._now=function(){return Math.round((new Date).getTime()/1e3)},AuthenticationContext.prototype._addAdalFrame=function(a){if(void 0!==a){this.info("Add adal frame to document:"+a);var b=document.getElementById(a);if(!b){if(document.createElement&&document.documentElement&&(window.opera||-1===window.navigator.userAgent.indexOf("MSIE 5.0"))){var c=document.createElement("iframe");c.setAttribute("id",a),c.style.visibility="hidden",c.style.position="absolute",c.style.width=c.style.height=c.borderWidth="0px",b=document.getElementsByTagName("body")[0].appendChild(c)}else document.body&&document.body.insertAdjacentHTML&&document.body.insertAdjacentHTML("beforeEnd",'');window.frames&&window.frames[a]&&(b=window.frames[a])}return b}},AuthenticationContext.prototype._saveItem=function(a,b){return this.config&&this.config.cacheLocation&&"localStorage"===this.config.cacheLocation?this._supportsLocalStorage()?(localStorage.setItem(a,b),!0):(this.info("Local storage is not supported"),!1):this._supportsSessionStorage()?(sessionStorage.setItem(a,b),!0):(this.info("Session storage is not supported"),!1)},AuthenticationContext.prototype._getItem=function(a){return this.config&&this.config.cacheLocation&&"localStorage"===this.config.cacheLocation?this._supportsLocalStorage()?localStorage.getItem(a):(this.info("Local storage is not supported"),null):this._supportsSessionStorage()?sessionStorage.getItem(a):(this.info("Session storage is not supported"),null)},AuthenticationContext.prototype._supportsLocalStorage=function(){try{return!!window.localStorage&&(window.localStorage.setItem("storageTest","A"),"A"==window.localStorage.getItem("storageTest")&&(window.localStorage.removeItem("storageTest"),!window.localStorage.getItem("storageTest")))}catch(a){return!1}},AuthenticationContext.prototype._supportsSessionStorage=function(){try{return!!window.sessionStorage&&(window.sessionStorage.setItem("storageTest","A"),"A"==window.sessionStorage.getItem("storageTest")&&(window.sessionStorage.removeItem("storageTest"),!window.sessionStorage.getItem("storageTest")))}catch(a){return!1}},AuthenticationContext.prototype._cloneConfig=function(a){if(null===a||"object"!=typeof a)return a;var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b},AuthenticationContext.prototype._addLibMetadata=function(){return"&x-client-SKU=Js&x-client-Ver="+this._libVersion()},AuthenticationContext.prototype.log=function(a,b,c){if(a<=Logging.level){var d=(new Date).toUTCString(),e="";e=this.config.correlationId?d+":"+this.config.correlationId+"-"+this._libVersion()+"-"+this.CONSTANTS.LEVEL_STRING_MAP[a]+" "+b:d+":"+this._libVersion()+"-"+this.CONSTANTS.LEVEL_STRING_MAP[a]+" "+b,c&&(e+="\nstack:\n"+c.stack),Logging.log(e)}},AuthenticationContext.prototype.error=function(a,b){this.log(this.CONSTANTS.LOGGING_LEVEL.ERROR,a,b)},AuthenticationContext.prototype.warn=function(a){this.log(this.CONSTANTS.LOGGING_LEVEL.WARN,a,null)},AuthenticationContext.prototype.info=function(a){this.log(this.CONSTANTS.LOGGING_LEVEL.INFO,a,null)},AuthenticationContext.prototype.verbose=function(a){this.log(this.CONSTANTS.LOGGING_LEVEL.VERBOSE,a,null)},AuthenticationContext.prototype._libVersion=function(){return"1.0.15"},"undefined"!=typeof module&&module.exports&&(module.exports=AuthenticationContext,module.exports.inject=function(a){return new AuthenticationContext(a)}),AuthenticationContext}();
\ No newline at end of file
diff --git a/lib/adal-angular.js b/lib/adal-angular.js
index e23183dc..0faa2319 100644
--- a/lib/adal-angular.js
+++ b/lib/adal-angular.js
@@ -1,5 +1,5 @@
//----------------------------------------------------------------------
-// AdalJS v1.0.14
+// AdalJS v1.0.15
// @preserve Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
@@ -75,7 +75,7 @@
else {
var hash = '#' + $location.path();
}
- processHash(hash);
+ processHash(hash, event);
$timeout(function () {
updateDataFromCache(_adal.config.loginResource);
@@ -83,7 +83,7 @@
}, 1);
};
- var processHash = function (hash) {
+ var processHash = function (hash, event) {
if (_adal.isCallback(hash)) {
// callback can come from login or iframe request
_adal.verbose('Processing the hash: ' + hash);
@@ -92,21 +92,31 @@
// Return to callback if it is sent from iframe
if (requestInfo.stateMatch) {
if (requestInfo.requestType === _adal.REQUEST_TYPE.RENEW_TOKEN) {
- var callback = $window.parent.callBackMappedToRenewStates[requestInfo.stateResponse];
+ _adal._renewActive = false;
+ var callback = $window.parent.callBackMappedToRenewStates[requestInfo.stateResponse] || _adal.callback;
// since this is a token renewal request in iFrame, we don't need to proceed with the location change.
- event.preventDefault();
+ if (event && event.preventDefault) {
+ if (window.parent !== window) {//if token renewal request is made in an iframe
+ event.preventDefault();
+ }
+ }
// Call within the same context without full page redirect keeps the callback
if (callback && typeof callback === 'function') {
// id_token or access_token can be renewed
- if (requestInfo.parameters['access_token']) {
- callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['access_token'], _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR));
- return;
- } else if (requestInfo.parameters['id_token']) {
- callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['id_token'], _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR));
- return;
- } else if (requestInfo.parameters['error']) {
- callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), null, _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR));
+ var token = requestInfo.parameters['access_token'] || requestInfo.parameters['id_token'];
+ var error = requestInfo.parameters['error'];
+ var errorDescription = requestInfo.parameters['error_description'];
+ if ($window.parent === $window && !$window.parent.callBackMappedToRenewStates[requestInfo.stateResponse]) {
+ if (token) {
+ $rootScope.$broadcast('adal:acquireTokenSuccess', token);
+ }
+ else if (error && errorDescription) {
+ $rootScope.$broadcast('adal:acquireTokenFailure', error, errorDescription);
+ }
+ }
+ callback(errorDescription, token, error);
+ if (window.parent !== window) {//in iframe
return;
}
}
@@ -127,28 +137,27 @@
if (_adal.callback && typeof _adal.callback === 'function')
_adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), _adal._getItem(_adal.CONSTANTS.STORAGE.IDTOKEN), _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR));
-
- // redirect to login start page
- if (!_adal.popUp) {
- if (_adal.config.navigateToLoginRequestUrl) {
- var loginStartPage = _adal._getItem(_adal.CONSTANTS.STORAGE.LOGIN_REQUEST);
- if (typeof loginStartPage !== 'undefined' && loginStartPage && loginStartPage.length !== 0) {
- // prevent the current location change and redirect the user back to the login start page
- _adal.verbose('Redirecting to start page: ' + loginStartPage);
- if (!$location.$$html5 && loginStartPage.indexOf('#') > -1) {
- $location.url(loginStartPage.substring(loginStartPage.indexOf('#') + 1));
- }
- $window.location.href = loginStartPage;
+ }
+ // redirect to login start page
+ if (!_adal.popUp && window.parent === window) {
+ if (_adal.config.navigateToLoginRequestUrl) {
+ var loginStartPage = _adal._getItem(_adal.CONSTANTS.STORAGE.LOGIN_REQUEST);
+ if (typeof loginStartPage !== 'undefined' && loginStartPage && loginStartPage.length !== 0) {
+ // prevent the current location change and redirect the user back to the login start page
+ _adal.verbose('Redirecting to start page: ' + loginStartPage);
+ if (!$location.$$html5 && loginStartPage.indexOf('#') > -1) {
+ $location.url(loginStartPage.substring(loginStartPage.indexOf('#') + 1));
}
+ $window.location.href = loginStartPage;
+ }
+ }
+ else {
+ // resetting the hash to null
+ if ($location.$$html5) {
+ $location.hash('');
}
else {
- // resetting the hash to null
- if ($location.$$html5) {
- $location.hash('');
- }
- else {
- $location.path('');
- }
+ $location.path('');
}
}
}
@@ -345,6 +354,27 @@
return deferred.promise;
},
+
+ acquireTokenPopup: function (resource, extraQueryParameters, claims) {
+ var deferred = $q.defer();
+ _adal.acquireTokenPopup(resource, extraQueryParameters, claims, function (errorDesc, tokenOut, error) {
+ if (error) {
+ $rootScope.$broadcast('adal:acquireTokenFailure', errorDesc, error);
+ _adal.error('Error when acquiring token for resource: ' + resource, error);
+ deferred.reject(errorDesc + "|" + error);
+ } else {
+ $rootScope.$broadcast('adal:acquireTokenSuccess', tokenOut);
+ deferred.resolve(tokenOut);
+ }
+ });
+
+ return deferred.promise;
+ },
+
+ acquireTokenRedirect: function (resource, extraQueryParameters, claims) {
+ _adal.acquireTokenRedirect(resource, extraQueryParameters, claims);
+ },
+
getUser: function () {
var deferred = $q.defer();
_adal.getUser(function (error, user) {
diff --git a/lib/adal.js b/lib/adal.js
index 12a839f5..1eb9d8ec 100644
--- a/lib/adal.js
+++ b/lib/adal.js
@@ -1,5 +1,5 @@
//----------------------------------------------------------------------
-// AdalJS v1.0.14
+// AdalJS v1.0.15
// @preserve Copyright (c) Microsoft Open Technologies, Inc.
// All Rights Reserved
// Apache License 2.0
@@ -9,7 +9,7 @@
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
-//
+//id
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -119,8 +119,9 @@ var AuthenticationContext = (function () {
this._user = null;
this._activeRenewals = {};
this._loginInProgress = false;
- this._renewStates = [];
+ this._acquireTokenInProgress = false;
+ window.renewStates = [];
window.callBackMappedToRenewStates = {};
window.callBacksMappedToRenewStates = {};
@@ -206,7 +207,7 @@ var AuthenticationContext = (function () {
else if (this.popUp) {
this._loginPopup(urlNavigate);
}
- else {
+ else {
this.promptUser(urlNavigate);
}
};
@@ -249,15 +250,21 @@ var AuthenticationContext = (function () {
* attached to the URI fragment as an id_token field. It closes popup window after redirection.
* @ignore
*/
- AuthenticationContext.prototype._loginPopup = function (urlNavigate) {
+ AuthenticationContext.prototype._loginPopup = function (urlNavigate, resource, callback) {
var popupWindow = this._openPopup(urlNavigate, "login", this.CONSTANTS.POPUP_WIDTH, this.CONSTANTS.POPUP_HEIGHT);
+ var loginCallback = callback || this.callback;
if (popupWindow == null) {
this.warn('Popup Window is null. This can happen if you are using IE');
this._saveItem(this.CONSTANTS.STORAGE.ERROR, 'Error opening popup');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, 'Popup Window is null. This can happen if you are using IE');
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'Popup Window is null. This can happen if you are using IE');
- if (this.callback)
- this.callback(this._getItem(this.CONSTANTS.STORAGE.LOGIN_ERROR), null, this._getItem(this.CONSTANTS.STORAGE.ERROR));
+ if (resource && this._activeRenewals[resource]) {
+ this._activeRenewals[resource] = null;
+ }
+ this._loginInProgress = false;
+ this._acquireTokenInProgress = false;
+ if (loginCallback)
+ loginCallback(this._getItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION), null, this._getItem(this.CONSTANTS.STORAGE.ERROR));
return;
}
if (this.config.redirectUri.indexOf('#') != -1)
@@ -268,6 +275,10 @@ var AuthenticationContext = (function () {
var pollTimer = window.setInterval(function () {
if (!popupWindow || popupWindow.closed || popupWindow.closed === undefined) {
that._loginInProgress = false;
+ that._acquireTokenInProgress = false;
+ if (resource && that._activeRenewals[resource]) {
+ that._activeRenewals[resource] = null;
+ }
window.clearInterval(pollTimer);
}
try {
@@ -280,15 +291,34 @@ var AuthenticationContext = (function () {
}
window.clearInterval(pollTimer);
that._loginInProgress = false;
+ that._acquireTokenInProgress = false;
that.info("Closing popup window");
popupWindow.close();
}
} catch (e) {
}
- }, 20);
+ }, 1);
};
AuthenticationContext.prototype._onPopUpHashChanged = function (hash) {
+ // Custom Event is not supported in IE, below IIFE will polyfill the CustomEvent() constructor functionality in Internet Explorer 9 and higher
+ (function () {
+
+ if (typeof window.CustomEvent === "function") {
+ return false;
+ }
+
+ function CustomEvent(event, params) {
+ params = params || { bubbles: false, cancelable: false, detail: undefined };
+ var evt = document.createEvent('CustomEvent');
+ evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
+ return evt;
+ }
+
+ CustomEvent.prototype = window.Event.prototype;
+ window.CustomEvent = CustomEvent;
+ })();
+
var evt = new CustomEvent('adal:popUpHashChanged', { detail: hash });
window.dispatchEvent(evt);
};
@@ -368,6 +398,8 @@ var AuthenticationContext = (function () {
window.callBacksMappedToRenewStates[expectedState].push(callback);
if (!window.callBackMappedToRenewStates[expectedState]) {
window.callBackMappedToRenewStates[expectedState] = function (errorDesc, token, error) {
+ self._activeRenewals[resource] = null;
+
for (var i = 0; i < window.callBacksMappedToRenewStates[expectedState].length; ++i) {
try {
window.callBacksMappedToRenewStates[expectedState][i](errorDesc, token, error);
@@ -376,7 +408,6 @@ var AuthenticationContext = (function () {
self.warn(error);
}
}
- self._activeRenewals[resource] = null;
window.callBacksMappedToRenewStates[expectedState] = null;
window.callBackMappedToRenewStates[expectedState] = null;
};
@@ -399,7 +430,7 @@ var AuthenticationContext = (function () {
var expectedState = this._guid() + '|' + resource;
this.config.state = expectedState;
// renew happens in iframe, so it keeps javascript context
- this._renewStates.push(expectedState);
+ window.renewStates.push(expectedState);
this.verbose('Renew token Expected state: ' + expectedState);
var urlNavigate = this._getNavigateUrl('token', resource) + '&prompt=none';
@@ -425,7 +456,7 @@ var AuthenticationContext = (function () {
this._saveItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN, this._idTokenNonce);
this.config.state = expectedState;
// renew happens in iframe, so it keeps javascript context
- this._renewStates.push(expectedState);
+ window.renewStates.push(expectedState);
this.verbose('Renew Idtoken Expected state: ' + expectedState);
var urlNavigate = this._getNavigateUrl('id_token', null) + '&prompt=none';
@@ -544,6 +575,104 @@ var AuthenticationContext = (function () {
};
/**
+ * Acquires token (interactive flow using a popUp window) by sending request to AAD to obtain a new token.
+ * @param {string} resource ResourceUri identifying the target resource
+ * @param {string} extraQueryParameters extraQueryParameters to add to the authentication request
+ * @param {tokenCallback} callback - The callback provided by the caller. It will be called with token or error.
+ */
+ AuthenticationContext.prototype.acquireTokenPopup = function (resource, extraQueryParameters, claims, callback) {
+ if (this._isEmpty(resource)) {
+ this.warn('resource is required');
+ callback('resource is required', null, 'resource is required');
+ return;
+ }
+
+ if (!this._user) {
+ this.warn('User login is required');
+ callback('User login is required', null, 'login required');
+ return;
+ }
+
+ if (this._acquireTokenInProgress) {
+ this.warn("Acquire token interactive is already in progress")
+ callback("Acquire token interactive is already in progress", null, "Acquire token interactive is already in progress");
+ return;
+ }
+
+ var expectedState = this._guid() + '|' + resource;
+ this.config.state = expectedState;
+ window.renewStates.push(expectedState);
+ this.verbose('Renew token Expected state: ' + expectedState);
+ var urlNavigate = this._getNavigateUrl('token', resource) + '&prompt=select_account';
+ if (extraQueryParameters) {
+ urlNavigate += encodeURIComponent(extraQueryParameters);
+ }
+
+ if (claims && (urlNavigate.indexOf("&claims") === -1)) {
+ urlNavigate += '&claims=' + encodeURIComponent(claims);
+ }
+ else if (claims && (urlNavigate.indexOf("&claims") !== -1)) {
+ throw new Error('Claims cannot be passed as an extraQueryParameter');
+ }
+
+ urlNavigate = this._addHintParameters(urlNavigate);
+ this._acquireTokenInProgress = true;
+ this.info('acquireToken interactive is called for the resource ' + resource);
+ this.registerCallback(expectedState, resource, callback);
+ this._loginPopup(urlNavigate, resource, callback);
+
+ };
+
+ /**
+ * Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the Authentication
+ * request constructor will be called.
+ * @param {string} resource ResourceUri identifying the target resource
+ * @param {string} extraQueryParameters extraQueryParameters to add to the authentication request
+ */
+ AuthenticationContext.prototype.acquireTokenRedirect = function (resource, extraQueryParameters, claims) {
+ if (this._isEmpty(resource)) {
+ this.warn('resource is required');
+ callback('resource is required', null, 'resource is required');
+ return;
+ }
+
+ if (!this._user) {
+ this.warn('User login is required');
+ callback('User login is required', null, 'login required');
+ return;
+ }
+
+ if (this._acquireTokenInProgress) {
+ this.warn("Acquire token interactive is already in progress")
+ callback("Acquire token interactive is already in progress", null, "Acquire token interactive is already in progress");
+ return;
+ }
+
+ var expectedState = this._guid() + '|' + resource;
+ this.config.state = expectedState;
+ window.renewStates.push(expectedState);
+ this.verbose('Renew token Expected state: ' + expectedState);
+ var urlNavigate = this._getNavigateUrl('token', resource) + '&prompt=select_account';
+ if (extraQueryParameters) {
+ urlNavigate += encodeURIComponent(extraQueryParameters);
+ }
+
+ if (claims && (urlNavigate.indexOf("&claims") === -1)) {
+ urlNavigate += '&claims=' + encodeURIComponent(claims);
+ }
+ else if (claims && (urlNavigate.indexOf("&claims") !== -1)) {
+ throw new Error('Claims cannot be passed as an extraQueryParameter');
+ }
+
+ urlNavigate = this._addHintParameters(urlNavigate);
+ this._acquireTokenInProgress = true;
+ this.info('acquireToken interactive is called for the resource ' + resource);
+
+ this._saveItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST, window.location.href);
+ this._saveItem(this.CONSTANTS.STORAGE.STATE_RENEW, expectedState);
+ this.promptUser(urlNavigate);
+ };
+ /**
* Redirects the browser to Azure AD authorization endpoint.
* @param {string} urlNavigate Url of the authorization endpoint.
*/
@@ -564,7 +693,7 @@ var AuthenticationContext = (function () {
this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY, 0);
this._saveItem(this.CONSTANTS.STORAGE.SESSION_STATE, '');
this._saveItem(this.CONSTANTS.STORAGE.STATE_LOGIN, '');
- this._renewStates = [];
+ window.renewStates = [];
this._saveItem(this.CONSTANTS.STORAGE.USERNAME, '');
this._saveItem(this.CONSTANTS.STORAGE.IDTOKEN, '');
this._saveItem(this.CONSTANTS.STORAGE.ERROR, '');
@@ -672,8 +801,11 @@ var AuthenticationContext = (function () {
// include hint params only if upn is present
if (this._user && this._user.profile && this._user.profile.hasOwnProperty('upn')) {
- // add login_hint
- urlNavigate += '&login_hint=' + encodeURIComponent(this._user.profile.upn);
+ // don't add login_hint twice if user provided it in the extraQueryParameter value
+ if (!this._urlContainsQueryStringParameter("login_hint", urlNavigate)) {
+ // add login_hint
+ urlNavigate += '&login_hint=' + encodeURIComponent(this._user.profile.upn);
+ }
// don't add domain_hint twice if user provided it in the extraQueryParameter value
if (!this._urlContainsQueryStringParameter("domain_hint", urlNavigate) && this._user.profile.upn.indexOf('@') > -1) {
@@ -804,9 +936,15 @@ var AuthenticationContext = (function () {
return requestInfo;
}
+ else if (stateResponse === this._getItem(this.CONSTANTS.STORAGE.STATE_RENEW)) {
+ requestInfo.requestType = this.REQUEST_TYPE.RENEW_TOKEN;
+ requestInfo.stateMatch = true;
+ return requestInfo;
+ }
+
// external api requests may have many renewtoken requests for different resource
- if (!requestInfo.stateMatch && window.parent && window.parent.AuthenticationContext) {
- var statesInParentContext = window.parent.AuthenticationContext()._renewStates;
+ if (!requestInfo.stateMatch && window.parent) {
+ var statesInParentContext = window.parent.renewStates;
for (var i = 0; i < statesInParentContext.length; i++) {
if (statesInParentContext[i] === requestInfo.stateResponse) {
requestInfo.requestType = this.REQUEST_TYPE.RENEW_TOKEN;
@@ -985,7 +1123,7 @@ var AuthenticationContext = (function () {
this.info('Returned from redirect url');
this.saveTokenFromHash(requestInfo);
var token = null, callback = null;
- if ((requestInfo.requestType === this.REQUEST_TYPE.RENEW_TOKEN) && window.parent && (window.parent !== window)) {
+ if ((requestInfo.requestType === this.REQUEST_TYPE.RENEW_TOKEN) && window.parent) {
// iframe call but same single page
this.verbose('Window is in iframe');
callback = window.parent.callBackMappedToRenewStates[requestInfo.stateResponse];
@@ -1002,7 +1140,7 @@ var AuthenticationContext = (function () {
}
if (!this.popUp) {
window.location.hash = '';
- if (this.config.navigateToLoginRequestUrl && window.location.href.replace('#', '') !== this._getItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST))
+ if (this.config.navigateToLoginRequestUrl)
window.location.href = this._getItem(this.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
}
@@ -1093,7 +1231,7 @@ var AuthenticationContext = (function () {
decoded += String.fromCharCode(c1, c2);
break;
}
- // if last one is '='
+ // if last one is '='
else if (i + 1 === length - 1) {
bits = h1 << 18 | h2 << 12
c1 = bits >> 16 & 255;
@@ -1250,7 +1388,7 @@ var AuthenticationContext = (function () {
buffer[8] |= 0x80; //buffer[8] | 10000000 will set the 7 bit to 1.
buffer[8] &= 0xbf; //buffer[8] & 10111111 will set the 6 bit to 0.
return this._decimalToHex(buffer[0]) + this._decimalToHex(buffer[1]) + this._decimalToHex(buffer[2]) + this._decimalToHex(buffer[3]) + '-' + this._decimalToHex(buffer[4]) + this._decimalToHex(buffer[5]) + '-' + this._decimalToHex(buffer[6]) + this._decimalToHex(buffer[7]) + '-' +
- this._decimalToHex(buffer[8]) + this._decimalToHex(buffer[9]) + '-' + this._decimalToHex(buffer[10]) + this._decimalToHex(buffer[11]) + this._decimalToHex(buffer[12]) + this._decimalToHex(buffer[13]) + this._decimalToHex(buffer[14]) + this._decimalToHex(buffer[15]);
+ this._decimalToHex(buffer[8]) + this._decimalToHex(buffer[9]) + '-' + this._decimalToHex(buffer[10]) + this._decimalToHex(buffer[11]) + this._decimalToHex(buffer[12]) + this._decimalToHex(buffer[13]) + this._decimalToHex(buffer[14]) + this._decimalToHex(buffer[15]);
}
else {
var guidHolder = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
@@ -1389,12 +1527,12 @@ var AuthenticationContext = (function () {
*/
AuthenticationContext.prototype._supportsLocalStorage = function () {
try {
- var supportsLocalStorage = 'localStorage' in window && window['localStorage'];
- if (supportsLocalStorage) {
- window.localStorage.setItem('storageTest', '');
- window.localStorage.removeItem('storageTest');
- }
- return supportsLocalStorage;
+ if (!window.localStorage) return false; // Test availability
+ window.localStorage.setItem('storageTest', 'A'); // Try write
+ if (window.localStorage.getItem('storageTest') != 'A') return false; // Test read/write
+ window.localStorage.removeItem('storageTest'); // Try delete
+ if (window.localStorage.getItem('storageTest')) return false; // Test delete
+ return true; // Success
} catch (e) {
return false;
}
@@ -1406,12 +1544,12 @@ var AuthenticationContext = (function () {
*/
AuthenticationContext.prototype._supportsSessionStorage = function () {
try {
- var supportsSessionStorage = 'sessionStorage' in window && window['sessionStorage'];
- if (supportsSessionStorage) {
- window.sessionStorage.setItem('storageTest', '');
- window.sessionStorage.removeItem('storageTest');
- }
- return supportsSessionStorage;
+ if (!window.sessionStorage) return false; // Test availability
+ window.sessionStorage.setItem('storageTest', 'A'); // Try write
+ if (window.sessionStorage.getItem('storageTest') != 'A') return false; // Test read/write
+ window.sessionStorage.removeItem('storageTest'); // Try delete
+ if (window.sessionStorage.getItem('storageTest')) return false; // Test delete
+ return true; // Success
} catch (e) {
return false;
}
@@ -1507,7 +1645,7 @@ var AuthenticationContext = (function () {
* @ignore
*/
AuthenticationContext.prototype._libVersion = function () {
- return '1.0.14';
+ return '1.0.15';
};
/**
@@ -1524,5 +1662,3 @@ var AuthenticationContext = (function () {
return AuthenticationContext;
}());
-
-
diff --git a/package.json b/package.json
index 69c5357f..496b0422 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
"type": "git",
"url": "https://github.com/AzureAD/azure-activedirectory-library-for-js.git"
},
- "version": "1.0.14",
+ "version": "1.0.15",
"description": "Windows Azure Active Directory Client Library for js",
"keywords": [
"implicit",
diff --git a/tests/unit/spec/AdalSpec.js b/tests/unit/spec/AdalSpec.js
index 631a2e3e..923a84c4 100644
--- a/tests/unit/spec/AdalSpec.js
+++ b/tests/unit/spec/AdalSpec.js
@@ -48,7 +48,7 @@ describe('Adal', function () {
};
var angularMock = {};
- var conf = { loginResource: 'defaultResource', tenant: 'testtenant', clientId: 'e9a5a8b6-8af7-4719-9821-0deef255f68e', navigateToLoginRequestUrl:true };
+ var conf = { loginResource: 'defaultResource', tenant: 'testtenant', clientId: 'e9a5a8b6-8af7-4719-9821-0deef255f68e', navigateToLoginRequestUrl: true };
var testPage = 'this is a song';
var STORAGE_PREFIX = 'adal';
var STORAGE_ACCESS_TOKEN_KEY = STORAGE_PREFIX + '.access.token.key';
@@ -125,7 +125,7 @@ describe('Adal', function () {
AdalModule.prototype._singletonInstance = null;
adal = new AdalModule(conf);
adal._user = null;
- adal._renewStates = [];
+ window.renewStates = [];
adal._activeRenewals = {};
adal.CONSTANTS.LOADFRAME_TIMEOUT = 800;
});
@@ -166,11 +166,6 @@ describe('Adal', function () {
expect(adal.getCachedToken(RESOURCE1)).toBe(null);
});
- it('gets cache username', function () {
- storageFake.setItem(adal.CONSTANTS.STORAGE.IDTOKEN, IDTOKEN_MOCK);
- expect(adal.getCachedUser().userName).toBe('user@oauthimplicit.ccsctp.net');
- });
-
it('navigates user to login by default', function () {
storageFake.setItem(adal.CONSTANTS.STORAGE.USERNAME, 'test user');
adal.config.displayCall = null;
@@ -208,7 +203,7 @@ describe('Adal', function () {
+ '&client-request-id=33333333-3333-4333-b333-333333333333'
+ adal._addLibMetadata()
+ '&nonce=33333333-3333-4333-b333-333333333333'
- );
+ );
expect(adal.config.state).toBe('33333333-3333-4333-b333-333333333333');
});
@@ -250,11 +245,11 @@ describe('Adal', function () {
token = valToken;
err = valErr;
};
- adal._renewStates = [];
+ window.renewStates = [];
adal._user = { profile: { 'upn': 'test@testuser.com' }, userName: 'test@domain.com' };
adal.acquireToken(RESOURCE1, callback);
expect(adal.callback).toBe(null);
- expect(adal._renewStates.length).toBe(1);
+ expect(window.renewStates.length).toBe(1);
// Wait for initial timeout load
console.log('Waiting for initial timeout');
waitsFor(function () {
@@ -285,12 +280,12 @@ describe('Adal', function () {
token2 = valToken;
err2 = valErr;
};
- adal._renewStates = [];
+ window.renewStates = [];
adal._user = { profile: { 'upn': 'test@testuser.com' }, userName: 'test@domain.com' };
adal.acquireToken(RESOURCE1, callback);
//Simulate second acquire i.e. second service call from Angular.
adal.acquireToken(RESOURCE1, callback2);
- expect(adal._renewStates.length).toBe(1);
+ expect(window.renewStates.length).toBe(1);
// Wait for initial timeout load
console.log('Waiting for initial timeout');
waitsFor(function () {
@@ -385,7 +380,7 @@ describe('Adal', function () {
var store = storageFake.storeVerify();
for (var prop in store) {
if (prop == adal.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + RESOURCE1 ||
- prop == adal.CONSTANTS.STORAGE.EXPIRATION_KEY + RESOURCE1) {
+ prop == adal.CONSTANTS.STORAGE.EXPIRATION_KEY + RESOURCE1) {
expect((store[prop] === '' || store[prop] == 0 || !store[prop])).toBe(true);
}
}
@@ -435,22 +430,6 @@ describe('Adal', function () {
expect(adal.promptUser).toHaveBeenCalledWith('https://login.microsoftonline.com/adfs/ls/?wa=wsignout1.0');
})
- it('gets user from cache', function () {
- storageFake.setItem(adal.CONSTANTS.STORAGE.IDTOKEN, IDTOKEN_MOCK);
- adal.config.clientId = 'e9a5a8b6-8af7-4719-9821-0deef255f68e';
- adal.config.loginResource = RESOURCE1;
- adal.config.expireOffsetSeconds = SECONDS_TO_EXPIRE - 100;
- var err = '', user = '';
- var callback = function (valErr, valResult) {
- err = valErr;
- user = valResult;
- };
- spyOn(adal, 'getCachedToken').andCallThrough();
- adal.getUser(callback);
- expect(adal.getCachedToken).not.toHaveBeenCalledWith(RESOURCE1);
- expect(user.userName).toBe('user@oauthimplicit.ccsctp.net');
- });
-
it('is callback if has error or access token or idtoken', function () {
expect(adal.isCallback('not a callback')).toBe(false);
expect(adal.isCallback('#error_description=someting_wrong')).toBe(true);
@@ -483,7 +462,7 @@ describe('Adal', function () {
var checkStateType = function (state, stateExpected, requestType) {
storageFake.setItem(state, stateExpected);
- adal._renewStates.push(stateExpected);
+ window.renewStates.push(stateExpected);
var requestInfo = adal.getRequestInfo('#error_description=someting_wrong&state=' + stateExpected);
expect(requestInfo.valid).toBe(true);
expect(requestInfo.stateResponse).toBe(stateExpected);
@@ -531,26 +510,6 @@ describe('Adal', function () {
expect(storageFake.getItem(adal.CONSTANTS.STORAGE.EXPIRATION_KEY + 'loginResource1')).toBe(mathMock.round(1) + 3589);
});
- it('saves username after extracting idtoken', function () {
- var requestInfo = {
- valid: true,
- parameters: {
- 'id_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjVUa0d0S1JrZ2FpZXpFWTJFc0xDMmdPTGpBNCJ9.eyJhdWQiOiJlOWE1YThiNi04YWY3LTQ3MTktOTgyMS0wZGVlZjI1NWY2OGUiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLXBwZS5uZXQvNTJkNGIwNzItOTQ3MC00OWZiLTg3MjEtYmMzYTFjOTkxMmExLyIsImlhdCI6MTQxMTk2MDkwMiwibmJmIjoxNDExOTYwOTAyLCJleHAiOjE0MTE5NjQ4MDIsInZlciI6IjEuMCIsInRpZCI6IjUyZDRiMDcyLTk0NzAtNDlmYi04NzIxLWJjM2ExYzk5MTJhMSIsImFtciI6WyJwd2QiXSwib2lkIjoiZmEzYzVmYTctN2Q5OC00Zjk3LWJmYzQtZGJkM2E0YTAyNDMxIiwidXBuIjoidXNlckBvYXV0aGltcGxpY2l0LmNjc2N0cC5uZXQiLCJ1bmlxdWVfbmFtZSI6InVzZXJAb2F1dGhpbXBsaWNpdC5jY3NjdHAubmV0Iiwic3ViIjoiWTdUbXhFY09IUzI0NGFHa3RjbWpicnNrdk5tU1I4WHo5XzZmbVc2NXloZyIsImZhbWlseV9uYW1lIjoiYSIsImdpdmVuX25hbWUiOiJ1c2VyIiwibm9uY2UiOiIxOWU2N2IyNC1jZDk5LTQ1YjYtYTU4OC04NDBlM2Y4ZjJhNzAiLCJwd2RfZXhwIjoiNTc3ODAwOCIsInB3ZF91cmwiOiJodHRwczovL3BvcnRhbC5taWNyb3NvZnRvbmxpbmUuY29tL0NoYW5nZVBhc3N3b3JkLmFzcHgifQ.GzbTwMXhjs4uJFogd1B46C_gKX6uZ4BfgJIpzFS-n-HRXEWeKdZWboRC_-C4UnEy6G9kR6vNFq7zi3DY1P8uf1lUavdOFUE27xNY1McN1Vjm6HKxKNYOLU549-wIb6SSfGVycdyskdJfplf5VRasMGclwHlY0l9bBCTaPunjhfcg-mQmGKND-aO0B54EGhdGs740NiLMCh6kNXbp1WAv7V6Yn408qZEIsOQoPO0dW-wO54DTqpbLtqiwae0pk0hDxXWczaUPxR_wcz0f3TgF42iTp-j5bXTf2GOP1VPZtN9PtdjcjDIfZ6ihAVZCEDB_Y9czHv7et0IvB1bzRWP6bQ',
- 'state': '123'
- },
- stateMatch: true,
- stateResponse: '123',
- requestType: adal.REQUEST_TYPE.ID_TOKEN
- };
- storageFake.setItem(adal.CONSTANTS.STORAGE.NONCE_IDTOKEN, '19e67b24-cd99-45b6-a588-840e3f8f2a70');
- adal.config.clientId = conf.clientId;
- adal._user = null;
- adal.saveTokenFromHash(requestInfo);
- var cachedUser = adal.getCachedUser();
- expect(cachedUser.userName).toBe('user@oauthimplicit.ccsctp.net');
- expect(cachedUser.profile.upn).toBe('user@oauthimplicit.ccsctp.net');
- });
-
it('does not save user for invalid nonce in idtoken', function () {
var requestInfo = {
valid: true,
@@ -703,7 +662,7 @@ describe('Adal', function () {
token = valToken;
err = valErr;
};
- adal._renewStates = [];
+ window.renewStates = [];
adal._user = { userName: 'test@testuser.com' };
adal.acquireToken(RESOURCE1, callback);
waitsFor(function () {
@@ -730,12 +689,12 @@ describe('Adal', function () {
token = valToken;
err = valErr;
};
- adal._renewStates = [];
+ window.renewStates = [];
adal._user = { profile: { 'upn': 'test@testuser.com' }, userName: 'test@domain.com' };
adal.acquireToken(adal.config.clientId, callback);
expect(storageFake.getItem(adal.CONSTANTS.STORAGE.NONCE_IDTOKEN)).toBe('33333333-3333-4333-b333-333333333333');
expect(adal.config.state).toBe('33333333-3333-4333-b333-333333333333' + '|' + 'client');
- expect(adal._renewStates.length).toBe(1);
+ expect(window.renewStates.length).toBe(1);
// Wait for initial timeout load
console.log('Waiting for initial timeout');
waitsFor(function () {
@@ -744,7 +703,7 @@ describe('Adal', function () {
runs(function () {
expect(mockFrames['adalIdTokenFrame'].src).toBe(DEFAULT_INSTANCE + conf.tenant + '/oauth2/authorize?response_type=id_token&client_id=' + adal.config.clientId + '&redirect_uri=contoso_site&state=33333333-3333-4333-b333-333333333333%7Cclient'
- + '&client-request-id=33333333-3333-4333-b333-333333333333' + adal._addLibMetadata() + '&prompt=none&login_hint=test%40testuser.com&domain_hint=testuser.com' + '&nonce=33333333-3333-4333-b333-333333333333');
+ + '&client-request-id=33333333-3333-4333-b333-333333333333' + adal._addLibMetadata() + '&prompt=none&login_hint=test%40testuser.com&domain_hint=testuser.com' + '&nonce=33333333-3333-4333-b333-333333333333');
});
});
@@ -806,18 +765,18 @@ describe('Adal', function () {
adal.config.expireOffsetSeconds = SECONDS_TO_EXPIRE + 100;
var callback = function () {
};
- adal._renewStates = [];
+ window.renewStates = [];
adal._user = { profile: { 'upn': 'test@testuser.com' }, userName: 'test@domain.com' };
spyOn(adal, '_loadFrameTimeout');
adal.acquireToken(RESOURCE1, callback);
expect(adal._loadFrameTimeout).toHaveBeenCalledWith(DEFAULT_INSTANCE + conf.tenant + '/oauth2/authorize?response_type=token&client_id=client&resource=' + RESOURCE1 + '&redirect_uri=contoso_site&state=33333333-3333-4333-b333-333333333333%7Ctoken.resource1'
- + '&client-request-id=33333333-3333-4333-b333-333333333333' + adal._addLibMetadata() + '&prompt=none&login_hint=test%40testuser.com&domain_hint=testuser.com', 'adalRenewFrametoken.resource1', 'token.resource1');
+ + '&client-request-id=33333333-3333-4333-b333-333333333333' + adal._addLibMetadata() + '&prompt=none&login_hint=test%40testuser.com&domain_hint=testuser.com', 'adalRenewFrametoken.resource1', 'token.resource1');
adal._activeRenewals = {};
adal._user = { profile: { 'sub': 'test@testuser.com' }, userName: 'test@domain.com' };
adal.acquireToken(RESOURCE1, callback);
expect(adal._loadFrameTimeout).toHaveBeenCalledWith(DEFAULT_INSTANCE + conf.tenant + '/oauth2/authorize?response_type=token&client_id=client&resource=' + RESOURCE1 + '&redirect_uri=contoso_site&state=33333333-3333-4333-b333-333333333333%7Ctoken.resource1'
- + '&client-request-id=33333333-3333-4333-b333-333333333333' + adal._addLibMetadata() + '&prompt=none', 'adalRenewFrametoken.resource1', 'token.resource1');
+ + '&client-request-id=33333333-3333-4333-b333-333333333333' + adal._addLibMetadata() + '&prompt=none', 'adalRenewFrametoken.resource1', 'token.resource1');
});
it('generates new correlationId for each request sent to AAD if not set by user', function () {
@@ -827,7 +786,7 @@ describe('Adal', function () {
adal.config.expireOffsetSeconds = SECONDS_TO_EXPIRE + 100;
var callback = function () {
};
- adal._renewStates = [];
+ window.renewStates = [];
adal._user = { profile: { 'upn': 'test@testuser.com' }, userName: 'test@domain.com' };
mathMock.random = function () {
return 0.1;
@@ -835,7 +794,7 @@ describe('Adal', function () {
spyOn(adal, '_loadFrameTimeout');
adal.acquireToken(RESOURCE1, callback);
expect(adal._loadFrameTimeout).toHaveBeenCalledWith(DEFAULT_INSTANCE + conf.tenant + '/oauth2/authorize?response_type=token&client_id=client&resource=' + RESOURCE1 + '&redirect_uri=contoso_site&state=11111111-1111-4111-9111-111111111111%7Ctoken.resource1'
- + '&client-request-id=11111111-1111-4111-9111-111111111111' + adal._addLibMetadata() + '&prompt=none&login_hint=test%40testuser.com&domain_hint=testuser.com', 'adalRenewFrametoken.resource1', 'token.resource1');
+ + '&client-request-id=11111111-1111-4111-9111-111111111111' + adal._addLibMetadata() + '&prompt=none&login_hint=test%40testuser.com&domain_hint=testuser.com', 'adalRenewFrametoken.resource1', 'token.resource1');
mathMock.random = function () {
return 0.3;
@@ -844,7 +803,7 @@ describe('Adal', function () {
adal._user = { profile: { 'sub': 'test@testuser.com' }, userName: 'test@domain.com' };
adal.acquireToken(RESOURCE1, callback);
expect(adal._loadFrameTimeout).toHaveBeenCalledWith(DEFAULT_INSTANCE + conf.tenant + '/oauth2/authorize?response_type=token&client_id=client&resource=' + RESOURCE1 + '&redirect_uri=contoso_site&state=44444444-4444-4444-8444-444444444444%7Ctoken.resource1'
- + '&client-request-id=44444444-4444-4444-8444-444444444444' + adal._addLibMetadata() + '&prompt=none', 'adalRenewFrametoken.resource1', 'token.resource1');
+ + '&client-request-id=44444444-4444-4444-8444-444444444444' + adal._addLibMetadata() + '&prompt=none', 'adalRenewFrametoken.resource1', 'token.resource1');
});
@@ -863,12 +822,12 @@ describe('Adal', function () {
adal._deserialize = function (query) {
var match,
- pl = /\+/g, // Regex for replacing addition symbol with a space
- search = /([^&=]+)=?([^&]*)/g,
- decode = function (s) {
- return decodeURIComponent(s.replace(pl, ' '));
- },
- obj = {};
+ pl = /\+/g, // Regex for replacing addition symbol with a space
+ search = /([^&=]+)=?([^&]*)/g,
+ decode = function (s) {
+ return decodeURIComponent(s.replace(pl, ' '));
+ },
+ obj = {};
match = search.exec(query);
while (match) {
obj[decode(match[1])] = decode(match[2]);
@@ -997,11 +956,7 @@ describe('Adal', function () {
err = valErr;
}
window.parent = {
- AuthenticationContext: function () {
- return {
- _renewStates: ['someState']
- }
- },
+ renewStates: ['someState'],
callBackMappedToRenewStates: { "someState": callback }
};
adal.handleWindowCallback(errorHash);