-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
interactiveBrowserCredential.ts
186 lines (162 loc) · 6.13 KB
/
interactiveBrowserCredential.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/* eslint-disable @typescript-eslint/no-unused-vars */
import { TokenCredential, GetTokenOptions, AccessToken } from "@azure/core-http";
import { InteractiveBrowserCredentialOptions } from "./interactiveBrowserCredentialOptions";
import { credentialLogger, formatError, formatSuccess } from "../util/logging";
import { DefaultTenantId, DeveloperSignOnClientId } from "../constants";
import { Socket } from "net";
import { AuthenticationRequired, MsalClient } from "../client/msalClient";
import { AuthorizationCodeRequest } from "@azure/msal-node";
import express from "express";
import open from "open";
import http from "http";
import { checkTenantId } from "../util/checkTenantId";
const logger = credentialLogger("InteractiveBrowserCredential");
/**
* Enables authentication to Azure Active Directory inside of the web browser
* using the interactive login flow, either via browser redirects or a popup
* window. This credential is not currently supported in Node.js.
*/
export class InteractiveBrowserCredential implements TokenCredential {
private redirectUri: string;
private port: number;
private msalClient: MsalClient;
constructor(options?: InteractiveBrowserCredentialOptions) {
const tenantId = (options && options.tenantId) || DefaultTenantId;
const clientId = (options && options.clientId) || DeveloperSignOnClientId;
checkTenantId(logger, tenantId);
// const persistenceEnabled = options?.persistenceEnabled ? options?.persistenceEnabled : false;
// const authenticationRecord = options?.authenticationRecord;
if (options && options.redirectUri) {
if (typeof options.redirectUri === "string") {
this.redirectUri = options.redirectUri;
} else {
this.redirectUri = options.redirectUri();
}
} else {
this.redirectUri = "http://localhost";
}
const url = new URL(this.redirectUri);
this.port = parseInt(url.port);
if (isNaN(this.port)) {
this.port = 80;
}
let authorityHost;
if (options && options.authorityHost) {
if (options.authorityHost.endsWith("/")) {
authorityHost = options.authorityHost + tenantId;
} else {
authorityHost = options.authorityHost + "/" + tenantId;
}
} else {
authorityHost = "https://login.microsoftonline.com/" + tenantId;
}
this.msalClient = new MsalClient(
{
clientId,
authority: authorityHost,
knownAuthorities: tenantId === "adfs" ? (authorityHost ? [authorityHost] : []) : []
},
false,
undefined,
options
);
}
/**
* 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.
*/
public getToken(
scopes: string | string[],
_options?: GetTokenOptions
): Promise<AccessToken | null> {
const scopeArray = typeof scopes === "object" ? scopes : [scopes];
return this.msalClient.acquireTokenFromCache(scopeArray).catch((e) => {
if (e instanceof AuthenticationRequired) {
return this.acquireTokenFromBrowser(scopeArray);
} else {
logger.getToken.info(formatError(scopes, e));
throw e;
}
});
}
private async openAuthCodeUrl(scopeArray: string[]): Promise<void> {
const authCodeUrlParameters = {
scopes: scopeArray,
redirectUri: this.redirectUri
};
const response = await this.msalClient.getAuthCodeUrl(authCodeUrlParameters);
await open(response);
}
private async acquireTokenFromBrowser(scopeArray: string[]): Promise<AccessToken | null> {
// eslint-disable-next-line
return new Promise<AccessToken | null>(async (resolve, reject) => {
// eslint-disable-next-line
let listen: http.Server | undefined;
let socketToDestroy: Socket | undefined;
function cleanup(): void {
if (listen) {
listen.close();
}
if (socketToDestroy) {
socketToDestroy.destroy();
}
}
// Create Express App and Routes
const app = express();
app.get("/", async (req, res) => {
const tokenRequest: AuthorizationCodeRequest = {
code: req.query.code as string,
redirectUri: this.redirectUri,
scopes: scopeArray
};
try {
const authResponse = await this.msalClient.acquireTokenByCode(tokenRequest);
const successMessage = `Authentication Complete. You can close the browser and return to the application.`;
if (authResponse && authResponse.expiresOn) {
const expiresOnTimestamp = authResponse?.expiresOn.valueOf();
res.status(200).send(successMessage);
logger.getToken.info(formatSuccess(scopeArray));
resolve({
expiresOnTimestamp,
token: authResponse.accessToken
});
} else {
reject(
new Error(
`Interactive Browser Authentication Error "Did not receive token with a valid expiration"`
)
);
}
} catch (error) {
const errorMessage = formatError(
scopeArray,
`${req.query["error"]}. ${req.query["error_description"]}`
);
res.status(500).send(errorMessage);
logger.getToken.info(errorMessage);
reject(new Error(errorMessage));
} finally {
cleanup();
}
});
listen = app.listen(this.port, () =>
logger.info(`Msal Node Auth Code Sample app listening on port ${this.port}!`)
);
listen.on("connection", (socket) => (socketToDestroy = socket));
try {
await this.openAuthCodeUrl(scopeArray);
} catch (e) {
cleanup();
throw e;
}
});
}
}