1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | import { TokenCredential } from "@azure/identity";
|
9 |
|
10 | import { GraphClientError } from "../../GraphClientError";
|
11 | import { AuthenticationProvider } from "../../IAuthenticationProvider";
|
12 | import { TokenCredentialAuthenticationProviderOptions } from "./ITokenCredentialAuthenticationProviderOptions";
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | export class TokenCredentialAuthenticationProvider implements AuthenticationProvider {
|
26 | |
27 |
|
28 |
|
29 |
|
30 | private tokenCredential: TokenCredential;
|
31 |
|
32 | |
33 |
|
34 |
|
35 |
|
36 | private authenticationProviderOptions: TokenCredentialAuthenticationProviderOptions;
|
37 |
|
38 | |
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | public constructor(tokenCredential: TokenCredential, authenticationProviderOptions: TokenCredentialAuthenticationProviderOptions) {
|
47 | if (!tokenCredential) {
|
48 | throw new GraphClientError("Please pass a token credential object to the TokenCredentialAuthenticationProvider class constructor");
|
49 | }
|
50 | if (!authenticationProviderOptions) {
|
51 | throw new GraphClientError("Please pass the TokenCredentialAuthenticationProviderOptions with scopes to the TokenCredentialAuthenticationProvider class constructor");
|
52 | }
|
53 | this.authenticationProviderOptions = authenticationProviderOptions;
|
54 | this.tokenCredential = tokenCredential;
|
55 | }
|
56 |
|
57 | |
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 | public async getAccessToken(): Promise<string> {
|
65 | const scopes = this.authenticationProviderOptions.scopes;
|
66 | const error = new GraphClientError();
|
67 |
|
68 | if (!scopes || scopes.length === 0) {
|
69 | error.name = "Empty Scopes";
|
70 | error.message = "Scopes cannot be empty, Please provide scopes";
|
71 | throw error;
|
72 | }
|
73 | const response = await this.tokenCredential.getToken(scopes, this.authenticationProviderOptions.getTokenOptions);
|
74 | if (response) {
|
75 | return response.token;
|
76 | }
|
77 | error.message = "Cannot retrieve accessToken from the Token Credential object";
|
78 | error.name = "Access token is undefined";
|
79 | throw error;
|
80 | }
|
81 | }
|