|
1 | 1 | import { HttpRequest } from "@azure/functions";
|
2 |
| -import { TokenValidator } from "./tokenValidator"; |
| 2 | +import { TokenValidator, EntraJwtPayload } from "./tokenValidator"; |
3 | 3 | import config from "./config";
|
4 | 4 | import { getEntraJwksUri, CloudType } from "./utils";
|
5 | 5 |
|
| 6 | +// Export symbols app devs will need to use |
| 7 | +export { CloudType } from "./utils"; |
| 8 | +export { EntraJwtPayload } from "./tokenValidator"; |
| 9 | + |
6 | 10 | /**
|
7 | 11 | * Middleware function to handle authorization using JWT.
|
8 | 12 | *
|
9 | 13 | * @param {HttpRequest} req - The HTTP request.
|
10 |
| - * @returns {Promise<boolean>} - A promise that resolves to a boolean value. |
| 14 | + * @returns {Promise<EntraJwtPayload | false>} - A promise that resolves to an array of JWT claims or false if authentication failed |
11 | 15 | */
|
12 |
| -export async function authMiddleware(req?: HttpRequest): Promise<boolean> { |
| 16 | +export async function authMiddleware(req: HttpRequest, |
| 17 | + scope: string | [string], |
| 18 | + allowedTenants: [string] = [config.aadAppTenantId], |
| 19 | + cloud: CloudType = CloudType.Public, |
| 20 | + issuer: string = `https://login.microsoftonline.com/${config.aadAppTenantId}/v2.0` |
| 21 | + ): Promise<EntraJwtPayload | false> { |
| 22 | + |
13 | 23 | // Get the token from the request headers
|
14 | 24 | const token = req.headers.get("authorization")?.split(" ")[1];
|
15 | 25 | if (!token) {
|
16 | 26 | return false;
|
17 | 27 | }
|
18 | 28 |
|
19 | 29 | try {
|
20 |
| - // Get the JWKS URL for the Microsoft Entra common tenant |
21 |
| - const entraJwksUri = await getEntraJwksUri(config.aadAppTenantId, CloudType.Public); |
| 30 | + // Get the JWKS URL for the specified Microsoft Entra cloud |
| 31 | + const entraJwksUri = await getEntraJwksUri(config.aadAppTenantId, cloud); |
22 | 32 |
|
23 | 33 | // Create a new token validator with the JWKS URL
|
24 | 34 | const validator = new TokenValidator({
|
25 | 35 | jwksUri: entraJwksUri,
|
26 | 36 | });
|
27 | 37 |
|
28 | 38 | const options = {
|
29 |
| - allowedTenants: [config.aadAppTenantId], |
| 39 | + allowedTenants: allowedTenants, |
30 | 40 | audience: config.aadAppClientId,
|
31 |
| - issuer: `https://login.microsoftonline.com/${config.aadAppTenantId}/v2.0`, |
32 |
| - scp: ["repairs_read"], |
| 41 | + issuer: issuer, |
| 42 | + scp: typeof scope === 'string' ? [scope] : scope |
33 | 43 | };
|
34 | 44 | // Validate the token
|
35 |
| - await validator.validateToken(token, options); |
| 45 | + const claims = await validator.validateToken(token, options); |
| 46 | + |
| 47 | + return claims; |
36 | 48 |
|
37 |
| - return true; |
38 | 49 | } catch (err) {
|
| 50 | + |
39 | 51 | // Handle JWT verification errors
|
40 | 52 | console.error("Token is invalid:", err);
|
41 | 53 | return false;
|
| 54 | + |
42 | 55 | }
|
43 | 56 | }
|
0 commit comments