Skip to content

Commit a9f16e5

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

File tree

2 files changed

+163
-0
lines changed

2 files changed

+163
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
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 { FetchHeadersInit, FetchRequestInit } from "../utils/fetchDefinitions";
14+
import { getRequestHeader } from "../utils/headersUtil";
15+
import { BaseBearerTokenAuthenticationProvider, Headers, RequestInformation } 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.headers)) {
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 requestInformation = new RequestInformation();
53+
requestInformation.URL = url;
54+
requestInformation.headers = new Headers();
55+
if (fetchRequestInit.headers !== undefined) {
56+
const headers = fetchRequestInit.headers as Record<string, string>;
57+
for (const key of Object.keys(headers)) {
58+
const value = headers[key];
59+
requestInformation.headers.add(key, value);
60+
}
61+
}
62+
63+
await this.authenticateRequest(requestInformation);
64+
65+
const response = await this.next?.execute(url, fetchRequestInit as RequestInit, requestOptions);
66+
if (!response) {
67+
throw new Error("Response is undefined");
68+
}
69+
if (response.status !== 401) {
70+
return response;
71+
}
72+
const claims = this.getClaimsFromResponse(response);
73+
if (!claims) {
74+
return response;
75+
}
76+
span?.addEvent("com.microsoft.kiota.handler.authorization.challenge_received");
77+
await this.authenticateRequest(requestInformation, claims);
78+
span?.setAttribute("http.request.resend_count", 1);
79+
return response;
80+
}
81+
82+
private authorizationIsPresent(header: FetchHeadersInit | undefined): boolean {
83+
if (!header) {
84+
return false;
85+
}
86+
const authorizationHeader = getRequestHeader(header, AuthorizationHandler.AUTHORIZATION_HEADER);
87+
return authorizationHeader !== undefined && authorizationHeader !== null;
88+
}
89+
90+
private async authenticateRequest(request: RequestInformation, claims?: string): Promise<void> {
91+
const additionalAuthenticationContext = {} as Record<string, unknown>;
92+
if (claims) {
93+
additionalAuthenticationContext.claims = claims;
94+
}
95+
await this.authenticationProvider.authenticateRequest(request, additionalAuthenticationContext);
96+
}
97+
98+
private readonly getClaimsFromResponse = (response: Response, claims?: string) => {
99+
if (response.status === 401 && !claims) {
100+
// avoid infinite loop, we only retry once
101+
// no need to check for the content since it's an array and it doesn't need to be rewound
102+
const rawAuthenticateHeader = response.headers.get("WWW-Authenticate");
103+
if (rawAuthenticateHeader && /^Bearer /gi.test(rawAuthenticateHeader)) {
104+
const rawParameters = rawAuthenticateHeader.replace(/^Bearer /gi, "").split(",");
105+
for (const rawParameter of rawParameters) {
106+
const trimmedParameter = rawParameter.trim();
107+
if (/claims="[^"]+"/gi.test(trimmedParameter)) {
108+
return trimmedParameter.replace(/claims="([^"]+)"/gi, "$1");
109+
}
110+
}
111+
}
112+
}
113+
return undefined;
114+
};
115+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { describe, expect, it } from "vitest";
2+
import { CompressionHandler, CompressionHandlerOptions } from "../../../src";
3+
import { AuthorizationHandler } from "../../../src/middlewares/authorizationHandler";
4+
import { DummyFetchHandler } from "./dummyFetchHandler";
5+
import { AccessTokenProvider, AllowedHostsValidator, BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions/src";
6+
7+
describe("AuthorizationHandler", () => {
8+
let authorizationHandler: AuthorizationHandler;
9+
let nextMiddleware: DummyFetchHandler;
10+
11+
it("should not add a header if authorization header exists", async () => {
12+
const url = "https://example.com";
13+
const validator = new AllowedHostsValidator();
14+
const tokenProvider: AccessTokenProvider = {
15+
getAuthorizationToken: async () => "New Token",
16+
getAllowedHostsValidator: () => validator,
17+
};
18+
const provider = new BaseBearerTokenAuthenticationProvider(tokenProvider);
19+
authorizationHandler = new AuthorizationHandler(provider);
20+
21+
const requestInit = {
22+
headers: {
23+
Authorization: "Bearer Existing Token",
24+
},
25+
};
26+
27+
await authorizationHandler.execute(url, requestInit);
28+
29+
expect((requestInit.headers as Record<string, string>)["Authorization"]).toBe("Bearer Existing Token");
30+
});
31+
32+
it("should attempt to authenticate when the header does not exist", async () => {
33+
const url = "https://example.com";
34+
const validator = new AllowedHostsValidator();
35+
const tokenProvider: AccessTokenProvider = {
36+
getAuthorizationToken: async () => "New Token",
37+
getAllowedHostsValidator: () => validator,
38+
};
39+
const provider = new BaseBearerTokenAuthenticationProvider(tokenProvider);
40+
authorizationHandler = new AuthorizationHandler(provider);
41+
42+
const requestInit = { headers: {} };
43+
44+
await authorizationHandler.execute(url, requestInit);
45+
46+
expect((requestInit.headers as Record<string, string>)["Authorization"]).toBe("Bearer New Token");
47+
});
48+
});

0 commit comments

Comments
 (0)