Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Proposed refactoring of API Plugin from Scratch with OAuth #13063

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,43 +1,60 @@
import { HttpRequest } from "@azure/functions";
import { TokenValidator } from "./tokenValidator";
import { TokenValidator, EntraJwtPayload } from "./tokenValidator";
import config from "./config";
import { getEntraJwksUri, CloudType } from "./utils";

// Export symbols app devs will need to use
export { CloudType } from "./utils";
export { EntraJwtPayload } from "./tokenValidator";

/**
* Middleware function to handle authorization using JWT.
*
* @param {HttpRequest} req - The HTTP request.
* @returns {Promise<boolean>} - A promise that resolves to a boolean value.
* @param {string | [string]} scope - The required scope(s) for the request.
* @param {string[]} allowedTenants - The allowed tenant IDs for the request.
* @param {CloudType} cloud - The Microsoft Entra cloud type.
* @param {string} issuer - The JWT issuer.
* @returns {Promise<EntraJwtPayload | false>} - A promise that resolves to an object containing JWT claims or false if authentication failed
*/
export async function authMiddleware(req?: HttpRequest): Promise<boolean> {
export async function authMiddleware(req: HttpRequest,
scope: string | [string],
allowedTenants: [string] = [config.aadAppTenantId],
cloud: CloudType = CloudType.Public,
issuer: string = `https://login.microsoftonline.com/${config.aadAppTenantId}/v2.0`
): Promise<EntraJwtPayload | false> {

// Get the token from the request headers
const token = req.headers.get("authorization")?.split(" ")[1];
if (!token) {
return false;
}

try {
// Get the JWKS URL for the Microsoft Entra common tenant
const entraJwksUri = await getEntraJwksUri(config.aadAppTenantId, CloudType.Public);
// Get the JWKS URL for the specified Microsoft Entra cloud
const entraJwksUri = await getEntraJwksUri(config.aadAppTenantId, cloud);

// Create a new token validator with the JWKS URL
const validator = new TokenValidator({
jwksUri: entraJwksUri,
});

const options = {
allowedTenants: [config.aadAppTenantId],
allowedTenants: allowedTenants,
audience: config.aadAppClientId,
issuer: `https://login.microsoftonline.com/${config.aadAppTenantId}/v2.0`,
scp: ["repairs_read"],
issuer: issuer,
scp: typeof scope === 'string' ? [scope] : scope
};
// Validate the token
await validator.validateToken(token, options);
const claims = await validator.validateToken(token, options);

return claims;

return true;
} catch (err) {

// Handle JWT verification errors
console.error("Token is invalid:", err);
return false;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export interface EntraJwtPayload extends JwtPayload {
roles?: string[];
scp?: string[];
ver?: string;
name?: string;
oid?: string;
preferred_username?: string;
tid?: string;
}

export class TokenValidator {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,15 @@ app.http("repairs", {
authLevel: "anonymous",
handler: async (req: HttpRequest, context: InvocationContext) => {
// Check if the request is authenticated
const isAuthenticated = await authMiddleware(req);
if (!isAuthenticated) {
const entraIdClaims = await authMiddleware(req, "repairs_read");
if (!entraIdClaims) {
return {
status: 401,
body: "Unauthorized",
};
}
console.log(`Authenticated ${req.method} request for ${entraIdClaims.name} (${entraIdClaims.oid})`);

// Call the actual handler function
return repairs(req, context);
},
Expand Down
Loading