Skip to content

Commit

Permalink
Proposed refactoring of API Plugin from Scratch with OAuth to separat…
Browse files Browse the repository at this point in the history
…e middleware from app
  • Loading branch information
BobGerman committed Jan 16, 2025
1 parent 3b8dd69 commit 9104bfd
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,43 +1,56 @@
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.
* @returns {Promise<EntraJwtPayload | false>} - A promise that resolves to an array of 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 @@ -6,7 +6,7 @@
import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";

import repairRecords from "../repairsData.json";
import { authMiddleware } from "./middleware/authMiddleware";
import { authMiddleware, EntraJwtPayload } from "./middleware/authMiddleware";

Check notice

Code scanning / CodeQL

Unused variable, import, function or class Note

Unused import EntraJwtPayload.

/**
* This function handles the HTTP request and returns the repair information.
Expand Down 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

0 comments on commit 9104bfd

Please sign in to comment.