-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathAuthProvider.js
245 lines (206 loc) · 9.05 KB
/
AuthProvider.js
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
const msal = require('@azure/msal-node');
const axios = require('axios');
const { getClaims } = require('../utils/claimUtils');
const {
GRAPH_ME_ENDPOINT,
SESSION_COOKIE_NAME,
STATE_COOKIE_NAME
} = require('../authConfig');
class AuthProvider {
config;
cryptoProvider;
constructor(config) {
this.config = config;
this.cryptoProvider = new msal.CryptoProvider();
}
getMsalInstance() {
return new msal.ConfidentialClientApplication(this.config.msalConfig);
}
async login(req, res, next, options = {}) {
/**
* MSAL Node allows you to pass your custom state as state parameter in the Request object.
* The state parameter can also be used to encode information of the app's state before redirect.
* You can pass the user's state in the app, such as the page or view they were on, as input to this parameter.
*/
const state = this.cryptoProvider.base64Encode(
JSON.stringify({
csrfToken: this.cryptoProvider.createNewGuid(), // create a GUID for csrf
redirectTo: options.postLoginRedirectUri ? options.postLoginRedirectUri : '/',
})
);
const authCodeUrlRequestParams = {
state: state,
/**
* By default, MSAL Node will add OIDC scopes to the auth code url request. For more information, visit:
* https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
*/
scopes: options.scopesToConsent ? options.scopesToConsent.split(' ') : [],
claims: getClaims(req.session, this.config.msalConfig.auth.clientId, GRAPH_ME_ENDPOINT),
};
const authCodeRequestParams = {
state: state,
/**
* By default, MSAL Node will add OIDC scopes to the auth code request. For more information, visit:
* https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
*/
scopes: options.scopesToConsent ? options.scopesToConsent.split(' ') : [],
claims: getClaims(req.session, this.config.msalConfig.auth.clientId, GRAPH_ME_ENDPOINT),
};
/**
* If the current msal configuration does not have cloudDiscoveryMetadata or authorityMetadata, we will
* make a request to the relevant endpoints to retrieve the metadata. This allows MSAL to avoid making
* metadata discovery calls, thereby improving performance of token acquisition process.
*/
if (!this.config.msalConfig.auth.cloudDiscoveryMetadata || !this.config.msalConfig.auth.authorityMetadata) {
const [cloudDiscoveryMetadata, authorityMetadata] = await Promise.all([
this.getCloudDiscoveryMetadata(),
this.getAuthorityMetadata()
]);
this.config.msalConfig.auth.cloudDiscoveryMetadata = JSON.stringify(cloudDiscoveryMetadata);
this.config.msalConfig.auth.authorityMetadata = JSON.stringify(authorityMetadata);
}
const msalInstance = this.getMsalInstance();
return this.redirectToAuthCodeUrl(
req,
res,
next,
authCodeUrlRequestParams,
authCodeRequestParams,
msalInstance
);
}
async redirectToAuthCodeUrl(req, res, next, authCodeUrlRequestParams, authCodeRequestParams, msalInstance) {
const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes();
const authCodeUrlRequest = {
redirectUri: this.config.redirectUri,
responseMode: msal.ResponseMode.FORM_POST, // recommended for confidential clients
codeChallenge: challenge,
codeChallengeMethod: 'S256',
...authCodeUrlRequestParams,
};
const cookiePayload = {
pkceCodes: {
verifier: verifier,
},
authCodeRequest: {
redirectUri: this.config.redirectUri,
...authCodeRequestParams,
}
};
try {
const authCodeUrlResponse = await msalInstance.getAuthCodeUrl(authCodeUrlRequest);
/**
* Web apps using OIDC form_post flow for authentication rely on cross-domain
* cookies for security. Here we designate the cookie with sameSite=none to ensure we can retrieve
* state after redirect from the Azure AD takes place. For more information, visit:
* https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-handle-samesite-cookie-changes-chrome-browser
*/
res.cookie(STATE_COOKIE_NAME, cookiePayload, { httpOnly: true, secure: true, sameSite: 'none' });
res.redirect(authCodeUrlResponse);
} catch (error) {
next(error)
}
}
async handleRedirect(req, res, next) {
const authCodeRequest = {
...req.cookies[STATE_COOKIE_NAME].authCodeRequest,
codeVerifier: req.cookies[STATE_COOKIE_NAME].pkceCodes.verifier,
code: req.body.code,
}
try {
const msalInstance = this.getMsalInstance();
const tokenResponse = await msalInstance.acquireTokenByCode(authCodeRequest, req.body);
req.session.tokenCache = msalInstance.getTokenCache().serialize();
req.session.accessToken = tokenResponse.accessToken;
req.session.idToken = tokenResponse.idToken;
req.session.account = tokenResponse.account;
req.session.isAuthenticated = true;
const { redirectTo } = JSON.parse(this.cryptoProvider.base64Decode(req.body.state));
res.clearCookie(STATE_COOKIE_NAME, { httpOnly: true, secure: true, sameSite: 'none'}); // discard the state cookie
res.redirect(redirectTo);
} catch (error) {
next(error)
}
}
async logout(req, res, next) {
/**
* Construct a logout URI and redirect the user to end the
* session with Azure AD. For more information, visit:
* https://docs.microsoft.com/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request
*/
const logoutUri = `${this.config.msalConfig.auth.authority}/oauth2/v2.0/logout?post_logout_redirect_uri=${this.config.postLogoutRedirectUri}`;
req.session.destroy(() => {
res.clearCookie(SESSION_COOKIE_NAME);
res.redirect(logoutUri);
});
}
async acquireToken(req, res, next, options = {}) {
const msalInstance = this.getMsalInstance();
try {
msalInstance.getTokenCache().deserialize(req.session.tokenCache);
const tokenResponse = await msalInstance.acquireTokenSilent({
account: req.session.account,
scopes: options.scopes || [],
claims: getClaims(req.session, this.config.msalConfig.auth.clientId, GRAPH_ME_ENDPOINT),
});
req.session.tokenCache = msalInstance.getTokenCache().serialize();
req.session.accessToken = tokenResponse.accessToken;
req.session.idToken = tokenResponse.idToken;
req.session.account = tokenResponse.account;
return tokenResponse;
} catch (error) {
if (error instanceof msal.InteractionRequiredAuthError) {
const err = new Error('InteractionRequiredAuthError occurred for given scopes');
err.payload = options.scopes.join(' ');
err.name = 'InteractionRequiredAuthError';
throw err;
} else {
throw error;
}
}
}
isAuthenticated(req, res, next) {
if (req.session && req.session.isAuthenticated) {
return true;
}
return false;
}
getAccount(req, res, next) {
if (this.isAuthenticated(req, res, next)) {
return req.session.account
}
return null;
}
/**
* Retrieves cloud discovery metadata from the /discovery/instance endpoint
* @returns
*/
async getCloudDiscoveryMetadata() {
const endpoint = 'https://login.microsoftonline.com/common/discovery/instance';
try {
const response = await axios.get(endpoint, {
params: {
'api-version': '1.1',
'authorization_endpoint': `${this.config.msalConfig.auth.authority}/oauth2/v2.0/authorize`
}
});
return await response.data;
} catch (error) {
throw error;
}
}
/**
* Retrieves oidc metadata from the openid endpoint
* @returns
*/
async getAuthorityMetadata() {
const endpoint = `${this.config.msalConfig.auth.authority}/v2.0/.well-known/openid-configuration`;
try {
const response = await axios.get(endpoint);
return await response.data;
} catch (error) {
throw error;
}
}
}
module.exports = AuthProvider;