/
interactiveBrowserCredential.browser.ts
170 lines (156 loc) · 5.88 KB
/
interactiveBrowserCredential.browser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import * as msal from "msal";
import { AccessToken, TokenCredential, GetTokenOptions } from "@azure/core-http";
import { IdentityClient } from "../client/identityClient";
import {
BrowserLoginStyle,
InteractiveBrowserCredentialOptions
} from "./interactiveBrowserCredentialOptions";
import { createSpan } from "../util/tracing";
import { CanonicalCode } from "@opentelemetry/types";
import { DefaultTenantId, DeveloperSignOnClientId } from "../constants";
import { logger } from "../util/logging";
/**
* Enables authentication to Azure Active Directory inside of the web browser
* using the interactive login flow, either via browser redirects or a popup
* window.
*/
export class InteractiveBrowserCredential implements TokenCredential {
private loginStyle: BrowserLoginStyle;
private msalConfig: msal.Configuration;
private msalObject: msal.UserAgentApplication;
/**
* Creates an instance of the InteractiveBrowserCredential with the
* details needed to authenticate against Azure Active Directory with
* a user identity.
*
* @param tenantId The Azure Active Directory tenant (directory) ID.
* @param clientId The client (application) ID of an App Registration in the tenant.
* @param options Options for configuring the client which makes the authentication request.
*/
constructor(options?: InteractiveBrowserCredentialOptions) {
options = {
...IdentityClient.getDefaultOptions(),
...options,
tenantId: (options && options.tenantId) || DefaultTenantId,
// TODO: temporary - this is the Azure CLI clientID - we'll replace it when
// Developer Sign On application is available
// https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/identity/Azure.Identity/src/Constants.cs#L9
clientId: (options && options.clientId) || DeveloperSignOnClientId
};
this.loginStyle = options.loginStyle || "popup";
if (["redirect", "popup"].indexOf(this.loginStyle) === -1) {
throw new Error(`Invalid loginStyle: ${options.loginStyle}`);
}
this.msalConfig = {
auth: {
clientId: options.clientId!, // we just initialized it above
authority: `${options.authorityHost}/${options.tenantId}`,
...(options.redirectUri && { redirectUri: options.redirectUri }),
...(options.postLogoutRedirectUri && { redirectUri: options.postLogoutRedirectUri })
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
this.msalObject = new msal.UserAgentApplication(this.msalConfig);
}
private login(): Promise<msal.AuthResponse> {
switch (this.loginStyle) {
case "redirect": {
const loginPromise = new Promise<msal.AuthResponse>((resolve, reject) => {
this.msalObject.handleRedirectCallback(resolve, reject);
});
this.msalObject.loginRedirect();
return loginPromise;
}
case "popup":
return this.msalObject.loginPopup();
}
}
private async acquireToken(
authParams: msal.AuthenticationParameters
): Promise<msal.AuthResponse | undefined> {
let authResponse: msal.AuthResponse | undefined;
try {
logger.info("InteractiveBrowserCredential: attempting to acquire token silently");
authResponse = await this.msalObject.acquireTokenSilent(authParams);
} catch (err) {
if (err instanceof msal.AuthError) {
switch (err.errorCode) {
case "consent_required":
case "interaction_required":
case "login_required":
logger.warning(
`InteractiveBrowserCredential: authentication returned errorCode ${err.errorCode}`
);
break;
default:
logger.warning(`InteractiveBrowserCredential: failed to acquire token: ${err}`);
throw err;
}
}
}
let authPromise: Promise<msal.AuthResponse> | undefined;
if (authResponse === undefined) {
logger.warning(
`InteractiveBrowserCredential: silent authentication failed, falling back to interactive method ${this.loginStyle}`
);
switch (this.loginStyle) {
case "redirect":
authPromise = new Promise((resolve, reject) => {
this.msalObject.handleRedirectCallback(resolve, reject);
});
this.msalObject.acquireTokenRedirect(authParams);
break;
case "popup":
authPromise = this.msalObject.acquireTokenPopup(authParams);
break;
}
authResponse = authPromise && (await authPromise);
}
return authResponse;
}
/**
* Authenticates with Azure Active Directory and returns an access token if
* successful. If authentication cannot be performed at this time, this method may
* return null. If an error occurs during authentication, an {@link AuthenticationError}
* containing failure details will be thrown.
*
* @param scopes The list of scopes for which the token will have access.
* @param options The options used to configure any requests this
* TokenCredential implementation might make.
*/
async getToken(
scopes: string | string[],
options?: GetTokenOptions
): Promise<AccessToken | null> {
const { span } = createSpan("InteractiveBrowserCredential-getToken", options);
try {
if (!this.msalObject.getAccount()) {
await this.login();
}
const authResponse = await this.acquireToken({
scopes: Array.isArray(scopes) ? scopes : scopes.split(",")
});
if (authResponse) {
return {
token: authResponse.accessToken,
expiresOnTimestamp: authResponse.expiresOn.getTime()
};
} else {
return null;
}
} catch (err) {
span.setStatus({
code: CanonicalCode.UNKNOWN,
message: err.message
});
throw err;
} finally {
span.end();
}
}
}