Skip to content

Commit f199ecf

Browse files
abdulkareemnalbandAbdulKareem Nalband
andauthored
Update azure ad token caching (Huachao#795)
* include scopes in cache key different network request may need token with different scopes , so include scopes in cache key * include original requested scopes also in cache scope Sometime token is missing requested scopes. When next request is sent with same scope application is asking for re authentication. Including original scopes in saved scopes fixes that Co-authored-by: AbdulKareem Nalband <abdulkareem.nalband@decisions.no>
1 parent 0ea5e3e commit f199ecf

1 file changed

Lines changed: 40 additions & 34 deletions

File tree

‎src/utils/aadV2TokenProvider.ts‎

Lines changed: 40 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ export class AadV2TokenProvider {
4242
}
4343
}
4444

45-
private async getDeviceCodeResponse(authParams: AuthParameters) : Promise<IDeviceCodeResponse> {
45+
private async getDeviceCodeResponse(authParams: AuthParameters): Promise<IDeviceCodeResponse> {
4646
const request = this.createUserCodeRequest(authParams.clientId, authParams.tenantId, authParams.scopes);
4747
const response = await this._httpClient.send(request);
4848

@@ -61,7 +61,7 @@ export class AadV2TokenProvider {
6161
return bodyObject as IDeviceCodeResponse;
6262
}
6363

64-
private async getToken(deviceCodeResponse: IDeviceCodeResponse, authParams: AuthParameters) : Promise<string> {
64+
private async getToken(deviceCodeResponse: IDeviceCodeResponse, authParams: AuthParameters): Promise<string> {
6565
const request = this.createAcquireTokenRequest(authParams.clientId, authParams.tenantId, deviceCodeResponse.device_code);
6666
const response = await this._httpClient.send(request);
6767

@@ -71,7 +71,13 @@ export class AadV2TokenProvider {
7171
this.processAuthErrorAndThrow(bodyObject);
7272
}
7373
const tokenResponse: ITokenResponse = bodyObject;
74-
AadV2TokenCache.setToken(authParams.getCacheKey(), tokenResponse.scope.split(' '), tokenResponse.access_token);
74+
const tokenScopes = tokenResponse.scope.split(' ');
75+
for (const scope of authParams.scopes) {
76+
if (!tokenScopes.includes(scope)) {
77+
tokenScopes.push(scope);
78+
}
79+
}
80+
AadV2TokenCache.setToken(authParams.getCacheKey(), tokenScopes, tokenResponse.access_token);
7581

7682
return tokenResponse.access_token;
7783
}
@@ -86,7 +92,7 @@ export class AadV2TokenProvider {
8692
this.processAuthErrorAndThrow(bodyObject);
8793
}
8894
const tokenResponse: ITokenResponse = bodyObject;
89-
const scopes : string[] = []; // Confidential Client tokens are limited to scopes defined in the app registration portal
95+
const scopes: string[] = []; // Confidential Client tokens are limited to scopes defined in the app registration portal
9096
AadV2TokenCache.setToken(authParams.getCacheKey(), scopes, tokenResponse.access_token);
9197
return tokenResponse.access_token;
9298
}
@@ -96,26 +102,26 @@ export class AadV2TokenProvider {
96102
throw new Error("Auth call failed. " + errorResponse.error_description);
97103
}
98104

99-
private createUserCodeRequest(clientId: string, tenantId: string, scopes: string[]) : HttpRequest {
105+
private createUserCodeRequest(clientId: string, tenantId: string, scopes: string[]): HttpRequest {
100106
return new HttpRequest(
101107
"POST", `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/devicecode`,
102108
{ "Content-Type": "application/x-www-form-urlencoded" },
103-
`client_id=${clientId}&scope=${scopes.join("%20")}`);
109+
`client_id=${clientId}&scope=${scopes.join("%20")}`);
104110
}
105111

106-
private createAcquireTokenRequest(clientId: string, tenantId: string, deviceCode: string) : HttpRequest {
112+
private createAcquireTokenRequest(clientId: string, tenantId: string, deviceCode: string): HttpRequest {
107113
return new HttpRequest("POST", `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
108-
{ "Content-Type": "application/x-www-form-urlencoded" },
109-
`grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=${clientId}&device_code=${deviceCode}`);
114+
{ "Content-Type": "application/x-www-form-urlencoded" },
115+
`grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=${clientId}&device_code=${deviceCode}`);
110116
}
111117

112-
private createAcquireConfidentialClientTokenRequest(clientId: string, tenantId: string, clientSecret: string, appUri: string) : HttpRequest {
118+
private createAcquireConfidentialClientTokenRequest(clientId: string, tenantId: string, clientSecret: string, appUri: string): HttpRequest {
113119
return new HttpRequest("POST", `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
114-
{ "Content-Type": "application/x-www-form-urlencoded" },
115-
`grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}&scope=${appUri}/.default`);
120+
{ "Content-Type": "application/x-www-form-urlencoded" },
121+
`grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}&scope=${appUri}/.default`);
116122
}
117123

118-
private async promptForUserCode(deviceCodeResponse: IDeviceCodeResponse) : Promise<boolean> {
124+
private async promptForUserCode(deviceCodeResponse: IDeviceCodeResponse): Promise<boolean> {
119125

120126
const messageBoxOptions = { modal: true };
121127
const signInPrompt = `Sign in to Azure AD with the following code (will be copied to the clipboard) to add a token to your request.\r\n\r\nCode: ${deviceCodeResponse.user_code}`;
@@ -159,7 +165,7 @@ class AuthParameters {
159165
this.appOnly = false;
160166
}
161167

162-
async readEnvironmentVariable(variableName: string) : Promise<string | undefined> {
168+
async readEnvironmentVariable(variableName: string): Promise<string | undefined> {
163169
if (await EnvironmentVariableProvider.Instance.has(variableName)) {
164170
const { value, error, warning } = await EnvironmentVariableProvider.Instance.get(variableName);
165171
if (!warning && !error) {
@@ -171,8 +177,8 @@ class AuthParameters {
171177
return undefined;
172178
}
173179

174-
getCacheKey() : string {
175-
return this.tenantId + "|" + this.clientId + "|" + this.appOnly as string;
180+
getCacheKey(): string {
181+
return this.tenantId + "|" + this.clientId + "|" + this.appOnly + "|" + this.scopes.join(',') as string;
176182
}
177183

178184
static async parseName(name: string): Promise<AuthParameters> {
@@ -218,7 +224,7 @@ class AuthParameters {
218224
}
219225
}
220226

221-
class AadV2TokenCache {
227+
class AadV2TokenCache {
222228

223229
private static tokens: Map<string, AadV2TokenCacheEntry> = new Map<string, AadV2TokenCacheEntry>();
224230

@@ -229,28 +235,28 @@ class AuthParameters {
229235
this.tokens.set(cacheKey, entry);
230236
}
231237

232-
public static getToken(cacheKey: string) : AadV2TokenCacheEntry | undefined {
238+
public static getToken(cacheKey: string): AadV2TokenCacheEntry | undefined {
233239
return this.tokens.get(cacheKey);
234240
}
235241
}
236242

237-
class AadV2TokenCacheEntry {
238-
public token: string;
239-
public scopes: string[];
240-
public supportScopes(scopes: string[]) : boolean {
243+
class AadV2TokenCacheEntry {
244+
public token: string;
245+
public scopes: string[];
246+
public supportScopes(scopes: string[]): boolean {
241247
return scopes.every((scope) => this.scopes.includes(scope));
242-
}
243-
}
244-
245-
interface IAuthError {
246-
error: string;
247-
error_description: string;
248-
error_uri: string;
249-
error_codes: number[];
250-
timestamp: string;
251-
trace_id: string;
252-
correlation_id: string;
253-
}
248+
}
249+
}
250+
251+
interface IAuthError {
252+
error: string;
253+
error_description: string;
254+
error_uri: string;
255+
error_codes: number[];
256+
timestamp: string;
257+
trace_id: string;
258+
correlation_id: string;
259+
}
254260

255261
interface IDeviceCodeResponse {
256262
user_code: string;

0 commit comments

Comments
 (0)