Skip to content

Commit dcb369c

Browse files
committed
feat: adds authorization handler
1 parent 3868a28 commit dcb369c

File tree

3 files changed

+158
-1
lines changed

3 files changed

+158
-1
lines changed

packages/abstractions/src/authentication/baseBearerTokenAuthenticationProvider.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export class BaseBearerTokenAuthenticationProvider implements AuthenticationProv
2626
request.headers.delete(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey);
2727
}
2828
if (!request.headers?.has(BaseBearerTokenAuthenticationProvider.authorizationHeaderKey)) {
29-
const token = await this.accessTokenProvider.getAuthorizationToken(request.URL, additionalAuthenticationContext);
29+
const token = await this.getAccessToken(request.URL, additionalAuthenticationContext);
3030
if (!request.headers) {
3131
request.headers = new Headers();
3232
}
@@ -35,4 +35,8 @@ export class BaseBearerTokenAuthenticationProvider implements AuthenticationProv
3535
}
3636
}
3737
};
38+
39+
public getAccessToken = async (url?: string, additionalAuthenticationContext?: Record<string, unknown>): Promise<string> => {
40+
return await this.accessTokenProvider.getAuthorizationToken(url, additionalAuthenticationContext);
41+
};
3842
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/**
2+
* -------------------------------------------------------------------------------------------
3+
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
4+
* See License in the project root for license information.
5+
* -------------------------------------------------------------------------------------------
6+
*/
7+
8+
import { type RequestOption } from "@microsoft/kiota-abstractions";
9+
import { Span, trace } from "@opentelemetry/api";
10+
11+
import { getObservabilityOptionsFromRequest } from "../observabilityOptions";
12+
import type { Middleware } from "./middleware";
13+
import type { FetchRequestInit } from "../utils/fetchDefinitions";
14+
import { getRequestHeader, setRequestHeader } from "../utils/headersUtil";
15+
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions/src";
16+
17+
export class AuthorizationHandler implements Middleware {
18+
next: Middleware | undefined;
19+
20+
/**
21+
* A member holding the name of content range header
22+
*/
23+
private static readonly AUTHORIZATION_HEADER = "Authorization";
24+
25+
public constructor(private readonly authenticationProvider: BaseBearerTokenAuthenticationProvider) {
26+
if (!authenticationProvider) {
27+
throw new Error("authenticationProvider cannot be undefined");
28+
}
29+
}
30+
31+
public execute(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response> {
32+
const obsOptions = getObservabilityOptionsFromRequest(requestOptions);
33+
if (obsOptions) {
34+
return trace.getTracer(obsOptions.getTracerInstrumentationName()).startActiveSpan("authorizationHandler - execute", (span) => {
35+
try {
36+
span.setAttribute("com.microsoft.kiota.handler.authorization.enable", true);
37+
return this.executeInternal(url, requestInit as FetchRequestInit, requestOptions, span);
38+
} finally {
39+
span.end();
40+
}
41+
});
42+
}
43+
return this.executeInternal(url, requestInit as FetchRequestInit, requestOptions, undefined);
44+
}
45+
46+
private async executeInternal(url: string, fetchRequestInit: FetchRequestInit, requestOptions?: Record<string, RequestOption>, span?: Span): Promise<Response> {
47+
if (this.authorizationIsPresent(fetchRequestInit)) {
48+
span?.setAttribute("com.microsoft.kiota.handler.authorization.token_present", true);
49+
return await this.next!.execute(url, fetchRequestInit as RequestInit, requestOptions);
50+
}
51+
52+
const token = await this.authenticateRequest(url);
53+
setRequestHeader(fetchRequestInit, AuthorizationHandler.AUTHORIZATION_HEADER, `Bearer ${token}`);
54+
const response = await this.next?.execute(url, fetchRequestInit as RequestInit, requestOptions);
55+
if (!response) {
56+
throw new Error("Response is undefined");
57+
}
58+
if (response.status !== 401) {
59+
return response;
60+
}
61+
const claims = this.getClaimsFromResponse(response);
62+
if (!claims) {
63+
return response;
64+
}
65+
span?.addEvent("com.microsoft.kiota.handler.authorization.challenge_received");
66+
const claimsToken = await this.authenticateRequest(url, claims);
67+
setRequestHeader(fetchRequestInit, AuthorizationHandler.AUTHORIZATION_HEADER, `Bearer ${claimsToken}`);
68+
span?.setAttribute("http.request.resend_count", 1);
69+
const retryResponse = await this.next?.execute(url, fetchRequestInit as RequestInit, requestOptions);
70+
if (!retryResponse) {
71+
throw new Error("Response is undefined");
72+
}
73+
return retryResponse;
74+
}
75+
76+
private authorizationIsPresent(request: FetchRequestInit | undefined): boolean {
77+
if (!request) {
78+
return false;
79+
}
80+
const authorizationHeader = getRequestHeader(request, AuthorizationHandler.AUTHORIZATION_HEADER);
81+
return authorizationHeader !== undefined && authorizationHeader !== null;
82+
}
83+
84+
private async authenticateRequest(url: string, claims?: string): Promise<string> {
85+
const additionalAuthenticationContext = {} as Record<string, unknown>;
86+
if (claims) {
87+
additionalAuthenticationContext.claims = claims;
88+
}
89+
return await this.authenticationProvider.getAccessToken(url, additionalAuthenticationContext);
90+
}
91+
92+
private readonly getClaimsFromResponse = (response: Response, claims?: string) => {
93+
if (response.status === 401 && !claims) {
94+
// avoid infinite loop, we only retry once
95+
// no need to check for the content since it's an array and it doesn't need to be rewound
96+
const rawAuthenticateHeader = response.headers.get("WWW-Authenticate");
97+
if (rawAuthenticateHeader && /^Bearer /gi.test(rawAuthenticateHeader)) {
98+
const rawParameters = rawAuthenticateHeader.replace(/^Bearer /gi, "").split(",");
99+
for (const rawParameter of rawParameters) {
100+
const trimmedParameter = rawParameter.trim();
101+
if (/claims="[^"]+"/gi.test(trimmedParameter)) {
102+
return trimmedParameter.replace(/claims="([^"]+)"/gi, "$1");
103+
}
104+
}
105+
}
106+
}
107+
return undefined;
108+
};
109+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { beforeEach, describe, expect, it } from "vitest";
2+
import { AuthorizationHandler } from "../../../src/middlewares/authorizationHandler";
3+
import { DummyFetchHandler } from "./dummyFetchHandler";
4+
import { AccessTokenProvider, AllowedHostsValidator } from "@microsoft/kiota-abstractions/src";
5+
6+
describe("AuthorizationHandler", () => {
7+
let authorizationHandler: AuthorizationHandler;
8+
let nextMiddleware: DummyFetchHandler;
9+
10+
beforeEach(() => {
11+
nextMiddleware = new DummyFetchHandler();
12+
const validator = new AllowedHostsValidator();
13+
const tokenProvider: AccessTokenProvider = {
14+
getAuthorizationToken: async () => "New Token",
15+
getAllowedHostsValidator: () => validator,
16+
};
17+
authorizationHandler = new AuthorizationHandler(tokenProvider);
18+
authorizationHandler.next = nextMiddleware;
19+
});
20+
21+
it("should not add a header if authorization header exists", async () => {
22+
const url = "https://example.com";
23+
const requestInit = {
24+
headers: {
25+
Authorization: "Bearer Existing Token",
26+
},
27+
};
28+
nextMiddleware.setResponses([new Response("ok", { status: 200 })]);
29+
30+
await authorizationHandler.execute(url, requestInit);
31+
32+
expect((requestInit.headers as Record<string, string>)["Authorization"]).toBe("Bearer Existing Token");
33+
});
34+
35+
it("should attempt to authenticate when the header does not exist", async () => {
36+
const url = "https://example.com";
37+
const requestInit = { headers: {} };
38+
nextMiddleware.setResponses([new Response("ok", { status: 200 })]);
39+
40+
await authorizationHandler.execute(url, requestInit);
41+
42+
expect((requestInit.headers as Record<string, string>)["Authorization"]).toBe("Bearer New Token");
43+
});
44+
});

0 commit comments

Comments
 (0)