├── .angular-cli.json ├── .editorconfig ├── .gitignore ├── README.md ├── e2e ├── app.e2e-spec.ts ├── app.po.ts └── tsconfig.e2e.json ├── karma.conf.js ├── package.json ├── protractor.conf.js ├── src ├── app │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ └── services │ │ ├── auth.service.ts │ │ └── graph.service.ts ├── assets │ ├── .gitkeep │ └── js │ │ └── msal.js ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.css ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── typings.d.ts ├── tsconfig.json └── tslint.json /.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "msal-angular-sample" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": [ 11 | "assets", 12 | "favicon.ico" 13 | ], 14 | "index": "index.html", 15 | "main": "main.ts", 16 | "polyfills": "polyfills.ts", 17 | "test": "test.ts", 18 | "tsconfig": "tsconfig.app.json", 19 | "testTsconfig": "tsconfig.spec.json", 20 | "prefix": "app", 21 | "styles": [ 22 | "styles.css" 23 | ], 24 | "scripts": [], 25 | "environmentSource": "environments/environment.ts", 26 | "environments": { 27 | "dev": "environments/environment.ts", 28 | "prod": "environments/environment.prod.ts" 29 | } 30 | } 31 | ], 32 | "e2e": { 33 | "protractor": { 34 | "config": "./protractor.conf.js" 35 | } 36 | }, 37 | "lint": [ 38 | { 39 | "project": "src/tsconfig.app.json" 40 | }, 41 | { 42 | "project": "src/tsconfig.spec.json" 43 | }, 44 | { 45 | "project": "e2e/tsconfig.e2e.json" 46 | } 47 | ], 48 | "test": { 49 | "karma": { 50 | "config": "./karma.conf.js" 51 | } 52 | }, 53 | "defaults": { 54 | "styleExt": "css", 55 | "component": {} 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | package-lock.json 34 | testem.log 35 | /typings 36 | 37 | # e2e 38 | /e2e/*.js 39 | /e2e/*.map 40 | 41 | # System Files 42 | .DS_Store 43 | Thumbs.db 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MSAL.js (Microsoft Authentication Library for Javascript) + Angular Sample 2 | 3 | - Uses [MSAL.js](https://github.com/AzureAD/microsoft-authentication-library-for-js) to add a Sign in with Microsoft button 4 | - Calls Microsoft Graph API by passing a token obtained via MSAL 5 | 6 | ## Setup 7 | 8 | Run `npm install` and `npm install -g @angular/cli` 9 | 10 | ## Development server 11 | 12 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 13 | 14 | ## Build 15 | 16 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. 17 | 18 | ## Running unit tests 19 | 20 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 21 | 22 | ## Running end-to-end tests 23 | 24 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 25 | Before running the tests make sure you are serving the app via `ng serve`. 26 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { MsalAngularSamplePage } from './app.po'; 2 | 3 | describe('msal-angular-sample App', () => { 4 | let page: MsalAngularSamplePage; 5 | 6 | beforeEach(() => { 7 | page = new MsalAngularSamplePage(); 8 | }); 9 | 10 | it('should display message saying app works', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('app works!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, element, by } from 'protractor'; 2 | 3 | export class MsalAngularSamplePage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types":[ 8 | "jasmine", 9 | "node" 10 | ] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/0.13/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular/cli'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular/cli/plugins/karma') 14 | ], 15 | client:{ 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | files: [ 19 | { pattern: './src/test.ts', watched: false } 20 | ], 21 | preprocessors: { 22 | './src/test.ts': ['@angular/cli'] 23 | }, 24 | mime: { 25 | 'text/x-typescript': ['ts','tsx'] 26 | }, 27 | coverageIstanbulReporter: { 28 | reports: [ 'html', 'lcovonly' ], 29 | fixWebpackSourcePaths: true 30 | }, 31 | angularCli: { 32 | environment: 'dev' 33 | }, 34 | reporters: config.angularCli && config.angularCli.codeCoverage 35 | ? ['progress', 'coverage-istanbul'] 36 | : ['progress', 'kjhtml'], 37 | port: 9876, 38 | colors: true, 39 | logLevel: config.LOG_INFO, 40 | autoWatch: true, 41 | browsers: ['Chrome'], 42 | singleRun: false 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "msal-angular-sample", 3 | "version": "0.1.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build": "ng build", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/common": "4.0.0", 16 | "@angular/compiler": "4.0.0", 17 | "@angular/core": "4.0.0", 18 | "@angular/forms": "4.0.0", 19 | "@angular/http": "4.0.0", 20 | "@angular/platform-browser": "4.0.0", 21 | "@angular/platform-browser-dynamic": "4.0.0", 22 | "@angular/router": "4.0.0", 23 | "core-js": "2.4.1", 24 | "msal": "0.1.1", 25 | "rxjs": "5.1.0", 26 | "zone.js": "0.8.4" 27 | }, 28 | "devDependencies": { 29 | "@angular/cli": "1.0.2", 30 | "@angular/compiler-cli": "4.0.0", 31 | "@types/jasmine": "2.5.38", 32 | "@types/node": "6.0.60", 33 | "codelyzer": "2.0.0", 34 | "jasmine-core": "2.5.2", 35 | "jasmine-spec-reporter": "3.2.0", 36 | "karma": "1.4.1", 37 | "karma-chrome-launcher": "2.0.0", 38 | "karma-cli": "1.0.1", 39 | "karma-jasmine": "1.1.0", 40 | "karma-jasmine-html-reporter": "0.2.2", 41 | "karma-coverage-istanbul-reporter": "0.2.0", 42 | "protractor": "5.1.0", 43 | "ts-node": "2.0.0", 44 | "tslint": "4.5.0", 45 | "typescript": "2.2.0" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | beforeLaunch: function() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | }, 27 | onPrepare() { 28 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunilbandla/msal-angular-sample/e9b8f4324b661f9a19dba1d65139034d2355a4e5/src/app/app.component.css -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |

5 | Hello {{ user.name }} 6 |

7 |

8 | {{ userInfo | json }} 9 |

10 | 11 | Login unsuccessful 12 | 13 | 14 | Graph API call unsuccessful 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async(() => { 7 | TestBed.configureTestingModule({ 8 | declarations: [ 9 | AppComponent 10 | ], 11 | }).compileComponents(); 12 | })); 13 | 14 | it('should create the app', async(() => { 15 | const fixture = TestBed.createComponent(AppComponent); 16 | const app = fixture.debugElement.componentInstance; 17 | expect(app).toBeTruthy(); 18 | })); 19 | 20 | it(`should have as title 'app works!'`, async(() => { 21 | const fixture = TestBed.createComponent(AppComponent); 22 | const app = fixture.debugElement.componentInstance; 23 | expect(app.title).toEqual('app works!'); 24 | })); 25 | 26 | it('should render title in a h1 tag', async(() => { 27 | const fixture = TestBed.createComponent(AppComponent); 28 | fixture.detectChanges(); 29 | const compiled = fixture.debugElement.nativeElement; 30 | expect(compiled.querySelector('h1').textContent).toContain('app works!'); 31 | })); 32 | }); 33 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { AuthService } from 'app/services/auth.service'; 3 | import { GraphService } from 'app/services/graph.service'; 4 | 5 | @Component({ 6 | selector: 'app-root', 7 | templateUrl: './app.component.html', 8 | styleUrls: ['./app.component.css'] 9 | }) 10 | export class AppComponent { 11 | public user: Msal.User = null; 12 | public userInfo: any = null; 13 | public apiCallFailed: boolean; 14 | public loginFailed: boolean; 15 | 16 | constructor(private authService: AuthService, 17 | private graphService: GraphService) { 18 | } 19 | 20 | public login() { 21 | this.loginFailed = false; 22 | this.authService.login() 23 | .then(user => { 24 | if (user) { 25 | this.user = user; 26 | } else { 27 | this.loginFailed = true; 28 | } 29 | }, () => { 30 | this.loginFailed = true; 31 | }); 32 | } 33 | 34 | private callAPI() { 35 | this.apiCallFailed = false; 36 | this.authService.getToken() 37 | .then(token => { 38 | this.graphService.getUserInfo(token) 39 | .subscribe(data => { 40 | this.userInfo = data; 41 | }, error => { 42 | console.error(error); 43 | this.apiCallFailed = true; 44 | }); 45 | }, error => { 46 | console.error(error); 47 | this.apiCallFailed = true; 48 | }); 49 | } 50 | 51 | private logout() { 52 | this.authService.logout(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { HttpModule } from '@angular/http'; 5 | 6 | import { AppComponent } from './app.component'; 7 | import { AuthService } from 'app/services/auth.service'; 8 | import { GraphService } from 'app/services/graph.service'; 9 | 10 | @NgModule({ 11 | declarations: [ 12 | AppComponent 13 | ], 14 | imports: [ 15 | BrowserModule, 16 | FormsModule, 17 | HttpModule 18 | ], 19 | providers: [ 20 | AuthService, 21 | GraphService 22 | ], 23 | bootstrap: [AppComponent] 24 | }) 25 | export class AppModule { } 26 | -------------------------------------------------------------------------------- /src/app/services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import '../../../node_modules/msal/out/msal'; 3 | /// 4 | 5 | @Injectable() 6 | export class AuthService { 7 | private applicationConfig: any = { 8 | clientID: '60e769a3-2b51-4adf-a7e9-b3377270e648', 9 | graphScopes: ['user.read'] 10 | }; 11 | private app: any; 12 | 13 | constructor() { 14 | this.app = new Msal.UserAgentApplication(this.applicationConfig.clientID, '', () => { 15 | // callback for login redirect 16 | }); 17 | } 18 | public login() { 19 | return this.app.loginPopup(this.applicationConfig.graphScopes) 20 | .then(idToken => { 21 | const user = this.app.getUser(); 22 | if (user) { 23 | return user; 24 | } else { 25 | return null; 26 | } 27 | }, () => { 28 | return null; 29 | }); 30 | } 31 | public logout() { 32 | this.app.logout(); 33 | } 34 | public getToken() { 35 | return this.app.acquireTokenSilent(this.applicationConfig.graphScopes) 36 | .then(accessToken => { 37 | return accessToken; 38 | }, error => { 39 | return this.app.acquireTokenPopup(this.applicationConfig.graphScopes) 40 | .then(accessToken => { 41 | return accessToken; 42 | }, err => { 43 | console.error(err); 44 | }); 45 | }); 46 | } 47 | } -------------------------------------------------------------------------------- /src/app/services/graph.service.ts: -------------------------------------------------------------------------------- 1 | import { Headers, RequestOptions, Http } from '@angular/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { Observable } from 'rxjs/Rx'; 4 | import 'rxjs/add/operator/catch'; 5 | import 'rxjs/add/operator/map'; 6 | 7 | @Injectable() 8 | export class GraphService { 9 | private readonly graphUrl = 'https://graph.microsoft.com/v1.0/'; 10 | constructor (private http: Http) { 11 | 12 | } 13 | 14 | public getUserInfo(token: string) { 15 | const headers = new Headers({ 'Authorization': `Bearer ${token}` }); 16 | const options = new RequestOptions({ headers: headers }); 17 | return this.http.get(`${this.graphUrl}/me`, options) 18 | .map(response => response.json()) 19 | .catch(response => Observable.throw(response.text())); 20 | } 21 | } -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunilbandla/msal-angular-sample/e9b8f4324b661f9a19dba1d65139034d2355a4e5/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/assets/js/msal.js: -------------------------------------------------------------------------------- 1 | /*! msal v0.1.1 2017-05-09 */ 2 | 3 | 'use strict'; 4 | var __extends = (this && this.__extends) || (function () { 5 | var extendStatics = Object.setPrototypeOf || 6 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 7 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 8 | return function (d, b) { 9 | extendStatics(d, b); 10 | function __() { this.constructor = d; } 11 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 12 | }; 13 | })(); 14 | var Msal; 15 | (function (Msal) { 16 | var AuthorityType; 17 | (function (AuthorityType) { 18 | AuthorityType[AuthorityType["Aad"] = 0] = "Aad"; 19 | AuthorityType[AuthorityType["Adfs"] = 1] = "Adfs"; 20 | AuthorityType[AuthorityType["B2C"] = 2] = "B2C"; 21 | })(AuthorityType = Msal.AuthorityType || (Msal.AuthorityType = {})); 22 | var Authority = (function () { 23 | function Authority(authority, validateAuthority) { 24 | this.IsValidationEnabled = validateAuthority; 25 | this.CanonicalAuthority = authority; 26 | this.validateAsUri(); 27 | } 28 | Object.defineProperty(Authority.prototype, "Tenant", { 29 | get: function () { 30 | return this.CanonicalAuthorityUrlComponents.PathSegments[0]; 31 | }, 32 | enumerable: true, 33 | configurable: true 34 | }); 35 | Object.defineProperty(Authority.prototype, "AuthorizationEndpoint", { 36 | get: function () { 37 | this.validateResolved(); 38 | return this.tenantDiscoveryResponse.AuthorizationEndpoint.replace("{tenant}", this.Tenant); 39 | }, 40 | enumerable: true, 41 | configurable: true 42 | }); 43 | Object.defineProperty(Authority.prototype, "EndSessionEndpoint", { 44 | get: function () { 45 | this.validateResolved(); 46 | return this.tenantDiscoveryResponse.EndSessionEndpoint.replace("{tenant}", this.Tenant); 47 | }, 48 | enumerable: true, 49 | configurable: true 50 | }); 51 | Object.defineProperty(Authority.prototype, "SelfSignedJwtAudience", { 52 | get: function () { 53 | this.validateResolved(); 54 | return this.tenantDiscoveryResponse.Issuer.replace("{tenant}", this.Tenant); 55 | }, 56 | enumerable: true, 57 | configurable: true 58 | }); 59 | Authority.prototype.validateResolved = function () { 60 | if (!this.tenantDiscoveryResponse) { 61 | throw "Please call ResolveEndpointsAsync first"; 62 | } 63 | }; 64 | Object.defineProperty(Authority.prototype, "CanonicalAuthority", { 65 | get: function () { 66 | return this.canonicalAuthority; 67 | }, 68 | set: function (url) { 69 | this.canonicalAuthority = Msal.Utils.CanonicalizeUri(url); 70 | this.canonicalAuthorityUrlComponents = null; 71 | }, 72 | enumerable: true, 73 | configurable: true 74 | }); 75 | ; 76 | Object.defineProperty(Authority.prototype, "CanonicalAuthorityUrlComponents", { 77 | get: function () { 78 | if (!this.canonicalAuthorityUrlComponents) { 79 | this.canonicalAuthorityUrlComponents = Msal.Utils.GetUrlComponents(this.CanonicalAuthority); 80 | } 81 | return this.canonicalAuthorityUrlComponents; 82 | }, 83 | enumerable: true, 84 | configurable: true 85 | }); 86 | Object.defineProperty(Authority.prototype, "DefaultOpenIdConfigurationEndpoint", { 87 | get: function () { 88 | return this.CanonicalAuthority + "v2.0/.well-known/openid-configuration"; 89 | }, 90 | enumerable: true, 91 | configurable: true 92 | }); 93 | Authority.prototype.validateAsUri = function () { 94 | var components; 95 | try { 96 | components = this.CanonicalAuthorityUrlComponents; 97 | } 98 | catch (e) { 99 | throw Msal.ErrorMessage.invalidAuthorityType; 100 | } 101 | if (!components.Protocol || components.Protocol.toLowerCase() !== "https:") { 102 | throw Msal.ErrorMessage.authorityUriInsecure; 103 | } 104 | ; 105 | if (!components.PathSegments || components.PathSegments.length < 1) { 106 | throw Msal.ErrorMessage.authorityUriInvalidPath; 107 | } 108 | }; 109 | Authority.DetectAuthorityFromUrl = function (authorityUrl) { 110 | authorityUrl = Msal.Utils.CanonicalizeUri(authorityUrl); 111 | var components = Msal.Utils.GetUrlComponents(authorityUrl); 112 | var pathSegments = components.PathSegments; 113 | switch (pathSegments[0]) { 114 | case "tfp": 115 | return AuthorityType.B2C; 116 | case "adfs": 117 | return AuthorityType.Adfs; 118 | default: 119 | return AuthorityType.Aad; 120 | } 121 | }; 122 | Authority.CreateInstance = function (authorityUrl, validateAuthority) { 123 | var type = Authority.DetectAuthorityFromUrl(authorityUrl); 124 | switch (type) { 125 | case AuthorityType.B2C: 126 | return new Msal.B2cAuthority(authorityUrl, validateAuthority); 127 | case AuthorityType.Aad: 128 | return new Msal.AadAuthority(authorityUrl, validateAuthority); 129 | default: 130 | throw Msal.ErrorMessage.invalidAuthorityType; 131 | } 132 | }; 133 | Authority.prototype.DiscoverEndpoints = function (openIdConfigurationEndpoint) { 134 | var client = new Msal.XhrClient(); 135 | return client.sendRequestAsync(openIdConfigurationEndpoint, "GET", true) 136 | .then(function (response) { 137 | return { 138 | AuthorizationEndpoint: response.authorization_endpoint, 139 | EndSessionEndpoint: response.end_session_endpoint, 140 | Issuer: response.issuer 141 | }; 142 | }); 143 | }; 144 | Authority.prototype.ResolveEndpointsAsync = function () { 145 | var _this = this; 146 | var openIdConfigurationEndpoint = ""; 147 | return this.GetOpenIdConfigurationEndpointAsync().then(function (openIdConfigurationEndpointResponse) { 148 | openIdConfigurationEndpoint = openIdConfigurationEndpointResponse; 149 | return _this.DiscoverEndpoints(openIdConfigurationEndpoint); 150 | }).then(function (tenantDiscoveryResponse) { 151 | _this.tenantDiscoveryResponse = tenantDiscoveryResponse; 152 | return _this; 153 | }); 154 | }; 155 | return Authority; 156 | }()); 157 | Msal.Authority = Authority; 158 | })(Msal || (Msal = {})); 159 | var Msal; 160 | (function (Msal) { 161 | var AadAuthority = (function (_super) { 162 | __extends(AadAuthority, _super); 163 | function AadAuthority(authority, validateAuthority) { 164 | return _super.call(this, authority, validateAuthority) || this; 165 | } 166 | Object.defineProperty(AadAuthority.prototype, "AadInstanceDiscoveryEndpointUrl", { 167 | get: function () { 168 | return AadAuthority.AadInstanceDiscoveryEndpoint + "?api-version=1.0&authorization_endpoint=" + this.CanonicalAuthority + "oauth2/v2.0/authorize"; 169 | }, 170 | enumerable: true, 171 | configurable: true 172 | }); 173 | Object.defineProperty(AadAuthority.prototype, "AuthorityType", { 174 | get: function () { 175 | return Msal.AuthorityType.Aad; 176 | }, 177 | enumerable: true, 178 | configurable: true 179 | }); 180 | AadAuthority.prototype.GetOpenIdConfigurationEndpointAsync = function () { 181 | var _this = this; 182 | var resultPromise = new Promise(function (resolve, reject) { 183 | return resolve(_this.DefaultOpenIdConfigurationEndpoint); 184 | }); 185 | if (!this.IsValidationEnabled) { 186 | return resultPromise; 187 | } 188 | var host = this.CanonicalAuthorityUrlComponents.HostNameAndPort; 189 | if (this.IsInTrustedHostList(host)) { 190 | return resultPromise; 191 | } 192 | var client = new Msal.XhrClient(); 193 | return client.sendRequestAsync(this.AadInstanceDiscoveryEndpointUrl, "GET", true) 194 | .then(function (response) { 195 | return response.tenant_discovery_endpoint; 196 | }); 197 | }; 198 | AadAuthority.prototype.IsInTrustedHostList = function (host) { 199 | return AadAuthority.TrustedHostList[host.toLowerCase()]; 200 | }; 201 | return AadAuthority; 202 | }(Msal.Authority)); 203 | AadAuthority.AadInstanceDiscoveryEndpoint = "https://login.microsoftonline.com/common/discovery/instance"; 204 | AadAuthority.TrustedHostList = { 205 | "login.windows.net": "login.windows.net", 206 | "login.chinacloudapi.cn": "login.chinacloudapi.cn", 207 | "login.cloudgovapi.us": "login.cloudgovapi.us", 208 | "login.microsoftonline.com": "login.microsoftonline.com", 209 | "login.microsoftonline.de": "login.microsoftonline.de" 210 | }; 211 | Msal.AadAuthority = AadAuthority; 212 | })(Msal || (Msal = {})); 213 | var Msal; 214 | (function (Msal) { 215 | var AccessTokenCacheItem = (function () { 216 | function AccessTokenCacheItem(key, value) { 217 | this.key = key; 218 | this.value = value; 219 | } 220 | return AccessTokenCacheItem; 221 | }()); 222 | Msal.AccessTokenCacheItem = AccessTokenCacheItem; 223 | })(Msal || (Msal = {})); 224 | var Msal; 225 | (function (Msal) { 226 | var AccessTokenKey = (function () { 227 | function AccessTokenKey(authority, clientId, scopes, uid, utid) { 228 | this.authority = authority; 229 | this.clientId = clientId; 230 | this.scopes = scopes; 231 | this.userIdentifier = Msal.Utils.base64EncodeStringUrlSafe(uid) + "." + Msal.Utils.base64EncodeStringUrlSafe(utid); 232 | } 233 | return AccessTokenKey; 234 | }()); 235 | Msal.AccessTokenKey = AccessTokenKey; 236 | })(Msal || (Msal = {})); 237 | var Msal; 238 | (function (Msal) { 239 | var AccessTokenValue = (function () { 240 | function AccessTokenValue(accessToken, idToken, expiresIn, clientInfo) { 241 | this.accessToken = accessToken; 242 | this.idToken = idToken; 243 | this.expiresIn = expiresIn; 244 | this.clientInfo = clientInfo; 245 | } 246 | return AccessTokenValue; 247 | }()); 248 | Msal.AccessTokenValue = AccessTokenValue; 249 | })(Msal || (Msal = {})); 250 | var Msal; 251 | (function (Msal) { 252 | var AuthenticationRequestParameters = (function () { 253 | function AuthenticationRequestParameters(authority, clientId, scope, responseType, redirectUri) { 254 | this.authorityInstance = authority; 255 | this.clientId = clientId; 256 | this.scopes = scope; 257 | this.responseType = responseType; 258 | this.redirectUri = redirectUri; 259 | this.correlationId = Msal.Utils.createNewGuid(); 260 | this.state = Msal.Utils.createNewGuid(); 261 | this.nonce = Msal.Utils.createNewGuid(); 262 | this.xClientSku = "MSAL.JS"; 263 | this.xClientVer = Msal.Utils.getLibraryVersion(); 264 | } 265 | Object.defineProperty(AuthenticationRequestParameters.prototype, "authority", { 266 | get: function () { 267 | return this.authorityInstance.CanonicalAuthority; 268 | }, 269 | enumerable: true, 270 | configurable: true 271 | }); 272 | AuthenticationRequestParameters.prototype.createNavigateUrl = function (scopes) { 273 | if (!scopes) { 274 | scopes = [this.clientId]; 275 | } 276 | if (scopes.indexOf(this.clientId) === -1) { 277 | scopes.push(this.clientId); 278 | } 279 | var str = []; 280 | str.push("response_type=" + this.responseType); 281 | this.translateclientIdUsedInScope(scopes); 282 | str.push("scope=" + encodeURIComponent(this.parseScope(scopes))); 283 | str.push("client_id=" + encodeURIComponent(this.clientId)); 284 | str.push("redirect_uri=" + encodeURIComponent(this.redirectUri)); 285 | str.push("state=" + encodeURIComponent(this.state)); 286 | str.push("nonce=" + encodeURIComponent(this.nonce)); 287 | str.push("client_info=1"); 288 | str.push("x-client-SKU=" + this.xClientSku); 289 | str.push("x-client-Ver=" + this.xClientVer); 290 | if (this.extraQueryParameters) { 291 | str.push(this.extraQueryParameters); 292 | } 293 | str.push("client-request-id=" + encodeURIComponent(this.correlationId)); 294 | var authEndpoint = this.authorityInstance.AuthorizationEndpoint; 295 | if (authEndpoint.indexOf("?") < 0) { 296 | authEndpoint += '?'; 297 | } 298 | else { 299 | authEndpoint += '&'; 300 | } 301 | var requestUrl = "" + authEndpoint + str.join("&"); 302 | return requestUrl; 303 | }; 304 | AuthenticationRequestParameters.prototype.translateclientIdUsedInScope = function (scopes) { 305 | var clientIdIndex = scopes.indexOf(this.clientId); 306 | if (clientIdIndex >= 0) { 307 | scopes.splice(clientIdIndex, 1); 308 | if (scopes.indexOf("openid") === -1) { 309 | scopes.push("openid"); 310 | } 311 | if (scopes.indexOf("profile") === -1) { 312 | scopes.push("profile"); 313 | } 314 | } 315 | }; 316 | AuthenticationRequestParameters.prototype.parseScope = function (scopes) { 317 | var scopeList = ""; 318 | if (scopes) { 319 | for (var i = 0; i < scopes.length; ++i) { 320 | scopeList += (i !== scopes.length - 1) ? scopes[i] + " " : scopes[i]; 321 | } 322 | } 323 | return scopeList; 324 | }; 325 | return AuthenticationRequestParameters; 326 | }()); 327 | Msal.AuthenticationRequestParameters = AuthenticationRequestParameters; 328 | })(Msal || (Msal = {})); 329 | var Msal; 330 | (function (Msal) { 331 | var B2cAuthority = (function (_super) { 332 | __extends(B2cAuthority, _super); 333 | function B2cAuthority(authority, validateAuthority) { 334 | var _this = _super.call(this, authority, validateAuthority) || this; 335 | var urlComponents = Msal.Utils.GetUrlComponents(authority); 336 | var pathSegments = urlComponents.PathSegments; 337 | if (pathSegments.length < 3) { 338 | throw Msal.ErrorMessage.b2cAuthorityUriInvalidPath; 339 | } 340 | _this.CanonicalAuthority = "https://" + urlComponents.HostNameAndPort + "/" + pathSegments[0] + "/" + pathSegments[1] + "/" + pathSegments[2] + "/"; 341 | return _this; 342 | } 343 | Object.defineProperty(B2cAuthority.prototype, "AuthorityType", { 344 | get: function () { 345 | return Msal.AuthorityType.B2C; 346 | }, 347 | enumerable: true, 348 | configurable: true 349 | }); 350 | B2cAuthority.prototype.GetOpenIdConfigurationEndpointAsync = function () { 351 | var _this = this; 352 | var resultPromise = new Promise(function (resolve, reject) { 353 | return resolve(_this.DefaultOpenIdConfigurationEndpoint); 354 | }); 355 | if (!this.IsValidationEnabled) { 356 | return resultPromise; 357 | } 358 | if (this.IsInTrustedHostList(this.CanonicalAuthorityUrlComponents.HostNameAndPort)) { 359 | return resultPromise; 360 | } 361 | return new Promise(function (resolve, reject) { 362 | return reject(Msal.ErrorMessage.unsupportedAuthorityValidation); 363 | }); 364 | }; 365 | return B2cAuthority; 366 | }(Msal.AadAuthority)); 367 | Msal.B2cAuthority = B2cAuthority; 368 | })(Msal || (Msal = {})); 369 | var Msal; 370 | (function (Msal) { 371 | var ClientInfo = (function () { 372 | function ClientInfo(rawClientInfo) { 373 | if (!rawClientInfo || Msal.Utils.isEmpty(rawClientInfo)) { 374 | this.uid = ""; 375 | this.utid = ""; 376 | return; 377 | } 378 | try { 379 | var decodedClientInfo = Msal.Utils.base64DecodeStringUrlSafe(rawClientInfo); 380 | var clientInfo = JSON.parse(decodedClientInfo); 381 | if (clientInfo) { 382 | if (clientInfo.hasOwnProperty("uid")) { 383 | this.uid = clientInfo.uid; 384 | } 385 | if (clientInfo.hasOwnProperty("utid")) { 386 | this.utid = clientInfo.utid; 387 | } 388 | } 389 | } 390 | catch (e) { 391 | throw new Error(e); 392 | } 393 | } 394 | Object.defineProperty(ClientInfo.prototype, "uid", { 395 | get: function () { 396 | return this._uid ? this._uid : ""; 397 | }, 398 | set: function (uid) { 399 | this._uid = uid; 400 | }, 401 | enumerable: true, 402 | configurable: true 403 | }); 404 | Object.defineProperty(ClientInfo.prototype, "utid", { 405 | get: function () { 406 | return this._utid ? this._utid : ""; 407 | }, 408 | set: function (utid) { 409 | this._utid = utid; 410 | }, 411 | enumerable: true, 412 | configurable: true 413 | }); 414 | return ClientInfo; 415 | }()); 416 | Msal.ClientInfo = ClientInfo; 417 | })(Msal || (Msal = {})); 418 | var Msal; 419 | (function (Msal) { 420 | var Constants = (function () { 421 | function Constants() { 422 | } 423 | Object.defineProperty(Constants, "errorDescription", { 424 | get: function () { return "error_description"; }, 425 | enumerable: true, 426 | configurable: true 427 | }); 428 | Object.defineProperty(Constants, "error", { 429 | get: function () { return "error"; }, 430 | enumerable: true, 431 | configurable: true 432 | }); 433 | Object.defineProperty(Constants, "scope", { 434 | get: function () { return "scope"; }, 435 | enumerable: true, 436 | configurable: true 437 | }); 438 | Object.defineProperty(Constants, "acquireTokenUser", { 439 | get: function () { return "msal_acquireTokenUser"; }, 440 | enumerable: true, 441 | configurable: true 442 | }); 443 | Object.defineProperty(Constants, "clientInfo", { 444 | get: function () { return "client_info"; }, 445 | enumerable: true, 446 | configurable: true 447 | }); 448 | Object.defineProperty(Constants, "clientId", { 449 | get: function () { return "clientId"; }, 450 | enumerable: true, 451 | configurable: true 452 | }); 453 | Object.defineProperty(Constants, "authority", { 454 | get: function () { return "authority"; }, 455 | enumerable: true, 456 | configurable: true 457 | }); 458 | Object.defineProperty(Constants, "idToken", { 459 | get: function () { return "id_token"; }, 460 | enumerable: true, 461 | configurable: true 462 | }); 463 | Object.defineProperty(Constants, "accessToken", { 464 | get: function () { return "access_token"; }, 465 | enumerable: true, 466 | configurable: true 467 | }); 468 | Object.defineProperty(Constants, "expiresIn", { 469 | get: function () { return "expires_in"; }, 470 | enumerable: true, 471 | configurable: true 472 | }); 473 | Object.defineProperty(Constants, "sessionState", { 474 | get: function () { return "session_state"; }, 475 | enumerable: true, 476 | configurable: true 477 | }); 478 | Object.defineProperty(Constants, "tokenKeys", { 479 | get: function () { return "msal.token.keys"; }, 480 | enumerable: true, 481 | configurable: true 482 | }); 483 | Object.defineProperty(Constants, "accessTokenKey", { 484 | get: function () { return "msal.access.token.key"; }, 485 | enumerable: true, 486 | configurable: true 487 | }); 488 | Object.defineProperty(Constants, "expirationKey", { 489 | get: function () { return "msal.expiration.key"; }, 490 | enumerable: true, 491 | configurable: true 492 | }); 493 | Object.defineProperty(Constants, "stateLogin", { 494 | get: function () { return "msal.state.login"; }, 495 | enumerable: true, 496 | configurable: true 497 | }); 498 | Object.defineProperty(Constants, "stateAcquireToken", { 499 | get: function () { return "msal.state.acquireToken"; }, 500 | enumerable: true, 501 | configurable: true 502 | }); 503 | Object.defineProperty(Constants, "stateRenew", { 504 | get: function () { return "msal.state.renew"; }, 505 | enumerable: true, 506 | configurable: true 507 | }); 508 | Object.defineProperty(Constants, "nonceIdToken", { 509 | get: function () { return "msal.nonce.idtoken"; }, 510 | enumerable: true, 511 | configurable: true 512 | }); 513 | Object.defineProperty(Constants, "userName", { 514 | get: function () { return "msal.username"; }, 515 | enumerable: true, 516 | configurable: true 517 | }); 518 | Object.defineProperty(Constants, "idTokenKey", { 519 | get: function () { return "msal.idtoken"; }, 520 | enumerable: true, 521 | configurable: true 522 | }); 523 | Object.defineProperty(Constants, "loginRequest", { 524 | get: function () { return "msal.login.request"; }, 525 | enumerable: true, 526 | configurable: true 527 | }); 528 | Object.defineProperty(Constants, "loginError", { 529 | get: function () { return "msal.login.error"; }, 530 | enumerable: true, 531 | configurable: true 532 | }); 533 | Object.defineProperty(Constants, "renewStatus", { 534 | get: function () { return "msal.token.renew.status"; }, 535 | enumerable: true, 536 | configurable: true 537 | }); 538 | Object.defineProperty(Constants, "resourceDelimeter", { 539 | get: function () { return "|"; }, 540 | enumerable: true, 541 | configurable: true 542 | }); 543 | Object.defineProperty(Constants, "loadFrameTimeout", { 544 | get: function () { 545 | return this._loadFrameTimeout; 546 | }, 547 | set: function (timeout) { 548 | this._loadFrameTimeout = timeout; 549 | }, 550 | enumerable: true, 551 | configurable: true 552 | }); 553 | ; 554 | ; 555 | Object.defineProperty(Constants, "tokenRenewStatusCancelled", { 556 | get: function () { return "Canceled"; }, 557 | enumerable: true, 558 | configurable: true 559 | }); 560 | Object.defineProperty(Constants, "tokenRenewStatusCompleted", { 561 | get: function () { return "Completed"; }, 562 | enumerable: true, 563 | configurable: true 564 | }); 565 | Object.defineProperty(Constants, "tokenRenewStatusInProgress", { 566 | get: function () { return "In Progress"; }, 567 | enumerable: true, 568 | configurable: true 569 | }); 570 | Object.defineProperty(Constants, "popUpWidth", { 571 | get: function () { return this._popUpWidth; }, 572 | set: function (width) { 573 | this._popUpWidth = width; 574 | }, 575 | enumerable: true, 576 | configurable: true 577 | }); 578 | ; 579 | Object.defineProperty(Constants, "popUpHeight", { 580 | get: function () { return this._popUpHeight; }, 581 | set: function (height) { 582 | this._popUpHeight = height; 583 | }, 584 | enumerable: true, 585 | configurable: true 586 | }); 587 | ; 588 | Object.defineProperty(Constants, "login", { 589 | get: function () { return "LOGIN"; }, 590 | enumerable: true, 591 | configurable: true 592 | }); 593 | Object.defineProperty(Constants, "renewToken", { 594 | get: function () { return "renewToken"; }, 595 | enumerable: true, 596 | configurable: true 597 | }); 598 | Object.defineProperty(Constants, "unknown", { 599 | get: function () { return "UNKNOWN"; }, 600 | enumerable: true, 601 | configurable: true 602 | }); 603 | return Constants; 604 | }()); 605 | Constants._loadFrameTimeout = 6000; 606 | Constants._popUpWidth = 483; 607 | Constants._popUpHeight = 600; 608 | Msal.Constants = Constants; 609 | var ErrorCodes = (function () { 610 | function ErrorCodes() { 611 | } 612 | Object.defineProperty(ErrorCodes, "loginProgressError", { 613 | get: function () { return "login_progress_error"; }, 614 | enumerable: true, 615 | configurable: true 616 | }); 617 | Object.defineProperty(ErrorCodes, "acquireTokenProgressError", { 618 | get: function () { return "acquiretoken_progress_error"; }, 619 | enumerable: true, 620 | configurable: true 621 | }); 622 | Object.defineProperty(ErrorCodes, "inputScopesError", { 623 | get: function () { return "input_scopes_error"; }, 624 | enumerable: true, 625 | configurable: true 626 | }); 627 | Object.defineProperty(ErrorCodes, "endpointResolutionError", { 628 | get: function () { return "endpoints_resolution_error"; }, 629 | enumerable: true, 630 | configurable: true 631 | }); 632 | Object.defineProperty(ErrorCodes, "popUpWindowError", { 633 | get: function () { return "popup_window_error"; }, 634 | enumerable: true, 635 | configurable: true 636 | }); 637 | Object.defineProperty(ErrorCodes, "userLoginError", { 638 | get: function () { return "user_login_error"; }, 639 | enumerable: true, 640 | configurable: true 641 | }); 642 | return ErrorCodes; 643 | }()); 644 | Msal.ErrorCodes = ErrorCodes; 645 | var ErrorDescription = (function () { 646 | function ErrorDescription() { 647 | } 648 | Object.defineProperty(ErrorDescription, "loginProgressError", { 649 | get: function () { return "Login is in progress"; }, 650 | enumerable: true, 651 | configurable: true 652 | }); 653 | Object.defineProperty(ErrorDescription, "acquireTokenProgressError", { 654 | get: function () { return "Acquire token is in progress"; }, 655 | enumerable: true, 656 | configurable: true 657 | }); 658 | Object.defineProperty(ErrorDescription, "inputScopesError", { 659 | get: function () { return "Invalid value of input scopes provided"; }, 660 | enumerable: true, 661 | configurable: true 662 | }); 663 | Object.defineProperty(ErrorDescription, "endpointResolutionError", { 664 | get: function () { return "Endpoints cannot be resolved"; }, 665 | enumerable: true, 666 | configurable: true 667 | }); 668 | Object.defineProperty(ErrorDescription, "popUpWindowError", { 669 | get: function () { return "Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser."; }, 670 | enumerable: true, 671 | configurable: true 672 | }); 673 | Object.defineProperty(ErrorDescription, "userLoginError", { 674 | get: function () { return "User login is required"; }, 675 | enumerable: true, 676 | configurable: true 677 | }); 678 | return ErrorDescription; 679 | }()); 680 | Msal.ErrorDescription = ErrorDescription; 681 | })(Msal || (Msal = {})); 682 | var Msal; 683 | (function (Msal) { 684 | var ErrorMessage = (function () { 685 | function ErrorMessage() { 686 | } 687 | Object.defineProperty(ErrorMessage, "authorityUriInvalidPath", { 688 | get: function () { return "AuthorityUriInvalidPath"; }, 689 | enumerable: true, 690 | configurable: true 691 | }); 692 | Object.defineProperty(ErrorMessage, "authorityUriInsecure", { 693 | get: function () { return "AuthorityUriInsecure"; }, 694 | enumerable: true, 695 | configurable: true 696 | }); 697 | Object.defineProperty(ErrorMessage, "invalidAuthorityType", { 698 | get: function () { return "InvalidAuthorityType"; }, 699 | enumerable: true, 700 | configurable: true 701 | }); 702 | Object.defineProperty(ErrorMessage, "unsupportedAuthorityValidation", { 703 | get: function () { return "UnsupportedAuthorityValidation"; }, 704 | enumerable: true, 705 | configurable: true 706 | }); 707 | Object.defineProperty(ErrorMessage, "b2cAuthorityUriInvalidPath", { 708 | get: function () { return "B2cAuthorityUriInvalidPath"; }, 709 | enumerable: true, 710 | configurable: true 711 | }); 712 | return ErrorMessage; 713 | }()); 714 | Msal.ErrorMessage = ErrorMessage; 715 | })(Msal || (Msal = {})); 716 | var Msal; 717 | (function (Msal) { 718 | var IdToken = (function () { 719 | function IdToken(rawIdToken) { 720 | if (Msal.Utils.isEmpty(rawIdToken)) { 721 | throw new Error("null or empty raw idtoken"); 722 | } 723 | try { 724 | this.rawIdToken = rawIdToken; 725 | var decodedIdToken = Msal.Utils.extractIdToken(rawIdToken); 726 | if (decodedIdToken) { 727 | if (decodedIdToken.hasOwnProperty("iss")) { 728 | this.issuer = decodedIdToken.iss; 729 | } 730 | if (decodedIdToken.hasOwnProperty("oid")) { 731 | this.objectId = decodedIdToken.oid; 732 | } 733 | if (decodedIdToken.hasOwnProperty("sub")) { 734 | this.subject = decodedIdToken.sub; 735 | } 736 | if (decodedIdToken.hasOwnProperty("tid")) { 737 | this.tenantId = decodedIdToken.tid; 738 | } 739 | if (decodedIdToken.hasOwnProperty("ver")) { 740 | this.version = decodedIdToken.ver; 741 | } 742 | if (decodedIdToken.hasOwnProperty("preferred_username")) { 743 | this.preferredName = decodedIdToken.preferred_username; 744 | } 745 | if (decodedIdToken.hasOwnProperty("name")) { 746 | this.name = decodedIdToken.name; 747 | } 748 | if (decodedIdToken.hasOwnProperty("nonce")) { 749 | this.nonce = decodedIdToken.nonce; 750 | } 751 | if (decodedIdToken.hasOwnProperty("exp")) { 752 | this.expiration = decodedIdToken.exp; 753 | } 754 | } 755 | } 756 | catch (e) { 757 | throw new Error("Failed to parse the returned id token"); 758 | } 759 | } 760 | return IdToken; 761 | }()); 762 | Msal.IdToken = IdToken; 763 | })(Msal || (Msal = {})); 764 | var Msal; 765 | (function (Msal) { 766 | var LogLevel; 767 | (function (LogLevel) { 768 | LogLevel[LogLevel["Error"] = 0] = "Error"; 769 | LogLevel[LogLevel["Warning"] = 1] = "Warning"; 770 | LogLevel[LogLevel["Info"] = 2] = "Info"; 771 | LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; 772 | })(LogLevel = Msal.LogLevel || (Msal.LogLevel = {})); 773 | var Logger = (function () { 774 | function Logger(correlationId) { 775 | this._level = LogLevel.Info; 776 | this._piiLoggingEnabled = false; 777 | if (Logger._instance) { 778 | return Logger._instance; 779 | } 780 | this._correlationId = correlationId; 781 | Logger._instance = this; 782 | return Logger._instance; 783 | } 784 | Object.defineProperty(Logger.prototype, "correlationId", { 785 | get: function () { return this._correlationId; }, 786 | set: function (correlationId) { 787 | this._correlationId = correlationId; 788 | }, 789 | enumerable: true, 790 | configurable: true 791 | }); 792 | ; 793 | Object.defineProperty(Logger.prototype, "level", { 794 | get: function () { return this._level; }, 795 | set: function (logLevel) { 796 | if (LogLevel[logLevel]) { 797 | this._level = logLevel; 798 | } 799 | else 800 | throw new Error("Provide a valid value for level. Possibles range for logLevel is 0-3"); 801 | }, 802 | enumerable: true, 803 | configurable: true 804 | }); 805 | ; 806 | Object.defineProperty(Logger.prototype, "piiLoggingEnabled", { 807 | get: function () { return this._piiLoggingEnabled; }, 808 | set: function (piiLoggingEnabled) { 809 | this._piiLoggingEnabled = piiLoggingEnabled; 810 | }, 811 | enumerable: true, 812 | configurable: true 813 | }); 814 | ; 815 | Object.defineProperty(Logger.prototype, "localCallback", { 816 | get: function () { return this._localCallback; }, 817 | set: function (localCallback) { 818 | if (this.localCallback) { 819 | throw new Error("MSAL logging callback can only be set once per process and should never change once set."); 820 | } 821 | this._localCallback = localCallback; 822 | }, 823 | enumerable: true, 824 | configurable: true 825 | }); 826 | ; 827 | Logger.prototype.logMessage = function (logMessage, logLevel, containsPii) { 828 | if ((logLevel > this.level) || (!this.piiLoggingEnabled && containsPii)) { 829 | return; 830 | } 831 | var timestamp = new Date().toUTCString(); 832 | var log; 833 | if (!Msal.Utils.isEmpty(this.correlationId)) { 834 | log = timestamp + ":" + this._correlationId + "-" + Msal.Utils.getLibraryVersion() + "-" + LogLevel[logLevel] + " " + logMessage; 835 | } 836 | else { 837 | log = timestamp + ":" + Msal.Utils.getLibraryVersion() + "-" + LogLevel[logLevel] + " " + logMessage; 838 | } 839 | this.executeCallback(logLevel, log, containsPii); 840 | }; 841 | Logger.prototype.executeCallback = function (level, message, containsPii) { 842 | if (this.localCallback) { 843 | this.localCallback(level, message, containsPii); 844 | } 845 | }; 846 | Logger.prototype.error = function (message) { 847 | this.logMessage(message, LogLevel.Error, false); 848 | }; 849 | Logger.prototype.errorPii = function (message) { 850 | this.logMessage(message, LogLevel.Error, true); 851 | }; 852 | Logger.prototype.warning = function (message) { 853 | this.logMessage(message, LogLevel.Warning, false); 854 | }; 855 | Logger.prototype.warningPii = function (message) { 856 | this.logMessage(message, LogLevel.Warning, true); 857 | }; 858 | Logger.prototype.info = function (message) { 859 | this.logMessage(message, LogLevel.Info, false); 860 | }; 861 | Logger.prototype.infoPii = function (message) { 862 | this.logMessage(message, LogLevel.Info, true); 863 | }; 864 | Logger.prototype.verbose = function (message) { 865 | this.logMessage(message, LogLevel.Verbose, false); 866 | }; 867 | Logger.prototype.verbosePii = function (message) { 868 | this.logMessage(message, LogLevel.Verbose, true); 869 | }; 870 | return Logger; 871 | }()); 872 | Msal.Logger = Logger; 873 | })(Msal || (Msal = {})); 874 | var Msal; 875 | (function (Msal) { 876 | var RequestContext = (function () { 877 | function RequestContext(correlationId) { 878 | if (RequestContext._instance) { 879 | return RequestContext._instance; 880 | } 881 | this._logger = new Msal.Logger(correlationId); 882 | this._correlationId = this._logger.correlationId; 883 | RequestContext._instance = this; 884 | } 885 | Object.defineProperty(RequestContext.prototype, "correlationId", { 886 | get: function () { return this._correlationId; }, 887 | enumerable: true, 888 | configurable: true 889 | }); 890 | Object.defineProperty(RequestContext.prototype, "logger", { 891 | get: function () { return this._logger; }, 892 | enumerable: true, 893 | configurable: true 894 | }); 895 | return RequestContext; 896 | }()); 897 | Msal.RequestContext = RequestContext; 898 | })(Msal || (Msal = {})); 899 | var Msal; 900 | (function (Msal) { 901 | var TokenResponse = (function () { 902 | function TokenResponse() { 903 | this.valid = false; 904 | this.parameters = {}; 905 | this.stateMatch = false; 906 | this.stateResponse = ""; 907 | this.requestType = "unknown"; 908 | } 909 | return TokenResponse; 910 | }()); 911 | Msal.TokenResponse = TokenResponse; 912 | })(Msal || (Msal = {})); 913 | var Msal; 914 | (function (Msal) { 915 | var Storage = (function () { 916 | function Storage(cacheLocation) { 917 | if (Storage._instance) { 918 | return Storage._instance; 919 | } 920 | this._cacheLocation = cacheLocation; 921 | this._localStorageSupported = typeof window[this._cacheLocation] != "undefined" && window[this._cacheLocation] != null; 922 | this._sessionStorageSupported = typeof window[cacheLocation] != "undefined" && window[cacheLocation] != null; 923 | Storage._instance = this; 924 | if (!this._localStorageSupported && !this._sessionStorageSupported) { 925 | throw new Error("localStorage and sessionStorage not supported"); 926 | } 927 | return Storage._instance; 928 | } 929 | Storage.prototype.setItem = function (key, value) { 930 | if (window[this._cacheLocation]) { 931 | window[this._cacheLocation].setItem(key, value); 932 | } 933 | else { 934 | throw new Error("localStorage and sessionStorage are not supported"); 935 | } 936 | }; 937 | Storage.prototype.getItem = function (key) { 938 | if (window[this._cacheLocation]) { 939 | return window[this._cacheLocation].getItem(key); 940 | } 941 | else { 942 | throw new Error("localStorage and sessionStorage are not supported"); 943 | } 944 | }; 945 | Storage.prototype.removeItem = function (key) { 946 | if (window[this._cacheLocation]) { 947 | return window[this._cacheLocation].removeItem(key); 948 | } 949 | else { 950 | throw new Error("localStorage and sessionStorage are not supported"); 951 | } 952 | }; 953 | Storage.prototype.clear = function () { 954 | if (window[this._cacheLocation]) { 955 | return window[this._cacheLocation].clear(); 956 | } 957 | else { 958 | throw new Error("localStorage and sessionStorage are not supported"); 959 | } 960 | }; 961 | Storage.prototype.getAllAccessTokens = function (clientId, userIdentifier) { 962 | var results = []; 963 | var accessTokenCacheItem; 964 | var storage = window[this._cacheLocation]; 965 | if (storage) { 966 | var key = void 0; 967 | for (key in storage) { 968 | if (storage.hasOwnProperty(key)) { 969 | if (key.match(clientId) && key.match(userIdentifier)) { 970 | var value = this.getItem(key); 971 | if (value) { 972 | accessTokenCacheItem = new Msal.AccessTokenCacheItem(JSON.parse(key), JSON.parse(value)); 973 | results.push(accessTokenCacheItem); 974 | } 975 | } 976 | } 977 | } 978 | } 979 | else { 980 | throw new Error("localStorage and sessionStorage are not supported"); 981 | } 982 | return results; 983 | }; 984 | Storage.prototype.removeAcquireTokenEntries = function (acquireTokenUser, acquireTokenStatus) { 985 | var storage = window[this._cacheLocation]; 986 | if (storage) { 987 | var key = void 0; 988 | for (key in storage) { 989 | if (storage.hasOwnProperty(key)) { 990 | if ((key.indexOf(acquireTokenUser) > -1) || (key.indexOf(acquireTokenStatus) > -1)) { 991 | this.removeItem(key); 992 | } 993 | } 994 | } 995 | } 996 | else { 997 | throw new Error("localStorage and sessionStorage are not supported"); 998 | } 999 | }; 1000 | Storage.prototype.resetCacheItems = function () { 1001 | var storage = window[this._cacheLocation]; 1002 | if (storage) { 1003 | var key = void 0; 1004 | for (key in storage) { 1005 | if (storage.hasOwnProperty(key)) { 1006 | storage[key] = ""; 1007 | } 1008 | } 1009 | } 1010 | else { 1011 | throw new Error("localStorage and sessionStorage are not supported"); 1012 | } 1013 | }; 1014 | return Storage; 1015 | }()); 1016 | Msal.Storage = Storage; 1017 | })(Msal || (Msal = {})); 1018 | var Msal; 1019 | (function (Msal) { 1020 | var Telemetry = (function () { 1021 | function Telemetry() { 1022 | } 1023 | Telemetry.prototype.RegisterReceiver = function (receiverCallback) { 1024 | this.receiverCallback = receiverCallback; 1025 | }; 1026 | Telemetry.GetInstance = function () { 1027 | return this.instance || (this.instance = new this()); 1028 | }; 1029 | return Telemetry; 1030 | }()); 1031 | Msal.Telemetry = Telemetry; 1032 | })(Msal || (Msal = {})); 1033 | var Msal; 1034 | (function (Msal) { 1035 | var User = (function () { 1036 | function User(displayableId, name, identityProvider, userIdentifier) { 1037 | this.displayableId = displayableId; 1038 | this.name = name; 1039 | this.identityProvider = identityProvider; 1040 | this.userIdentifier = userIdentifier; 1041 | } 1042 | User.createUser = function (idToken, clientInfo, authority) { 1043 | var uid; 1044 | var utid; 1045 | if (!clientInfo) { 1046 | uid = ""; 1047 | utid = ""; 1048 | } 1049 | else { 1050 | uid = clientInfo.uid; 1051 | utid = clientInfo.utid; 1052 | } 1053 | var userIdentifier = Msal.Utils.base64EncodeStringUrlSafe(uid) + "." + Msal.Utils.base64EncodeStringUrlSafe(utid); 1054 | return new User(idToken.preferredName, idToken.name, idToken.issuer, userIdentifier); 1055 | }; 1056 | return User; 1057 | }()); 1058 | Msal.User = User; 1059 | })(Msal || (Msal = {})); 1060 | var Msal; 1061 | (function (Msal) { 1062 | var ResponseTypes = { 1063 | id_token: "id_token", 1064 | token: "token", 1065 | id_token_token: "id_token token" 1066 | }; 1067 | var UserAgentApplication = (function () { 1068 | function UserAgentApplication(clientId, authority, tokenReceivedCallback, validateAuthority) { 1069 | this._cacheLocations = { 1070 | localStorage: "localStorage", 1071 | sessionStorage: "sessionStorage" 1072 | }; 1073 | this._cacheLocation = "sessionStorage"; 1074 | this._interactionModes = { 1075 | popUp: "popUp", 1076 | redirect: "redirect" 1077 | }; 1078 | this._interactionMode = "redirect"; 1079 | this._clockSkew = 300; 1080 | this._tokenReceivedCallback = null; 1081 | this.navigateToLoginRequestUrl = true; 1082 | this.clientId = clientId; 1083 | this.validateAuthority = validateAuthority === true; 1084 | this.authority = authority ? authority : "https://login.microsoftonline.com/common"; 1085 | if (tokenReceivedCallback) { 1086 | this._tokenReceivedCallback = tokenReceivedCallback; 1087 | } 1088 | this.redirectUri = window.location.href.split("?")[0].split("#")[0]; 1089 | this.postLogoutredirectUri = this.redirectUri; 1090 | this._loginInProgress = false; 1091 | this._acquireTokenInProgress = false; 1092 | this._renewStates = []; 1093 | this._activeRenewals = {}; 1094 | this._cacheStorage = new Msal.Storage(this._cacheLocation); 1095 | this._requestContext = new Msal.RequestContext(""); 1096 | window.msal = this; 1097 | window.callBackMappedToRenewStates = {}; 1098 | window.callBacksMappedToRenewStates = {}; 1099 | if (!window.opener) { 1100 | var isCallback = this.isCallback(window.location.hash); 1101 | if (isCallback) 1102 | this.handleAuthenticationResponse(window.location.hash); 1103 | } 1104 | } 1105 | Object.defineProperty(UserAgentApplication.prototype, "cacheLocation", { 1106 | get: function () { 1107 | return this._cacheLocation; 1108 | }, 1109 | set: function (cache) { 1110 | this._cacheLocation = cache; 1111 | if (this._cacheLocations[cache]) { 1112 | this._cacheStorage = new Msal.Storage(this._cacheLocations[cache]); 1113 | } 1114 | else { 1115 | throw new Error('Cache Location is not valid. Provided value:' + this._cacheLocation + '.Possible values are: ' + this._cacheLocations.localStorage + ', ' + this._cacheLocations.sessionStorage); 1116 | } 1117 | }, 1118 | enumerable: true, 1119 | configurable: true 1120 | }); 1121 | Object.defineProperty(UserAgentApplication.prototype, "authority", { 1122 | get: function () { 1123 | return this.authorityInstance.CanonicalAuthority; 1124 | }, 1125 | set: function (val) { 1126 | this.authorityInstance = Msal.Authority.CreateInstance(val, this.validateAuthority); 1127 | }, 1128 | enumerable: true, 1129 | configurable: true 1130 | }); 1131 | UserAgentApplication.prototype.loginRedirect = function (scopes, extraQueryParameters) { 1132 | var _this = this; 1133 | if (this._loginInProgress) { 1134 | if (this._tokenReceivedCallback) { 1135 | this._tokenReceivedCallback("Login is in progress", null, null, Msal.Constants.idToken); 1136 | return; 1137 | } 1138 | } 1139 | if (scopes) { 1140 | var isValidScope = this.validateInputScope(scopes); 1141 | if (isValidScope && !Msal.Utils.isEmpty(isValidScope)) { 1142 | if (this._tokenReceivedCallback) { 1143 | this._tokenReceivedCallback(isValidScope, null, null, Msal.Constants.idToken); 1144 | return; 1145 | } 1146 | } 1147 | scopes = this.filterScopes(scopes); 1148 | } 1149 | this.authorityInstance.ResolveEndpointsAsync() 1150 | .then(function () { 1151 | var authenticationRequest = new Msal.AuthenticationRequestParameters(_this.authorityInstance, _this.clientId, scopes, ResponseTypes.id_token, _this.redirectUri); 1152 | if (extraQueryParameters) { 1153 | authenticationRequest.extraQueryParameters = extraQueryParameters; 1154 | } 1155 | _this._cacheStorage.setItem(Msal.Constants.loginRequest, window.location.href); 1156 | _this._cacheStorage.setItem(Msal.Constants.loginError, ""); 1157 | _this._cacheStorage.setItem(Msal.Constants.stateLogin, authenticationRequest.state); 1158 | _this._cacheStorage.setItem(Msal.Constants.nonceIdToken, authenticationRequest.nonce); 1159 | _this._cacheStorage.setItem(Msal.Constants.error, ""); 1160 | _this._cacheStorage.setItem(Msal.Constants.errorDescription, ""); 1161 | var authorityKey = Msal.Constants.authority + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1162 | if (Msal.Utils.isEmpty(_this._cacheStorage.getItem(authorityKey))) { 1163 | _this._cacheStorage.setItem(authorityKey, _this.authority); 1164 | } 1165 | var urlNavigate = authenticationRequest.createNavigateUrl(scopes) + "&prompt=select_account" + "&response_mode=fragment"; 1166 | _this._loginInProgress = true; 1167 | _this.promptUser(urlNavigate); 1168 | }); 1169 | }; 1170 | UserAgentApplication.prototype.loginPopup = function (scopes, extraQueryParameters) { 1171 | var _this = this; 1172 | return new Promise(function (resolve, reject) { 1173 | _this._interactionMode = _this._interactionModes.popUp; 1174 | if (_this._loginInProgress) { 1175 | reject(Msal.ErrorCodes.loginProgressError + ':' + Msal.ErrorDescription.loginProgressError); 1176 | return; 1177 | } 1178 | if (scopes) { 1179 | var isValidScope = _this.validateInputScope(scopes); 1180 | if (isValidScope && !Msal.Utils.isEmpty(isValidScope)) { 1181 | reject(Msal.ErrorCodes.inputScopesError + ':' + Msal.ErrorDescription.inputScopesError); 1182 | return; 1183 | } 1184 | scopes = _this.filterScopes(scopes); 1185 | } 1186 | var popUpWindow = _this.openWindow('about:blank', '_blank', 1, _this, resolve, reject); 1187 | if (!popUpWindow) { 1188 | return; 1189 | } 1190 | _this.authorityInstance.ResolveEndpointsAsync().then(function () { 1191 | var authenticationRequest = new Msal.AuthenticationRequestParameters(_this.authorityInstance, _this.clientId, scopes, ResponseTypes.id_token, _this.redirectUri); 1192 | if (extraQueryParameters) { 1193 | authenticationRequest.extraQueryParameters = extraQueryParameters; 1194 | } 1195 | _this._cacheStorage.setItem(Msal.Constants.loginRequest, window.location.href); 1196 | _this._cacheStorage.setItem(Msal.Constants.loginError, ""); 1197 | _this._cacheStorage.setItem(Msal.Constants.stateLogin, authenticationRequest.state); 1198 | _this._cacheStorage.setItem(Msal.Constants.nonceIdToken, authenticationRequest.nonce); 1199 | _this._cacheStorage.setItem(Msal.Constants.error, ""); 1200 | _this._cacheStorage.setItem(Msal.Constants.errorDescription, ""); 1201 | var authorityKey = Msal.Constants.authority + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1202 | if (Msal.Utils.isEmpty(_this._cacheStorage.getItem(authorityKey))) { 1203 | _this._cacheStorage.setItem(authorityKey, _this.authority); 1204 | } 1205 | var urlNavigate = authenticationRequest.createNavigateUrl(scopes) + "&prompt=select_account" + "&response_mode=fragment"; 1206 | _this._loginInProgress = true; 1207 | if (popUpWindow) { 1208 | popUpWindow.location.href = urlNavigate; 1209 | } 1210 | }, function () { 1211 | _this._requestContext.logger.info(Msal.ErrorCodes.endpointResolutionError + ':' + Msal.ErrorDescription.endpointResolutionError); 1212 | _this._cacheStorage.setItem(Msal.Constants.error, Msal.ErrorCodes.endpointResolutionError); 1213 | _this._cacheStorage.setItem(Msal.Constants.errorDescription, Msal.ErrorDescription.endpointResolutionError); 1214 | if (reject) { 1215 | reject(Msal.ErrorCodes.endpointResolutionError + ':' + Msal.ErrorDescription.endpointResolutionError); 1216 | } 1217 | if (popUpWindow) { 1218 | popUpWindow.close(); 1219 | } 1220 | }); 1221 | }); 1222 | }; 1223 | UserAgentApplication.prototype.promptUser = function (urlNavigate) { 1224 | if (urlNavigate && !Msal.Utils.isEmpty(urlNavigate)) { 1225 | this._requestContext.logger.info('Navigate to:' + urlNavigate); 1226 | window.location.replace(urlNavigate); 1227 | } 1228 | else { 1229 | this._requestContext.logger.info('Navigate url is empty'); 1230 | } 1231 | }; 1232 | ; 1233 | UserAgentApplication.prototype.openWindow = function (urlNavigate, title, interval, instance, resolve, reject) { 1234 | var _this = this; 1235 | var popupWindow = this.openPopup(urlNavigate, title, Msal.Constants.popUpWidth, Msal.Constants.popUpHeight); 1236 | if (popupWindow == null) { 1237 | instance._loginInProgress = false; 1238 | instance._acquireTokenInProgress = false; 1239 | this._requestContext.logger.info(Msal.ErrorCodes.popUpWindowError + ':' + Msal.ErrorDescription.popUpWindowError); 1240 | this._cacheStorage.setItem(Msal.Constants.error, Msal.ErrorCodes.popUpWindowError); 1241 | this._cacheStorage.setItem(Msal.Constants.errorDescription, Msal.ErrorDescription.popUpWindowError); 1242 | if (reject) { 1243 | reject(Msal.ErrorCodes.popUpWindowError + ':' + Msal.ErrorDescription.popUpWindowError); 1244 | } 1245 | return null; 1246 | } 1247 | var pollTimer = window.setInterval(function () { 1248 | if (!popupWindow || popupWindow.closed || popupWindow.closed === undefined) { 1249 | instance._loginInProgress = false; 1250 | instance._acquireTokenInProgress = false; 1251 | window.clearInterval(pollTimer); 1252 | } 1253 | try { 1254 | if (popupWindow.location.href.indexOf(_this.redirectUri) !== -1) { 1255 | _this.handleAuthenticationResponse(popupWindow.location.hash, resolve, reject); 1256 | window.clearInterval(pollTimer); 1257 | instance._loginInProgress = false; 1258 | instance._acquireTokenInProgress = false; 1259 | _this._requestContext.logger.info("Closing popup window"); 1260 | popupWindow.close(); 1261 | } 1262 | } 1263 | catch (e) { 1264 | } 1265 | }, interval); 1266 | return popupWindow; 1267 | }; 1268 | UserAgentApplication.prototype.logout = function () { 1269 | this.clearCache(); 1270 | this._user = null; 1271 | var logout = ""; 1272 | if (this.postLogoutredirectUri) { 1273 | logout = 'post_logout_redirect_uri=' + encodeURIComponent(this.postLogoutredirectUri); 1274 | } 1275 | var urlNavigate = this.authority + "/oauth2/v2.0/logout?" + logout; 1276 | this.promptUser(urlNavigate); 1277 | }; 1278 | UserAgentApplication.prototype.clearCache = function () { 1279 | this._renewStates = []; 1280 | var accessTokenItems = this._cacheStorage.getAllAccessTokens(Msal.Constants.clientId, Msal.Constants.authority); 1281 | for (var i = 0; i < accessTokenItems.length; i++) { 1282 | this._cacheStorage.removeItem(JSON.stringify(accessTokenItems[i].key)); 1283 | } 1284 | this._cacheStorage.removeAcquireTokenEntries(Msal.Constants.acquireTokenUser, Msal.Constants.renewStatus); 1285 | this._cacheStorage.removeAcquireTokenEntries(Msal.Constants.authority + Msal.Constants.resourceDelimeter, Msal.Constants.renewStatus); 1286 | this._cacheStorage.resetCacheItems(); 1287 | }; 1288 | UserAgentApplication.prototype.openPopup = function (urlNavigate, title, popUpWidth, popUpHeight) { 1289 | try { 1290 | var winLeft = window.screenLeft ? window.screenLeft : window.screenX; 1291 | var winTop = window.screenTop ? window.screenTop : window.screenY; 1292 | var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; 1293 | var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; 1294 | var left = ((width / 2) - (popUpWidth / 2)) + winLeft; 1295 | var top_1 = ((height / 2) - (popUpHeight / 2)) + winTop; 1296 | var popupWindow = window.open(urlNavigate, title, 'width=' + popUpWidth + ', height=' + popUpHeight + ', top=' + top_1 + ', left=' + left); 1297 | if (popupWindow.focus) { 1298 | popupWindow.focus(); 1299 | } 1300 | return popupWindow; 1301 | } 1302 | catch (e) { 1303 | this._requestContext.logger.error('error opening popup ' + e.message); 1304 | this._loginInProgress = false; 1305 | this._acquireTokenInProgress = false; 1306 | return null; 1307 | } 1308 | }; 1309 | UserAgentApplication.prototype.validateInputScope = function (scopes) { 1310 | if (!scopes || scopes.length < 1) { 1311 | return "Scopes cannot be passed as an empty array"; 1312 | } 1313 | if (!Array.isArray(scopes)) { 1314 | throw new Error("API does not accept non-array scopes"); 1315 | } 1316 | if (scopes.indexOf(this.clientId) > -1) { 1317 | if (scopes.length > 1) { 1318 | return "ClientId can only be provided as a single scope"; 1319 | } 1320 | } 1321 | return ""; 1322 | }; 1323 | UserAgentApplication.prototype.filterScopes = function (scopes) { 1324 | scopes = scopes.filter(function (element) { 1325 | return element !== "openid"; 1326 | }); 1327 | scopes = scopes.filter(function (element) { 1328 | return element !== "profile"; 1329 | }); 1330 | return scopes; 1331 | }; 1332 | UserAgentApplication.prototype.registerCallback = function (expectedState, scope, resolve, reject) { 1333 | var _this = this; 1334 | this._activeRenewals[scope] = expectedState; 1335 | if (!window.callBacksMappedToRenewStates[expectedState]) { 1336 | window.callBacksMappedToRenewStates[expectedState] = []; 1337 | } 1338 | window.callBacksMappedToRenewStates[expectedState].push({ resolve: resolve, reject: reject }); 1339 | if (!window.callBackMappedToRenewStates[expectedState]) { 1340 | window.callBackMappedToRenewStates[expectedState] = 1341 | function (errorDesc, token, error, tokenType) { 1342 | _this._activeRenewals[scope] = null; 1343 | for (var i = 0; i < window.callBacksMappedToRenewStates[expectedState].length; ++i) { 1344 | try { 1345 | if (errorDesc || error) { 1346 | window.callBacksMappedToRenewStates[expectedState][i].reject(errorDesc + ": " + error); 1347 | ; 1348 | } 1349 | else if (token) { 1350 | window.callBacksMappedToRenewStates[expectedState][i].resolve(token); 1351 | } 1352 | } 1353 | catch (e) { 1354 | _this._requestContext.logger.warning(e); 1355 | } 1356 | } 1357 | window.callBacksMappedToRenewStates[expectedState] = null; 1358 | window.callBackMappedToRenewStates[expectedState] = null; 1359 | }; 1360 | } 1361 | }; 1362 | UserAgentApplication.prototype.getCachedToken = function (authenticationRequest, user) { 1363 | var accessTokenCacheItem = null; 1364 | var scopes = authenticationRequest.scopes; 1365 | var tokenCacheItems = this._cacheStorage.getAllAccessTokens(this.clientId, user.userIdentifier); 1366 | if (tokenCacheItems.length === 0) { 1367 | return null; 1368 | } 1369 | var filteredItems = []; 1370 | if (!authenticationRequest.authority) { 1371 | for (var i = 0; i < tokenCacheItems.length; i++) { 1372 | var cacheItem = tokenCacheItems[i]; 1373 | var cachedScopes = cacheItem.key.scopes.split(" "); 1374 | if (Msal.Utils.containsScope(cachedScopes, scopes)) { 1375 | filteredItems.push(cacheItem); 1376 | } 1377 | } 1378 | if (filteredItems.length === 1) { 1379 | accessTokenCacheItem = filteredItems[0]; 1380 | authenticationRequest.authorityInstance = Msal.Authority.CreateInstance(accessTokenCacheItem.key.authority, this.validateAuthority); 1381 | } 1382 | else if (filteredItems.length > 1) { 1383 | return { 1384 | errorDesc: "The cache contains multiple tokens satisfying the requirements. Call AcquireToken again providing more requirements like authority", 1385 | token: null, 1386 | error: "multiple_matching_tokens_detected" 1387 | }; 1388 | } 1389 | else { 1390 | var authorityList = this.getUniqueAuthority(tokenCacheItems, 'authority'); 1391 | if (authorityList.length > 1) { 1392 | return { 1393 | errorDesc: "Multiple authorities found in the cache. Pass authority in the API overload.", 1394 | token: null, 1395 | error: "multiple_matching_tokens_detected" 1396 | }; 1397 | } 1398 | authenticationRequest.authorityInstance = Msal.Authority.CreateInstance(authorityList[0], this.validateAuthority); 1399 | } 1400 | } 1401 | else { 1402 | for (var i = 0; i < tokenCacheItems.length; i++) { 1403 | var cacheItem = tokenCacheItems[i]; 1404 | var cachedScopes = cacheItem.key.scopes.split(" "); 1405 | if (Msal.Utils.containsScope(cachedScopes, scopes) && cacheItem.key.authority === authenticationRequest.authority) { 1406 | filteredItems.push(cacheItem); 1407 | } 1408 | } 1409 | if (filteredItems.length === 0) { 1410 | return null; 1411 | } 1412 | else if (filteredItems.length === 1) { 1413 | accessTokenCacheItem = filteredItems[0]; 1414 | } 1415 | else { 1416 | return { 1417 | errorDesc: "The cache contains multiple tokens satisfying the requirements.Call AcquireToken again providing more requirements like authority", 1418 | token: null, 1419 | error: "multiple_matching_tokens_detected" 1420 | }; 1421 | } 1422 | } 1423 | if (accessTokenCacheItem != null) { 1424 | var expired = Number(accessTokenCacheItem.value.expiresIn); 1425 | var offset = this._clockSkew || 300; 1426 | if (expired && (expired > Msal.Utils.now() + offset)) { 1427 | return { 1428 | errorDesc: null, 1429 | token: accessTokenCacheItem.value.accessToken, 1430 | error: null 1431 | }; 1432 | } 1433 | else { 1434 | this._cacheStorage.removeItem(JSON.stringify(filteredItems[0].key)); 1435 | return null; 1436 | } 1437 | } 1438 | else { 1439 | return null; 1440 | } 1441 | }; 1442 | UserAgentApplication.prototype.getAllUsers = function () { 1443 | var users = []; 1444 | var accessTokenCacheItems = this._cacheStorage.getAllAccessTokens(Msal.Constants.clientId, Msal.Constants.authority); 1445 | for (var i = 0; i < accessTokenCacheItems.length; i++) { 1446 | var idToken = new Msal.IdToken(accessTokenCacheItems[i].value.idToken); 1447 | var clientInfo = new Msal.ClientInfo(accessTokenCacheItems[i].value.clientInfo); 1448 | var user = Msal.User.createUser(idToken, clientInfo, this.authority); 1449 | users.push(user); 1450 | } 1451 | return this.getUniqueUsers(users); 1452 | }; 1453 | UserAgentApplication.prototype.getUniqueUsers = function (users) { 1454 | if (!users || users.length <= 1) { 1455 | return users; 1456 | } 1457 | var flags = []; 1458 | var uniqueUsers = []; 1459 | for (var index = 0; index < users.length; ++index) { 1460 | if (users[index].userIdentifier && flags.indexOf(users[index].userIdentifier) === -1) { 1461 | flags.push(users[index].userIdentifier); 1462 | uniqueUsers.push(users[index]); 1463 | } 1464 | } 1465 | return uniqueUsers; 1466 | }; 1467 | UserAgentApplication.prototype.getUniqueAuthority = function (accessTokenCacheItems, property) { 1468 | var authorityList = []; 1469 | var flags = []; 1470 | accessTokenCacheItems.forEach(function (element) { 1471 | if (element.key.hasOwnProperty(property) && (flags.indexOf(element.key[property]) === -1)) { 1472 | flags.push(element.key[property]); 1473 | authorityList.push(element.key[property]); 1474 | } 1475 | }); 1476 | return authorityList; 1477 | }; 1478 | UserAgentApplication.prototype.addHintParameters = function (urlNavigate, user) { 1479 | var userObject = user ? user : this._user; 1480 | var decodedClientInfo = userObject.userIdentifier.split('.'); 1481 | var uid = Msal.Utils.base64DecodeStringUrlSafe(decodedClientInfo[0]); 1482 | var utid = Msal.Utils.base64DecodeStringUrlSafe(decodedClientInfo[1]); 1483 | if (userObject.displayableId && !Msal.Utils.isEmpty(userObject.displayableId)) { 1484 | urlNavigate += '&login_hint=' + encodeURIComponent(user.displayableId); 1485 | } 1486 | if (!Msal.Utils.isEmpty(uid) && !Msal.Utils.isEmpty(utid)) { 1487 | if (!this.urlContainsQueryStringParameter("domain_req", urlNavigate) && !Msal.Utils.isEmpty(utid)) { 1488 | urlNavigate += '&domain_req=' + encodeURIComponent(utid); 1489 | } 1490 | if (!this.urlContainsQueryStringParameter("login_req", urlNavigate) && !Msal.Utils.isEmpty(uid)) { 1491 | urlNavigate += '&login_req=' + encodeURIComponent(uid); 1492 | } 1493 | if (!this.urlContainsQueryStringParameter("domain_hint", urlNavigate) && !Msal.Utils.isEmpty(utid)) { 1494 | if (utid === "9188040d-6c67-4c5b-b112-36a304b66dad") { 1495 | urlNavigate += '&domain_hint=' + encodeURIComponent("consumers"); 1496 | } 1497 | else { 1498 | urlNavigate += '&domain_hint=' + encodeURIComponent("organizations"); 1499 | } 1500 | } 1501 | } 1502 | return urlNavigate; 1503 | }; 1504 | UserAgentApplication.prototype.urlContainsQueryStringParameter = function (name, url) { 1505 | var regex = new RegExp("[\\?&]" + name + "="); 1506 | return regex.test(url); 1507 | }; 1508 | UserAgentApplication.prototype.acquireTokenRedirect = function (scopes, authority, user, extraQueryParameters) { 1509 | var _this = this; 1510 | var isValidScope = this.validateInputScope(scopes); 1511 | if (isValidScope && !Msal.Utils.isEmpty(isValidScope)) { 1512 | if (this._tokenReceivedCallback) { 1513 | this._tokenReceivedCallback(isValidScope, null, null, Msal.Constants.accessToken); 1514 | return; 1515 | } 1516 | } 1517 | if (scopes) { 1518 | scopes = this.filterScopes(scopes); 1519 | } 1520 | var userObject = user ? user : this._user; 1521 | if (this._acquireTokenInProgress) { 1522 | return; 1523 | } 1524 | var scope = scopes.join(" ").toLowerCase(); 1525 | if (!userObject) { 1526 | if (this._tokenReceivedCallback) { 1527 | this._tokenReceivedCallback(Msal.ErrorDescription.userLoginError, null, Msal.ErrorCodes.userLoginError, Msal.Constants.accessToken); 1528 | return; 1529 | } 1530 | } 1531 | this._acquireTokenInProgress = true; 1532 | var authenticationRequest; 1533 | var acquireTokenAuthority = authority ? Msal.Authority.CreateInstance(authority, this.validateAuthority) : this.authorityInstance; 1534 | acquireTokenAuthority.ResolveEndpointsAsync().then(function () { 1535 | if (Msal.Utils.compareObjects(userObject, _this._user)) { 1536 | authenticationRequest = new Msal.AuthenticationRequestParameters(acquireTokenAuthority, _this.clientId, scopes, ResponseTypes.token, _this.redirectUri); 1537 | } 1538 | else { 1539 | authenticationRequest = new Msal.AuthenticationRequestParameters(acquireTokenAuthority, _this.clientId, scopes, ResponseTypes.id_token_token, _this.redirectUri); 1540 | } 1541 | _this._cacheStorage.setItem(Msal.Constants.nonceIdToken, authenticationRequest.nonce); 1542 | var acquireTokenUserKey = Msal.Constants.acquireTokenUser + Msal.Constants.resourceDelimeter + userObject.userIdentifier + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1543 | if (Msal.Utils.isEmpty(_this._cacheStorage.getItem(acquireTokenUserKey))) { 1544 | _this._cacheStorage.setItem(acquireTokenUserKey, JSON.stringify(userObject)); 1545 | } 1546 | var authorityKey = Msal.Constants.authority + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1547 | if (Msal.Utils.isEmpty(_this._cacheStorage.getItem(authorityKey))) { 1548 | _this._cacheStorage.setItem(authorityKey, acquireTokenAuthority.CanonicalAuthority); 1549 | } 1550 | if (extraQueryParameters) { 1551 | authenticationRequest.extraQueryParameters = extraQueryParameters; 1552 | } 1553 | var urlNavigate = authenticationRequest.createNavigateUrl(scopes) + "&prompt=select_account" + "&response_mode=fragment"; 1554 | urlNavigate = _this.addHintParameters(urlNavigate, userObject); 1555 | if (urlNavigate) { 1556 | _this._cacheStorage.setItem(Msal.Constants.stateAcquireToken, authenticationRequest.state); 1557 | window.location.replace(urlNavigate); 1558 | } 1559 | }); 1560 | }; 1561 | UserAgentApplication.prototype.acquireTokenPopup = function (scopes, authority, user, extraQueryParameters) { 1562 | var _this = this; 1563 | return new Promise(function (resolve, reject) { 1564 | _this._interactionMode = _this._interactionModes.popUp; 1565 | var isValidScope = _this.validateInputScope(scopes); 1566 | if (isValidScope && !Msal.Utils.isEmpty(isValidScope)) { 1567 | reject(Msal.ErrorCodes.inputScopesError + ':' + isValidScope); 1568 | } 1569 | if (scopes) { 1570 | scopes = _this.filterScopes(scopes); 1571 | } 1572 | var userObject = user ? user : _this._user; 1573 | if (_this._acquireTokenInProgress) { 1574 | reject(Msal.ErrorCodes.acquireTokenProgressError + ':' + Msal.ErrorDescription.acquireTokenProgressError); 1575 | return; 1576 | } 1577 | var scope = scopes.join(" ").toLowerCase(); 1578 | if (!userObject) { 1579 | reject(Msal.ErrorCodes.userLoginError + ':' + Msal.ErrorDescription.userLoginError); 1580 | return; 1581 | } 1582 | _this._acquireTokenInProgress = true; 1583 | var authenticationRequest; 1584 | var acquireTokenAuthority = authority ? Msal.Authority.CreateInstance(authority, _this.validateAuthority) : _this.authorityInstance; 1585 | var popUpWindow = _this.openWindow('about:blank', '_blank', 1, _this, resolve, reject); 1586 | if (!popUpWindow) { 1587 | return; 1588 | } 1589 | acquireTokenAuthority.ResolveEndpointsAsync().then(function () { 1590 | if (Msal.Utils.compareObjects(userObject, _this._user)) { 1591 | authenticationRequest = new Msal.AuthenticationRequestParameters(acquireTokenAuthority, _this.clientId, scopes, ResponseTypes.token, _this.redirectUri); 1592 | } 1593 | else { 1594 | authenticationRequest = new Msal.AuthenticationRequestParameters(acquireTokenAuthority, _this.clientId, scopes, ResponseTypes.id_token_token, _this.redirectUri); 1595 | } 1596 | _this._cacheStorage.setItem(Msal.Constants.nonceIdToken, authenticationRequest.nonce); 1597 | authenticationRequest.state = authenticationRequest.state; 1598 | var acquireTokenUserKey = Msal.Constants.acquireTokenUser + Msal.Constants.resourceDelimeter + userObject.userIdentifier + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1599 | if (Msal.Utils.isEmpty(_this._cacheStorage.getItem(acquireTokenUserKey))) { 1600 | _this._cacheStorage.setItem(acquireTokenUserKey, JSON.stringify(userObject)); 1601 | } 1602 | var authorityKey = Msal.Constants.authority + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1603 | if (Msal.Utils.isEmpty(_this._cacheStorage.getItem(authorityKey))) { 1604 | _this._cacheStorage.setItem(authorityKey, acquireTokenAuthority.CanonicalAuthority); 1605 | } 1606 | if (extraQueryParameters) { 1607 | authenticationRequest.extraQueryParameters = extraQueryParameters; 1608 | } 1609 | var urlNavigate = authenticationRequest.createNavigateUrl(scopes) + "&prompt=select_account" + "&response_mode=fragment"; 1610 | urlNavigate = _this.addHintParameters(urlNavigate, userObject); 1611 | _this._renewStates.push(authenticationRequest.state); 1612 | _this.registerCallback(authenticationRequest.state, scope, resolve, reject); 1613 | if (popUpWindow) { 1614 | popUpWindow.location.href = urlNavigate; 1615 | } 1616 | }, function () { 1617 | _this._requestContext.logger.info(Msal.ErrorCodes.endpointResolutionError + ':' + Msal.ErrorDescription.endpointResolutionError); 1618 | _this._cacheStorage.setItem(Msal.Constants.error, Msal.ErrorCodes.endpointResolutionError); 1619 | _this._cacheStorage.setItem(Msal.Constants.errorDescription, Msal.ErrorDescription.endpointResolutionError); 1620 | if (reject) { 1621 | reject(Msal.ErrorCodes.endpointResolutionError + ':' + Msal.ErrorDescription.endpointResolutionError); 1622 | } 1623 | if (popUpWindow) 1624 | popUpWindow.close(); 1625 | }); 1626 | }); 1627 | }; 1628 | UserAgentApplication.prototype.acquireTokenSilent = function (scopes, authority, user, extraQueryParameters) { 1629 | var _this = this; 1630 | return new Promise(function (resolve, reject) { 1631 | var isValidScope = _this.validateInputScope(scopes); 1632 | if (isValidScope && !Msal.Utils.isEmpty(isValidScope)) { 1633 | reject(Msal.ErrorCodes.inputScopesError + ':' + isValidScope); 1634 | } 1635 | else { 1636 | if (scopes) { 1637 | scopes = _this.filterScopes(scopes); 1638 | } 1639 | var scope = scopes.join(" ").toLowerCase(); 1640 | var userObject_1 = user ? user : _this._user; 1641 | if (!userObject_1) { 1642 | reject(Msal.ErrorCodes.userLoginError + ':' + Msal.ErrorDescription.userLoginError); 1643 | return; 1644 | } 1645 | var authenticationRequest_1; 1646 | var newAuthority = authority ? Msal.Authority.CreateInstance(authority, _this.validateAuthority) : _this.authorityInstance; 1647 | if (Msal.Utils.compareObjects(userObject_1, _this._user)) { 1648 | authenticationRequest_1 = new Msal.AuthenticationRequestParameters(newAuthority, _this.clientId, scopes, ResponseTypes.token, _this.redirectUri); 1649 | } 1650 | else { 1651 | authenticationRequest_1 = new Msal.AuthenticationRequestParameters(newAuthority, _this.clientId, scopes, ResponseTypes.id_token_token, _this.redirectUri); 1652 | } 1653 | var cacheResult = _this.getCachedToken(authenticationRequest_1, userObject_1); 1654 | if (cacheResult) { 1655 | if (cacheResult.token) { 1656 | _this._requestContext.logger.info('Token is already in cache for scope:' + scope); 1657 | resolve(cacheResult.token); 1658 | return; 1659 | } 1660 | else if (cacheResult.errorDesc || cacheResult.error) { 1661 | _this._requestContext.logger.info(cacheResult.errorDesc + ":" + cacheResult.error); 1662 | reject(cacheResult.errorDesc + ": " + cacheResult.error); 1663 | return; 1664 | } 1665 | } 1666 | if (_this._activeRenewals[scope]) { 1667 | _this.registerCallback(_this._activeRenewals[scope], scope, resolve, reject); 1668 | } 1669 | return _this.authorityInstance.ResolveEndpointsAsync() 1670 | .then(function () { 1671 | if (scopes && scopes.indexOf(_this.clientId) > -1 && scopes.length === 1) { 1672 | _this._requestContext.logger.verbose("renewing idToken"); 1673 | _this.renewIdToken(scopes, resolve, reject, userObject_1, authenticationRequest_1, extraQueryParameters); 1674 | } 1675 | else { 1676 | _this._requestContext.logger.verbose("renewing accesstoken"); 1677 | _this.renewToken(scopes, resolve, reject, userObject_1, authenticationRequest_1, extraQueryParameters); 1678 | } 1679 | }); 1680 | } 1681 | }); 1682 | }; 1683 | UserAgentApplication.prototype.loadFrameTimeout = function (urlNavigate, frameName, scope) { 1684 | var _this = this; 1685 | this._requestContext.logger.verbose('Set loading state to pending for: ' + scope); 1686 | this._cacheStorage.setItem(Msal.Constants.renewStatus + scope, Msal.Constants.tokenRenewStatusInProgress); 1687 | this.loadFrame(urlNavigate, frameName); 1688 | setTimeout(function () { 1689 | if (_this._cacheStorage.getItem(Msal.Constants.renewStatus + scope) === Msal.Constants.tokenRenewStatusInProgress) { 1690 | _this._requestContext.logger.verbose('Loading frame has timed out after: ' + (Msal.Constants.loadFrameTimeout / 1000) + ' seconds for scope ' + scope); 1691 | var expectedState = _this._activeRenewals[scope]; 1692 | if (expectedState && window.callBackMappedToRenewStates[expectedState]) 1693 | window.callBackMappedToRenewStates[expectedState]("Token renewal operation failed due to timeout", null, null, Msal.Constants.accessToken); 1694 | _this._cacheStorage.setItem(Msal.Constants.renewStatus + scope, Msal.Constants.tokenRenewStatusCancelled); 1695 | } 1696 | }, Msal.Constants.loadFrameTimeout); 1697 | }; 1698 | UserAgentApplication.prototype.loadFrame = function (urlNavigate, frameName) { 1699 | var _this = this; 1700 | this._requestContext.logger.info('LoadFrame: ' + frameName); 1701 | var frameCheck = frameName; 1702 | setTimeout(function () { 1703 | var frameHandle = _this.addAdalFrame(frameCheck); 1704 | if (frameHandle.src === "" || frameHandle.src === "about:blank") { 1705 | frameHandle.src = urlNavigate; 1706 | } 1707 | }, 500); 1708 | }; 1709 | UserAgentApplication.prototype.addAdalFrame = function (iframeId) { 1710 | if (typeof iframeId === "undefined") { 1711 | return null; 1712 | } 1713 | this._requestContext.logger.info('Add msal frame to document:' + iframeId); 1714 | var adalFrame = document.getElementById(iframeId); 1715 | if (!adalFrame) { 1716 | if (document.createElement && 1717 | document.documentElement && 1718 | (window.navigator.userAgent.indexOf("MSIE 5.0") === -1)) { 1719 | var ifr = document.createElement("iframe"); 1720 | ifr.setAttribute("id", iframeId); 1721 | ifr.style.visibility = "hidden"; 1722 | ifr.style.position = "absolute"; 1723 | ifr.style.width = ifr.style.height = "0"; 1724 | adalFrame = document.getElementsByTagName("body")[0].appendChild(ifr); 1725 | } 1726 | else if (document.body && document.body.insertAdjacentHTML) { 1727 | document.body.insertAdjacentHTML('beforeEnd', ''); 1728 | } 1729 | if (window.frames && window.frames[iframeId]) { 1730 | adalFrame = window.frames[iframeId]; 1731 | } 1732 | } 1733 | return adalFrame; 1734 | }; 1735 | UserAgentApplication.prototype.renewToken = function (scopes, resolve, reject, user, authenticationRequest, extraQueryParameters) { 1736 | var scope = scopes.join(" ").toLowerCase(); 1737 | this._requestContext.logger.verbose('renewToken is called for scope:' + scope); 1738 | var frameHandle = this.addAdalFrame('msalRenewFrame' + scope); 1739 | if (extraQueryParameters) { 1740 | authenticationRequest.extraQueryParameters = extraQueryParameters; 1741 | } 1742 | var acquireTokenUserKey = Msal.Constants.acquireTokenUser + Msal.Constants.resourceDelimeter + user.userIdentifier + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1743 | if (Msal.Utils.isEmpty(this._cacheStorage.getItem(acquireTokenUserKey))) { 1744 | this._cacheStorage.setItem(acquireTokenUserKey, JSON.stringify(user)); 1745 | } 1746 | var authorityKey = Msal.Constants.authority + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1747 | if (Msal.Utils.isEmpty(this._cacheStorage.getItem(authorityKey))) { 1748 | this._cacheStorage.setItem(authorityKey, authenticationRequest.authority); 1749 | } 1750 | this._cacheStorage.setItem(Msal.Constants.nonceIdToken, authenticationRequest.nonce); 1751 | this._requestContext.logger.verbose('Renew token Expected state: ' + authenticationRequest.state); 1752 | var urlNavigate = authenticationRequest.createNavigateUrl(scopes) + "&prompt=none"; 1753 | urlNavigate = this.addHintParameters(urlNavigate, user); 1754 | this._renewStates.push(authenticationRequest.state); 1755 | this.registerCallback(authenticationRequest.state, scope, resolve, reject); 1756 | this._requestContext.logger.infoPii('Navigate to:' + urlNavigate); 1757 | frameHandle.src = "about:blank"; 1758 | this.loadFrameTimeout(urlNavigate, 'msalRenewFrame' + scope, scope); 1759 | }; 1760 | UserAgentApplication.prototype.renewIdToken = function (scopes, resolve, reject, user, authenticationRequest, extraQueryParameters) { 1761 | var scope = scopes.join(" ").toLowerCase(); 1762 | this._requestContext.logger.info('renewidToken is called'); 1763 | var frameHandle = this.addAdalFrame("msalIdTokenFrame"); 1764 | if (extraQueryParameters) { 1765 | authenticationRequest.extraQueryParameters = extraQueryParameters; 1766 | } 1767 | var acquireTokenUserKey = Msal.Constants.acquireTokenUser + Msal.Constants.resourceDelimeter + user.userIdentifier + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1768 | if (Msal.Utils.isEmpty(this._cacheStorage.getItem(acquireTokenUserKey))) { 1769 | this._cacheStorage.setItem(acquireTokenUserKey, JSON.stringify(user)); 1770 | } 1771 | var authorityKey = Msal.Constants.authority + Msal.Constants.resourceDelimeter + authenticationRequest.state; 1772 | if (Msal.Utils.isEmpty(this._cacheStorage.getItem(authorityKey))) { 1773 | this._cacheStorage.setItem(authorityKey, authenticationRequest.authority); 1774 | } 1775 | this._cacheStorage.setItem(Msal.Constants.nonceIdToken, authenticationRequest.nonce); 1776 | this._requestContext.logger.verbose('Renew Idtoken Expected state: ' + authenticationRequest.state); 1777 | var urlNavigate = authenticationRequest.createNavigateUrl(scopes) + "&prompt=none"; 1778 | urlNavigate = this.addHintParameters(urlNavigate, user); 1779 | this._renewStates.push(authenticationRequest.state); 1780 | this.registerCallback(authenticationRequest.state, this.clientId, resolve, reject); 1781 | this._requestContext.logger.infoPii('Navigate to:' + urlNavigate); 1782 | frameHandle.src = "about:blank"; 1783 | this.loadFrameTimeout(urlNavigate, "adalIdTokenFrame", this.clientId); 1784 | }; 1785 | UserAgentApplication.prototype.getUser = function () { 1786 | if (this._user) { 1787 | return this._user; 1788 | } 1789 | var rawIdToken = this._cacheStorage.getItem(Msal.Constants.idTokenKey); 1790 | var rawClientInfo = this._cacheStorage.getItem(Msal.Constants.clientInfo); 1791 | if (!Msal.Utils.isEmpty(rawIdToken) && !Msal.Utils.isEmpty(rawClientInfo)) { 1792 | var idToken = new Msal.IdToken(rawIdToken); 1793 | var clientInfo = new Msal.ClientInfo(rawClientInfo); 1794 | this._user = Msal.User.createUser(idToken, clientInfo, this.authority); 1795 | return this._user; 1796 | } 1797 | return null; 1798 | }; 1799 | ; 1800 | UserAgentApplication.prototype.handleAuthenticationResponse = function (hash, resolve, reject) { 1801 | if (hash == null) { 1802 | hash = window.location.hash; 1803 | } 1804 | if (this.isCallback(hash)) { 1805 | var requestInfo = this.getRequestInfo(hash); 1806 | this._requestContext.logger.info("Returned from redirect url"); 1807 | this.saveTokenFromHash(requestInfo); 1808 | var token = null, tokenReceivedCallback = null, tokenType = void 0; 1809 | if ((requestInfo.requestType === Msal.Constants.renewToken) && window.parent) { 1810 | if (window.parent !== window) 1811 | this._requestContext.logger.verbose("Window is in iframe, acquiring token silently"); 1812 | else 1813 | this._requestContext.logger.verbose("acquiring token interactive in progress"); 1814 | if (window.parent.callBackMappedToRenewStates[requestInfo.stateResponse]) 1815 | tokenReceivedCallback = window.parent.callBackMappedToRenewStates[requestInfo.stateResponse]; 1816 | else 1817 | tokenReceivedCallback = this._tokenReceivedCallback; 1818 | token = requestInfo.parameters[Msal.Constants.accessToken] || requestInfo.parameters[Msal.Constants.idToken]; 1819 | tokenType = Msal.Constants.accessToken; 1820 | } 1821 | else if (requestInfo.requestType === Msal.Constants.login) { 1822 | tokenReceivedCallback = this._tokenReceivedCallback; 1823 | token = requestInfo.parameters[Msal.Constants.idToken]; 1824 | tokenType = Msal.Constants.idToken; 1825 | } 1826 | try { 1827 | var errorDesc = requestInfo.parameters[Msal.Constants.errorDescription]; 1828 | var error = requestInfo.parameters[Msal.Constants.error]; 1829 | if (reject && resolve) { 1830 | if (error || errorDesc) { 1831 | reject(errorDesc + ":" + error); 1832 | } 1833 | else if (token) { 1834 | resolve(token); 1835 | } 1836 | } 1837 | else if (tokenReceivedCallback) { 1838 | tokenReceivedCallback(errorDesc, token, error, tokenType); 1839 | } 1840 | } 1841 | catch (err) { 1842 | this._requestContext.logger.error('Error occurred in token received callback function: ' + err); 1843 | } 1844 | if (this._interactionMode !== this._interactionModes.popUp) { 1845 | window.location.hash = ""; 1846 | if (this.navigateToLoginRequestUrl && window.location.href.replace("#", "") !== this._cacheStorage.getItem(Msal.Constants.loginRequest)) 1847 | window.location.href = this._cacheStorage.getItem(Msal.Constants.loginRequest); 1848 | } 1849 | } 1850 | }; 1851 | UserAgentApplication.prototype.saveAccessToken = function (authority, tokenResponse, user, clientInfo, idToken) { 1852 | var scope; 1853 | var clientObj = new Msal.ClientInfo(clientInfo); 1854 | if (tokenResponse.parameters.hasOwnProperty("scope")) { 1855 | scope = tokenResponse.parameters["scope"]; 1856 | var consentedScopes = scope.split(" "); 1857 | var accessTokenCacheItems = this._cacheStorage.getAllAccessTokens(this.clientId, authority); 1858 | for (var i = 0; i < accessTokenCacheItems.length; i++) { 1859 | var accessTokenCacheItem = accessTokenCacheItems[i]; 1860 | if (accessTokenCacheItem.key.userIdentifier === user.userIdentifier) { 1861 | var cachedScopes = accessTokenCacheItem.key.scopes.split(" "); 1862 | if (Msal.Utils.isIntersectingScopes(cachedScopes, consentedScopes)) 1863 | this._cacheStorage.removeItem(JSON.stringify(accessTokenCacheItem.key)); 1864 | } 1865 | } 1866 | var accessTokenKey = new Msal.AccessTokenKey(authority, this.clientId, scope, clientObj.uid, clientObj.utid); 1867 | var accessTokenValue = new Msal.AccessTokenValue(tokenResponse.parameters[Msal.Constants.accessToken], idToken.rawIdToken, Msal.Utils.expiresIn(tokenResponse.parameters[Msal.Constants.expiresIn]).toString(), clientInfo); 1868 | this._cacheStorage.setItem(JSON.stringify(accessTokenKey), JSON.stringify(accessTokenValue)); 1869 | } 1870 | else { 1871 | scope = this.clientId; 1872 | var accessTokenKey = new Msal.AccessTokenKey(authority, this.clientId, scope, clientObj.uid, clientObj.utid); 1873 | var accessTokenValue = new Msal.AccessTokenValue(tokenResponse.parameters[Msal.Constants.idToken], tokenResponse.parameters[Msal.Constants.idToken], idToken.expiration, clientInfo); 1874 | this._cacheStorage.setItem(JSON.stringify(accessTokenKey), JSON.stringify(accessTokenValue)); 1875 | } 1876 | }; 1877 | UserAgentApplication.prototype.saveTokenFromHash = function (tokenResponse) { 1878 | this._requestContext.logger.info('State status:' + tokenResponse.stateMatch + '; Request type:' + tokenResponse.requestType); 1879 | this._cacheStorage.setItem(Msal.Constants.error, ""); 1880 | this._cacheStorage.setItem(Msal.Constants.errorDescription, ""); 1881 | var scope = ''; 1882 | if (tokenResponse.parameters.hasOwnProperty("scope")) { 1883 | scope = tokenResponse.parameters["scope"]; 1884 | } 1885 | else { 1886 | scope = this.clientId; 1887 | } 1888 | if (tokenResponse.parameters.hasOwnProperty(Msal.Constants.errorDescription) || tokenResponse.parameters.hasOwnProperty(Msal.Constants.error)) { 1889 | this._requestContext.logger.info('Error :' + tokenResponse.parameters[Msal.Constants.error] + '; Error description:' + tokenResponse.parameters[Msal.Constants.errorDescription]); 1890 | this._cacheStorage.setItem(Msal.Constants.error, tokenResponse.parameters["error"]); 1891 | this._cacheStorage.setItem(Msal.Constants.errorDescription, tokenResponse.parameters[Msal.Constants.errorDescription]); 1892 | if (tokenResponse.requestType === Msal.Constants.login) { 1893 | this._loginInProgress = false; 1894 | this._cacheStorage.setItem(Msal.Constants.loginError, tokenResponse.parameters[Msal.Constants.errorDescription] + ':' + tokenResponse.parameters[Msal.Constants.error]); 1895 | } 1896 | if (tokenResponse.requestType === Msal.Constants.renewToken) { 1897 | this._acquireTokenInProgress = false; 1898 | } 1899 | } 1900 | else { 1901 | if (tokenResponse.stateMatch) { 1902 | this._requestContext.logger.info("State is right"); 1903 | if (tokenResponse.parameters.hasOwnProperty(Msal.Constants.sessionState)) 1904 | this._cacheStorage.setItem(Msal.Constants.sessionState, tokenResponse.parameters[Msal.Constants.sessionState]); 1905 | var idToken; 1906 | var clientInfo = ''; 1907 | if (tokenResponse.parameters.hasOwnProperty(Msal.Constants.accessToken)) { 1908 | this._requestContext.logger.info("Fragment has access token"); 1909 | this._acquireTokenInProgress = false; 1910 | var user = void 0; 1911 | if (tokenResponse.parameters.hasOwnProperty(Msal.Constants.idToken)) { 1912 | idToken = new Msal.IdToken(tokenResponse.parameters[Msal.Constants.idToken]); 1913 | } 1914 | else { 1915 | idToken = new Msal.IdToken(this._cacheStorage.getItem(Msal.Constants.idTokenKey)); 1916 | } 1917 | var authorityKey = Msal.Constants.authority + Msal.Constants.resourceDelimeter + tokenResponse.stateResponse; 1918 | var authority = void 0; 1919 | if (!Msal.Utils.isEmpty(this._cacheStorage.getItem(authorityKey))) { 1920 | authority = this._cacheStorage.getItem(authorityKey); 1921 | authority = Msal.Utils.replaceFirstPath(authority, idToken.tenantId); 1922 | } 1923 | if (tokenResponse.parameters.hasOwnProperty(Msal.Constants.clientInfo)) { 1924 | clientInfo = tokenResponse.parameters[Msal.Constants.clientInfo]; 1925 | user = Msal.User.createUser(idToken, new Msal.ClientInfo(clientInfo), authority); 1926 | } 1927 | else { 1928 | this._requestContext.logger.warning("ClientInfo not received in the response from AAD"); 1929 | user = Msal.User.createUser(idToken, new Msal.ClientInfo(clientInfo), authority); 1930 | } 1931 | var acquireTokenUserKey = Msal.Constants.acquireTokenUser + Msal.Constants.resourceDelimeter + user.userIdentifier + Msal.Constants.resourceDelimeter + tokenResponse.stateResponse; 1932 | var acquireTokenUser = void 0; 1933 | if (!Msal.Utils.isEmpty(this._cacheStorage.getItem(acquireTokenUserKey))) { 1934 | acquireTokenUser = JSON.parse(this._cacheStorage.getItem(acquireTokenUserKey)); 1935 | if (user && acquireTokenUser && Msal.Utils.compareObjects(user, acquireTokenUser)) { 1936 | this.saveAccessToken(authority, tokenResponse, user, clientInfo, idToken); 1937 | this._requestContext.logger.info("The user object received in the response is the same as the one passed in the acquireToken request"); 1938 | } 1939 | else { 1940 | this._requestContext.logger.warning("The user object created from the response is not the same as the one passed in the acquireToken request"); 1941 | } 1942 | } 1943 | } 1944 | if (tokenResponse.parameters.hasOwnProperty(Msal.Constants.idToken)) { 1945 | if (scope.indexOf(this.clientId) > -1) { 1946 | this._requestContext.logger.info("Fragment has id token"); 1947 | this._loginInProgress = false; 1948 | idToken = new Msal.IdToken(tokenResponse.parameters[Msal.Constants.idToken]); 1949 | if (tokenResponse.parameters.hasOwnProperty(Msal.Constants.clientInfo)) { 1950 | clientInfo = tokenResponse.parameters[Msal.Constants.clientInfo]; 1951 | } 1952 | else { 1953 | this._requestContext.logger.warning("ClientInfo not received in the response from AAD"); 1954 | } 1955 | var authorityKey = Msal.Constants.authority + Msal.Constants.resourceDelimeter + tokenResponse.stateResponse; 1956 | var authority = void 0; 1957 | if (!Msal.Utils.isEmpty(this._cacheStorage.getItem(authorityKey))) { 1958 | authority = this._cacheStorage.getItem(authorityKey); 1959 | authority = Msal.Utils.replaceFirstPath(authority, idToken.tenantId); 1960 | } 1961 | this._user = Msal.User.createUser(idToken, new Msal.ClientInfo(clientInfo), authority); 1962 | if (idToken && idToken.nonce) { 1963 | if (idToken.nonce !== this._cacheStorage.getItem(Msal.Constants.nonceIdToken)) { 1964 | this._user = null; 1965 | this._cacheStorage.setItem(Msal.Constants.loginError, 'Nonce Mismatch.Expected: ' + this._cacheStorage.getItem(Msal.Constants.nonceIdToken) + ',' + 'Actual: ' + idToken.nonce); 1966 | } 1967 | else { 1968 | this._cacheStorage.setItem(Msal.Constants.idTokenKey, tokenResponse.parameters[Msal.Constants.idToken]); 1969 | this._cacheStorage.setItem(Msal.Constants.clientInfo, clientInfo); 1970 | this.saveAccessToken(authority, tokenResponse, this._user, clientInfo, idToken); 1971 | } 1972 | } 1973 | else { 1974 | this._cacheStorage.setItem(Msal.Constants.error, 'invalid idToken'); 1975 | this._cacheStorage.setItem(Msal.Constants.errorDescription, 'Invalid idToken. idToken: ' + tokenResponse.parameters[Msal.Constants.idToken]); 1976 | } 1977 | } 1978 | } 1979 | } 1980 | else { 1981 | this._cacheStorage.setItem(Msal.Constants.error, 'Invalid_state'); 1982 | this._cacheStorage.setItem(Msal.Constants.errorDescription, 'Invalid_state. state: ' + tokenResponse.stateResponse); 1983 | } 1984 | } 1985 | this._cacheStorage.setItem(Msal.Constants.renewStatus + scope, Msal.Constants.tokenRenewStatusCompleted); 1986 | this._cacheStorage.removeAcquireTokenEntries(Msal.Constants.acquireTokenUser, Msal.Constants.renewStatus); 1987 | this._cacheStorage.removeAcquireTokenEntries(Msal.Constants.authority + Msal.Constants.resourceDelimeter, Msal.Constants.renewStatus); 1988 | }; 1989 | ; 1990 | UserAgentApplication.prototype.isCallback = function (hash) { 1991 | hash = this.getHash(hash); 1992 | var parameters = Msal.Utils.deserialize(hash); 1993 | return (parameters.hasOwnProperty(Msal.Constants.errorDescription) || 1994 | parameters.hasOwnProperty(Msal.Constants.error) || 1995 | parameters.hasOwnProperty(Msal.Constants.accessToken) || 1996 | parameters.hasOwnProperty(Msal.Constants.idToken)); 1997 | }; 1998 | UserAgentApplication.prototype.getHash = function (hash) { 1999 | if (hash.indexOf("#/") > -1) { 2000 | hash = hash.substring(hash.indexOf("#/") + 2); 2001 | } 2002 | else if (hash.indexOf("#") > -1) { 2003 | hash = hash.substring(1); 2004 | } 2005 | return hash; 2006 | }; 2007 | ; 2008 | UserAgentApplication.prototype.getRequestInfo = function (hash) { 2009 | hash = this.getHash(hash); 2010 | var parameters = Msal.Utils.deserialize(hash); 2011 | var tokenResponse = new Msal.TokenResponse(); 2012 | if (parameters) { 2013 | tokenResponse.parameters = parameters; 2014 | if (parameters.hasOwnProperty(Msal.Constants.errorDescription) || 2015 | parameters.hasOwnProperty(Msal.Constants.error) || 2016 | parameters.hasOwnProperty(Msal.Constants.accessToken) || 2017 | parameters.hasOwnProperty(Msal.Constants.idToken)) { 2018 | tokenResponse.valid = true; 2019 | var stateResponse = void 0; 2020 | if (parameters.hasOwnProperty("state")) 2021 | stateResponse = parameters.state; 2022 | else 2023 | return tokenResponse; 2024 | tokenResponse.stateResponse = stateResponse; 2025 | if (stateResponse === this._cacheStorage.getItem(Msal.Constants.stateLogin)) { 2026 | tokenResponse.requestType = Msal.Constants.login; 2027 | tokenResponse.stateMatch = true; 2028 | return tokenResponse; 2029 | } 2030 | else if (stateResponse === this._cacheStorage.getItem(Msal.Constants.stateAcquireToken)) { 2031 | tokenResponse.requestType = Msal.Constants.renewToken; 2032 | tokenResponse.stateMatch = true; 2033 | return tokenResponse; 2034 | } 2035 | if (!tokenResponse.stateMatch && window.parent && window.parent.msal) { 2036 | var clientApplication = window.parent.msal; 2037 | var statesInParentContext = clientApplication._renewStates; 2038 | for (var i = 0; i < statesInParentContext.length; i++) { 2039 | if (statesInParentContext[i] === tokenResponse.stateResponse) { 2040 | tokenResponse.requestType = Msal.Constants.renewToken; 2041 | tokenResponse.stateMatch = true; 2042 | break; 2043 | } 2044 | } 2045 | } 2046 | } 2047 | } 2048 | return tokenResponse; 2049 | }; 2050 | ; 2051 | UserAgentApplication.prototype.getScopeFromState = function (state) { 2052 | if (state) { 2053 | var splitIndex = state.indexOf("|"); 2054 | if (splitIndex > -1 && splitIndex + 1 < state.length) { 2055 | return state.substring(splitIndex + 1); 2056 | } 2057 | } 2058 | return ""; 2059 | }; 2060 | ; 2061 | return UserAgentApplication; 2062 | }()); 2063 | Msal.UserAgentApplication = UserAgentApplication; 2064 | })(Msal || (Msal = {})); 2065 | var Msal; 2066 | (function (Msal) { 2067 | var Utils = (function () { 2068 | function Utils() { 2069 | } 2070 | Utils.compareObjects = function (u1, u2) { 2071 | if (!u1 || !u2) 2072 | return false; 2073 | if (u1.userIdentifier && u2.userIdentifier) { 2074 | if (u1.userIdentifier === u2.userIdentifier) { 2075 | return true; 2076 | } 2077 | } 2078 | return false; 2079 | }; 2080 | ; 2081 | Utils.expiresIn = function (expires) { 2082 | if (!expires) 2083 | expires = "3599"; 2084 | return this.now() + parseInt(expires, 10); 2085 | }; 2086 | ; 2087 | Utils.now = function () { 2088 | return Math.round(new Date().getTime() / 1000.0); 2089 | }; 2090 | ; 2091 | Utils.isEmpty = function (str) { 2092 | return (typeof str === "undefined" || !str || 0 === str.length); 2093 | }; 2094 | ; 2095 | Utils.extractIdToken = function (encodedIdToken) { 2096 | var decodedToken = this.decodeJwt(encodedIdToken); 2097 | if (!decodedToken) { 2098 | return null; 2099 | } 2100 | try { 2101 | var base64IdToken = decodedToken.JWSPayload; 2102 | var base64Decoded = this.base64DecodeStringUrlSafe(base64IdToken); 2103 | if (!base64Decoded) { 2104 | return null; 2105 | } 2106 | return JSON.parse(base64Decoded); 2107 | } 2108 | catch (err) { 2109 | } 2110 | return null; 2111 | }; 2112 | ; 2113 | Utils.base64EncodeStringUrlSafe = function (input) { 2114 | if (window.btoa) { 2115 | return window.btoa(input); 2116 | } 2117 | else { 2118 | return this.encode(input); 2119 | } 2120 | }; 2121 | Utils.base64DecodeStringUrlSafe = function (base64IdToken) { 2122 | base64IdToken = base64IdToken.replace(/-/g, "+").replace(/_/g, "/"); 2123 | if (window.atob) { 2124 | return decodeURIComponent(window.atob(base64IdToken)); 2125 | } 2126 | else { 2127 | return decodeURIComponent(this.decode(base64IdToken)); 2128 | } 2129 | }; 2130 | ; 2131 | Utils.encode = function (input) { 2132 | var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 2133 | var output = ""; 2134 | var chr1, chr2, chr3, enc1, enc2, enc3, enc4; 2135 | var i = 0; 2136 | input = this.utf8Encode(input); 2137 | while (i < input.length) { 2138 | chr1 = input.charCodeAt(i++); 2139 | chr2 = input.charCodeAt(i++); 2140 | chr3 = input.charCodeAt(i++); 2141 | enc1 = chr1 >> 2; 2142 | enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 2143 | enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 2144 | enc4 = chr3 & 63; 2145 | if (isNaN(chr2)) { 2146 | enc3 = enc4 = 64; 2147 | } 2148 | else if (isNaN(chr3)) { 2149 | enc4 = 64; 2150 | } 2151 | output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); 2152 | } 2153 | return output.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); 2154 | }; 2155 | Utils.utf8Encode = function (input) { 2156 | input = input.replace(/\r\n/g, "\n"); 2157 | var utftext = ""; 2158 | for (var n = 0; n < input.length; n++) { 2159 | var c = input.charCodeAt(n); 2160 | if (c < 128) { 2161 | utftext += String.fromCharCode(c); 2162 | } 2163 | else if ((c > 127) && (c < 2048)) { 2164 | utftext += String.fromCharCode((c >> 6) | 192); 2165 | utftext += String.fromCharCode((c & 63) | 128); 2166 | } 2167 | else { 2168 | utftext += String.fromCharCode((c >> 12) | 224); 2169 | utftext += String.fromCharCode(((c >> 6) & 63) | 128); 2170 | utftext += String.fromCharCode((c & 63) | 128); 2171 | } 2172 | } 2173 | return utftext; 2174 | }; 2175 | Utils.decode = function (base64IdToken) { 2176 | var codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; 2177 | base64IdToken = String(base64IdToken).replace(/=+$/, ""); 2178 | var length = base64IdToken.length; 2179 | if (length % 4 === 1) { 2180 | throw new Error("The token to be decoded is not correctly encoded."); 2181 | } 2182 | var h1, h2, h3, h4, bits, c1, c2, c3, decoded = ""; 2183 | for (var i = 0; i < length; i += 4) { 2184 | h1 = codes.indexOf(base64IdToken.charAt(i)); 2185 | h2 = codes.indexOf(base64IdToken.charAt(i + 1)); 2186 | h3 = codes.indexOf(base64IdToken.charAt(i + 2)); 2187 | h4 = codes.indexOf(base64IdToken.charAt(i + 3)); 2188 | if (i + 2 === length - 1) { 2189 | bits = h1 << 18 | h2 << 12 | h3 << 6; 2190 | c1 = bits >> 16 & 255; 2191 | c2 = bits >> 8 & 255; 2192 | decoded += String.fromCharCode(c1, c2); 2193 | break; 2194 | } 2195 | else if (i + 1 === length - 1) { 2196 | bits = h1 << 18 | h2 << 12; 2197 | c1 = bits >> 16 & 255; 2198 | decoded += String.fromCharCode(c1); 2199 | break; 2200 | } 2201 | bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; 2202 | c1 = bits >> 16 & 255; 2203 | c2 = bits >> 8 & 255; 2204 | c3 = bits & 255; 2205 | decoded += String.fromCharCode(c1, c2, c3); 2206 | } 2207 | return decoded; 2208 | }; 2209 | ; 2210 | Utils.decodeJwt = function (jwtToken) { 2211 | if (this.isEmpty(jwtToken)) { 2212 | return null; 2213 | } 2214 | ; 2215 | var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; 2216 | var matches = idTokenPartsRegex.exec(jwtToken); 2217 | if (!matches || matches.length < 4) { 2218 | return null; 2219 | } 2220 | var crackedToken = { 2221 | header: matches[1], 2222 | JWSPayload: matches[2], 2223 | JWSSig: matches[3] 2224 | }; 2225 | return crackedToken; 2226 | }; 2227 | ; 2228 | Utils.deserialize = function (query) { 2229 | var match; 2230 | var pl = /\+/g; 2231 | var search = /([^&=]+)=([^&]*)/g; 2232 | var decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }; 2233 | var obj = {}; 2234 | match = search.exec(query); 2235 | while (match) { 2236 | obj[decode(match[1])] = decode(match[2]); 2237 | match = search.exec(query); 2238 | } 2239 | return obj; 2240 | }; 2241 | ; 2242 | Utils.isIntersectingScopes = function (cachedScopes, scopes) { 2243 | cachedScopes = this.convertToLowerCase(cachedScopes); 2244 | for (var i = 0; i < scopes.length; i++) { 2245 | if (cachedScopes.indexOf(scopes[i].toLowerCase()) > -1) 2246 | return true; 2247 | } 2248 | return false; 2249 | }; 2250 | Utils.containsScope = function (cachedScopes, scopes) { 2251 | cachedScopes = this.convertToLowerCase(cachedScopes); 2252 | return scopes.every(function (value) { return cachedScopes.indexOf(value.toString().toLowerCase()) >= 0; }); 2253 | }; 2254 | Utils.convertToLowerCase = function (scopes) { 2255 | return scopes.map(function (scope) { return scope.toLowerCase(); }); 2256 | }; 2257 | Utils.removeElement = function (scopes, scope) { 2258 | return scopes.filter(function (value) { return value !== scope; }); 2259 | }; 2260 | Utils.decimalToHex = function (num) { 2261 | var hex = num.toString(16); 2262 | while (hex.length < 2) { 2263 | hex = "0" + hex; 2264 | } 2265 | return hex; 2266 | }; 2267 | Utils.getLibraryVersion = function () { 2268 | return "0.1.1"; 2269 | }; 2270 | Utils.replaceFirstPath = function (href, tenantId) { 2271 | var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/); 2272 | if (match) { 2273 | var urlObject = Utils.GetUrlComponents(href); 2274 | var pathArray = urlObject.PathSegments; 2275 | pathArray.shift(); 2276 | if (pathArray[0] && pathArray[0] === 'common' || pathArray[0] === 'organizations') { 2277 | pathArray[0] = tenantId; 2278 | href = urlObject.Protocol + "//" + urlObject.HostNameAndPort + "/" + pathArray.join('/'); 2279 | } 2280 | } 2281 | return href; 2282 | }; 2283 | Utils.createNewGuid = function () { 2284 | var cryptoObj = window.crypto; 2285 | if (cryptoObj && cryptoObj.getRandomValues) { 2286 | var buffer = new Uint8Array(16); 2287 | cryptoObj.getRandomValues(buffer); 2288 | buffer[6] |= 0x40; 2289 | buffer[6] &= 0x4f; 2290 | buffer[8] |= 0x80; 2291 | buffer[8] &= 0xbf; 2292 | return Utils.decimalToHex(buffer[0]) + Utils.decimalToHex(buffer[1]) 2293 | + Utils.decimalToHex(buffer[2]) + Utils.decimalToHex(buffer[3]) 2294 | + "-" + Utils.decimalToHex(buffer[4]) + Utils.decimalToHex(buffer[5]) 2295 | + "-" + Utils.decimalToHex(buffer[6]) + Utils.decimalToHex(buffer[7]) 2296 | + "-" + Utils.decimalToHex(buffer[8]) + Utils.decimalToHex(buffer[9]) 2297 | + "-" + Utils.decimalToHex(buffer[10]) + Utils.decimalToHex(buffer[11]) 2298 | + Utils.decimalToHex(buffer[12]) + Utils.decimalToHex(buffer[13]) 2299 | + Utils.decimalToHex(buffer[14]) + Utils.decimalToHex(buffer[15]); 2300 | } 2301 | else { 2302 | var guidHolder = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"; 2303 | var hex = "0123456789abcdef"; 2304 | var r = 0; 2305 | var guidResponse = ""; 2306 | for (var i = 0; i < 36; i++) { 2307 | if (guidHolder[i] !== "-" && guidHolder[i] !== "4") { 2308 | r = Math.random() * 16 | 0; 2309 | } 2310 | if (guidHolder[i] === "x") { 2311 | guidResponse += hex[r]; 2312 | } 2313 | else if (guidHolder[i] === "y") { 2314 | r &= 0x3; 2315 | r |= 0x8; 2316 | guidResponse += hex[r]; 2317 | } 2318 | else { 2319 | guidResponse += guidHolder[i]; 2320 | } 2321 | } 2322 | return guidResponse; 2323 | } 2324 | }; 2325 | ; 2326 | Utils.GetUrlComponents = function (url) { 2327 | if (!url) { 2328 | throw "Url required"; 2329 | } 2330 | var regEx = new RegExp(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/); 2331 | var match = url.match(regEx); 2332 | if (!match || match.length < 6) { 2333 | throw "Valid url required"; 2334 | } 2335 | var urlComponents = { 2336 | Protocol: match[1], 2337 | HostNameAndPort: match[4], 2338 | AbsolutePath: match[5] 2339 | }; 2340 | var pathSegments = urlComponents.AbsolutePath.split("/"); 2341 | pathSegments = pathSegments.filter(function (val) { return val && val.length > 0; }); 2342 | urlComponents.PathSegments = pathSegments; 2343 | return urlComponents; 2344 | }; 2345 | Utils.CanonicalizeUri = function (url) { 2346 | if (url) { 2347 | url = url.toLowerCase(); 2348 | } 2349 | if (url && !Utils.endsWith(url, "/")) { 2350 | url += "/"; 2351 | } 2352 | return url; 2353 | }; 2354 | Utils.endsWith = function (url, suffix) { 2355 | if (!url || !suffix) { 2356 | return false; 2357 | } 2358 | return url.indexOf(suffix, url.length - suffix.length) !== -1; 2359 | }; 2360 | return Utils; 2361 | }()); 2362 | Msal.Utils = Utils; 2363 | })(Msal || (Msal = {})); 2364 | var Msal; 2365 | (function (Msal) { 2366 | var XhrClient = (function () { 2367 | function XhrClient() { 2368 | } 2369 | XhrClient.prototype.sendRequestAsync = function (url, method, enableCaching) { 2370 | var _this = this; 2371 | return new Promise(function (resolve, reject) { 2372 | var xhr = new XMLHttpRequest(); 2373 | xhr.open(method, url, true); 2374 | if (enableCaching) { 2375 | } 2376 | xhr.onload = function (ev) { 2377 | if (xhr.status < 200 || xhr.status >= 300) { 2378 | reject(_this.handleError(xhr.responseText)); 2379 | } 2380 | try { 2381 | var jsonResponse = JSON.parse(xhr.responseText); 2382 | } 2383 | catch (e) { 2384 | reject(_this.handleError(xhr.responseText)); 2385 | } 2386 | resolve(jsonResponse); 2387 | }; 2388 | xhr.onerror = function (ev) { 2389 | reject(xhr.status); 2390 | }; 2391 | if (method == 'GET') { 2392 | xhr.send(); 2393 | } 2394 | else { 2395 | throw "not implemented"; 2396 | } 2397 | }); 2398 | }; 2399 | XhrClient.prototype.handleError = function (responseText) { 2400 | var jsonResponse; 2401 | try { 2402 | jsonResponse = JSON.parse(responseText); 2403 | if (jsonResponse.error) { 2404 | return jsonResponse.error; 2405 | } 2406 | else 2407 | throw responseText; 2408 | } 2409 | catch (e) { 2410 | return responseText; 2411 | } 2412 | }; 2413 | return XhrClient; 2414 | }()); 2415 | Msal.XhrClient = XhrClient; 2416 | })(Msal || (Msal = {})); 2417 | //# sourceMappingURL=msal.js.map -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunilbandla/msal-angular-sample/e9b8f4324b661f9a19dba1d65139034d2355a4e5/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | MSAL.js + Angular 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule); 12 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/set'; 35 | 36 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 37 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 38 | 39 | /** IE10 and IE11 requires the following to support `@angular/animation`. */ 40 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 41 | 42 | 43 | /** Evergreen browsers require these. **/ 44 | import 'core-js/es6/reflect'; 45 | import 'core-js/es7/reflect'; 46 | 47 | 48 | /** ALL Firefox browsers require the following to support `@angular/animation`. **/ 49 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 50 | 51 | 52 | 53 | /*************************************************************************************************** 54 | * Zone JS is required by Angular itself. 55 | */ 56 | import 'zone.js/dist/zone'; // Included with Angular CLI. 57 | 58 | 59 | 60 | /*************************************************************************************************** 61 | * APPLICATION IMPORTS 62 | */ 63 | 64 | /** 65 | * Date, currency, decimal and percent pipes. 66 | * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 67 | */ 68 | // import 'intl'; // Run `npm install --save intl`. 69 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare var __karma__: any; 17 | declare var require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "es2015", 6 | "baseUrl": "", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "baseUrl": "", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts" 15 | ], 16 | "include": [ 17 | "**/*.spec.ts", 18 | "**/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "baseUrl": "src", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "moduleResolution": "node", 9 | "emitDecoratorMetadata": true, 10 | "experimentalDecorators": true, 11 | "target": "es5", 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "lib": [ 16 | "es2016", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "callable-types": true, 7 | "class-name": true, 8 | "comment-format": [ 9 | true, 10 | "check-space" 11 | ], 12 | "curly": true, 13 | "eofline": true, 14 | "forin": true, 15 | "import-blacklist": [true, "rxjs"], 16 | "import-spacing": true, 17 | "indent": [ 18 | true, 19 | "spaces" 20 | ], 21 | "interface-over-type-literal": true, 22 | "label-position": true, 23 | "max-line-length": [ 24 | true, 25 | 140 26 | ], 27 | "member-access": false, 28 | "member-ordering": [ 29 | true, 30 | "static-before-instance", 31 | "variables-before-functions" 32 | ], 33 | "no-arg": true, 34 | "no-bitwise": true, 35 | "no-console": [ 36 | true, 37 | "debug", 38 | "info", 39 | "time", 40 | "timeEnd", 41 | "trace" 42 | ], 43 | "no-construct": true, 44 | "no-debugger": true, 45 | "no-duplicate-variable": true, 46 | "no-empty": false, 47 | "no-empty-interface": true, 48 | "no-eval": true, 49 | "no-inferrable-types": [true, "ignore-params"], 50 | "no-shadowed-variable": true, 51 | "no-string-literal": false, 52 | "no-string-throw": true, 53 | "no-switch-case-fall-through": true, 54 | "no-trailing-whitespace": true, 55 | "no-unused-expression": true, 56 | "no-use-before-declare": true, 57 | "no-var-keyword": true, 58 | "object-literal-sort-keys": false, 59 | "one-line": [ 60 | true, 61 | "check-open-brace", 62 | "check-catch", 63 | "check-else", 64 | "check-whitespace" 65 | ], 66 | "prefer-const": true, 67 | "quotemark": [ 68 | true, 69 | "single" 70 | ], 71 | "radix": true, 72 | "semicolon": [ 73 | "always" 74 | ], 75 | "triple-equals": [ 76 | true, 77 | "allow-null-check" 78 | ], 79 | "typedef-whitespace": [ 80 | true, 81 | { 82 | "call-signature": "nospace", 83 | "index-signature": "nospace", 84 | "parameter": "nospace", 85 | "property-declaration": "nospace", 86 | "variable-declaration": "nospace" 87 | } 88 | ], 89 | "typeof-compare": true, 90 | "unified-signatures": true, 91 | "variable-name": false, 92 | "whitespace": [ 93 | true, 94 | "check-branch", 95 | "check-decl", 96 | "check-operator", 97 | "check-separator", 98 | "check-type" 99 | ], 100 | 101 | "directive-selector": [true, "attribute", "app", "camelCase"], 102 | "component-selector": [true, "element", "app", "kebab-case"], 103 | "use-input-property-decorator": true, 104 | "use-output-property-decorator": true, 105 | "use-host-property-decorator": true, 106 | "no-input-rename": true, 107 | "no-output-rename": true, 108 | "use-life-cycle-interface": true, 109 | "use-pipe-transform-interface": true, 110 | "component-class-suffix": true, 111 | "directive-class-suffix": true, 112 | "no-access-missing-member": true, 113 | "templates-use-public": true, 114 | "invoke-injectable": true 115 | } 116 | } 117 | --------------------------------------------------------------------------------