|
1 | 1 | import { Request, Response, NextFunction } from 'express'; |
2 | | -import OktaJwtVerifier from '@okta/jwt-verifier'; |
3 | | - |
4 | | -export interface AuthMiddlewareConfig { |
5 | | - oktaIssuer: string; |
6 | | - oktaClientId: string; |
7 | | - expectedAudience: string; |
8 | | -} |
9 | | - |
10 | | -export function createRequireAuth(config: AuthMiddlewareConfig) { |
11 | | - const { oktaIssuer, oktaClientId, expectedAudience } = config; |
12 | | - |
13 | | - console.log('🔐 Auth Middleware Configuration:'); |
14 | | - console.log(` Issuer: ${oktaIssuer}`); |
15 | | - console.log(` Client ID: ${oktaClientId}`); |
16 | | - console.log(` Expected Audience: ${expectedAudience}`); |
17 | | - |
18 | | - const oktaJwtVerifier = new OktaJwtVerifier({ |
19 | | - issuer: oktaIssuer, |
20 | | - clientId: oktaClientId, |
21 | | - assertClaims: { |
22 | | - aud: expectedAudience, |
23 | | - }, |
24 | | - }); |
25 | 2 |
|
| 3 | +export function createRequireAuth() { |
26 | 4 | return async function requireAuth(req: Request, res: Response, next: NextFunction) { |
27 | | - // 1. Check for session-based authentication |
28 | | - if (req.session && (req.session as any).access_token) { |
29 | | - console.log('✓ Session-based authentication found'); |
30 | | - return next(); |
31 | | - } |
32 | | - |
33 | | - // 2. Check for Bearer token authentication |
34 | | - const authHeader = req.headers.authorization || ''; |
35 | | - const match = authHeader.match(/^Bearer (.+)$/); |
36 | | - if (!match) { |
37 | | - console.log('✗ No Bearer token found in Authorization header'); |
38 | | - return res.status(401).json({ error: 'Missing or invalid Authorization header or session' }); |
39 | | - } |
40 | | - |
41 | | - const accessToken = match[1]; |
42 | | - console.log('🔍 Verifying access token...'); |
43 | | - |
44 | | - try { |
45 | | - // Verify the access token |
46 | | - const jwt = await oktaJwtVerifier.verifyAccessToken(accessToken, expectedAudience); |
47 | | - |
48 | | - console.log('✅ Token verified successfully'); |
49 | | - console.log(' Subject:', jwt.claims.sub); |
50 | | - console.log(' Scopes:', jwt.claims.scp); |
51 | | - console.log(' Client ID:', jwt.claims.cid); |
52 | | - |
53 | | - (req as any).user = jwt.claims; |
54 | | - return next(); |
55 | | - } catch (err: any) { |
56 | | - console.error('❌ Token verification failed:', err.message); |
57 | | - return res.status(401).json({ |
58 | | - error: 'Invalid or expired token', |
59 | | - details: err.message |
60 | | - }); |
61 | | - } |
| 5 | + // 1. Check for session-based authentication |
| 6 | + if (req.session && (req.session as any).access_token) { |
| 7 | + console.log('✓ Session-based authentication found'); |
| 8 | + return next(); |
| 9 | + } else { |
| 10 | + return res.status(401).json({ error: 'Missing or invalid session' }); |
| 11 | + } |
62 | 12 | }; |
63 | 13 | } |
64 | 14 |
|
|
0 commit comments