/
communicationUserCredentialPolicy.ts
65 lines (60 loc) · 2.14 KB
/
communicationUserCredentialPolicy.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { CommunicationUserCredential } from "@azure/communication-common";
import {
Constants,
HttpOperationResponse,
WebResourceLike,
BaseRequestPolicy,
RequestPolicy,
RequestPolicyOptions,
RequestPolicyFactory
} from "@azure/core-http";
/**
* Creates a new CommunicationUserCredentialPolicy factory.
*
* @param credential The CommunicationUserCredential implementation that can supply the user credential.
*/
export const createCommunicationUserCredentialPolicy = (
credential: CommunicationUserCredential
): RequestPolicyFactory => ({
create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {
return new CommunicationUserCredentialPolicy(nextPolicy, options, credential);
}
});
/**
*
* Provides a RequestPolicy that can request a token from a CommunicationUserCredential
* implementation and then apply it to the Authorization header of a request.
*
* @internal
*/
export class CommunicationUserCredentialPolicy extends BaseRequestPolicy {
/**
* Creates a new CommunicationUserCredentialPolicy object.
*
* @param nextPolicy The next RequestPolicy in the request pipeline.
* @param options Options for this RequestPolicy.
* @param credential The CommunicationUserCredential implementation that can supply the user credential.
* @param tokenCache The cache for the most recent AccessToken returned from the CommunicationUserCredential.
*/
constructor(
nextPolicy: RequestPolicy,
options: RequestPolicyOptions,
private readonly credential: CommunicationUserCredential
) {
super(nextPolicy, options);
}
/**
* Applies the user credential to the request through the Authorization header.
* @param webResource
*/
public async sendRequest(webResource: WebResourceLike): Promise<HttpOperationResponse> {
if (!webResource) {
throw new Error("webResource cannot be null or undefined");
}
const token = (await this.credential.getToken())?.token;
webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`);
return this._nextPolicy.sendRequest(webResource);
}
}