-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
bearerTokenAuthenticationPolicy.ts
221 lines (204 loc) · 7.45 KB
/
bearerTokenAuthenticationPolicy.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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import type { AccessToken, GetTokenOptions, TokenCredential } from "@azure/core-auth";
import type { AzureLogger } from "@azure/logger";
import type { PipelineRequest, PipelineResponse, SendRequest } from "../interfaces.js";
import type { PipelinePolicy } from "../pipeline.js";
import { createTokenCycler } from "../util/tokenCycler.js";
import { logger as coreLogger } from "../log.js";
/**
* The programmatic identifier of the bearerTokenAuthenticationPolicy.
*/
export const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
/**
* Options sent to the authorizeRequest callback
*/
export interface AuthorizeRequestOptions {
/**
* The scopes for which the bearer token applies.
*/
scopes: string[];
/**
* Function that retrieves either a cached access token or a new access token.
*/
getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise<AccessToken | null>;
/**
* Request that the policy is trying to fulfill.
*/
request: PipelineRequest;
/**
* A logger, if one was sent through the HTTP pipeline.
*/
logger?: AzureLogger;
}
/**
* Options sent to the authorizeRequestOnChallenge callback
*/
export interface AuthorizeRequestOnChallengeOptions {
/**
* The scopes for which the bearer token applies.
*/
scopes: string[];
/**
* Function that retrieves either a cached access token or a new access token.
*/
getAccessToken: (scopes: string[], options: GetTokenOptions) => Promise<AccessToken | null>;
/**
* Request that the policy is trying to fulfill.
*/
request: PipelineRequest;
/**
* Response containing the challenge.
*/
response: PipelineResponse;
/**
* A logger, if one was sent through the HTTP pipeline.
*/
logger?: AzureLogger;
}
/**
* Options to override the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.
*/
export interface ChallengeCallbacks {
/**
* Allows for the authorization of the main request of this policy before it's sent.
*/
authorizeRequest?(options: AuthorizeRequestOptions): Promise<void>;
/**
* Allows to handle authentication challenges and to re-authorize the request.
* The response containing the challenge is `options.response`.
* If this method returns true, the underlying request will be sent once again.
* The request may be modified before being sent.
*/
authorizeRequestOnChallenge?(options: AuthorizeRequestOnChallengeOptions): Promise<boolean>;
}
/**
* Options to configure the bearerTokenAuthenticationPolicy
*/
export interface BearerTokenAuthenticationPolicyOptions {
/**
* The TokenCredential implementation that can supply the bearer token.
*/
credential?: TokenCredential;
/**
* The scopes for which the bearer token applies.
*/
scopes: string | string[];
/**
* Allows for the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.
* If provided, it must contain at least the `authorizeRequestOnChallenge` method.
* If provided, after a request is sent, if it has a challenge, it can be processed to re-send the original request with the relevant challenge information.
*/
challengeCallbacks?: ChallengeCallbacks;
/**
* A logger can be sent for debugging purposes.
*/
logger?: AzureLogger;
}
/**
* Default authorize request handler
*/
async function defaultAuthorizeRequest(options: AuthorizeRequestOptions): Promise<void> {
const { scopes, getAccessToken, request } = options;
const getTokenOptions: GetTokenOptions = {
abortSignal: request.abortSignal,
tracingOptions: request.tracingOptions,
};
const accessToken = await getAccessToken(scopes, getTokenOptions);
if (accessToken) {
options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
}
}
/**
* We will retrieve the challenge only if the response status code was 401,
* and if the response contained the header "WWW-Authenticate" with a non-empty value.
*/
function getChallenge(response: PipelineResponse): string | undefined {
const challenge = response.headers.get("WWW-Authenticate");
if (response.status === 401 && challenge) {
return challenge;
}
return;
}
/**
* A policy that can request a token from a TokenCredential implementation and
* then apply it to the Authorization header of a request as a Bearer token.
*/
export function bearerTokenAuthenticationPolicy(
options: BearerTokenAuthenticationPolicyOptions,
): PipelinePolicy {
const { credential, scopes, challengeCallbacks } = options;
const logger = options.logger || coreLogger;
const callbacks = {
authorizeRequest: challengeCallbacks?.authorizeRequest ?? defaultAuthorizeRequest,
authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge,
// keep all other properties
...challengeCallbacks,
};
// This function encapsulates the entire process of reliably retrieving the token
// The options are left out of the public API until there's demand to configure this.
// Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
// in order to pass through the `options` object.
const getAccessToken = credential
? createTokenCycler(credential /* , options */)
: () => Promise.resolve(null);
return {
name: bearerTokenAuthenticationPolicyName,
/**
* If there's no challenge parameter:
* - It will try to retrieve the token using the cache, or the credential's getToken.
* - Then it will try the next policy with or without the retrieved token.
*
* It uses the challenge parameters to:
* - Skip a first attempt to get the token from the credential if there's no cached token,
* since it expects the token to be retrievable only after the challenge.
* - Prepare the outgoing request if the `prepareRequest` method has been provided.
* - Send an initial request to receive the challenge if it fails.
* - Process a challenge if the response contains it.
* - Retrieve a token with the challenge information, then re-send the request.
*/
async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {
if (!request.url.toLowerCase().startsWith("https://")) {
throw new Error(
"Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.",
);
}
await callbacks.authorizeRequest({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
getAccessToken,
logger,
});
let response: PipelineResponse;
let error: Error | undefined;
try {
response = await next(request);
} catch (err: any) {
error = err;
response = err.response;
}
if (
callbacks.authorizeRequestOnChallenge &&
response?.status === 401 &&
getChallenge(response)
) {
// processes challenge
const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
response,
getAccessToken,
logger,
});
if (shouldSendRequest) {
return next(request);
}
}
if (error) {
throw error;
} else {
return response;
}
},
};
}