1
- import type { Context , MiddlewareHandler } from ' hono' ;
2
- import type { GeneralKeyValueStore , VerificationResult } from '.' ;
3
- import { getJwks , useKVStore , verify } from '.' ;
1
+ import type { Context , MiddlewareHandler } from " hono" ;
2
+ import type { GeneralKeyValueStore , VerificationResult } from "." ;
3
+ import { getJwks , useKVStore , verify } from "." ;
4
4
5
5
export type VerifyRsaJwtConfig = {
6
6
jwksUri ?: string ;
@@ -10,25 +10,24 @@ export type VerifyRsaJwtConfig = {
10
10
optional ?: boolean ;
11
11
} ;
12
12
13
- const PAYLOAD_KEY = ' verifyRsaJwtPayload' ;
13
+ const PAYLOAD_KEY = " verifyRsaJwtPayload" ;
14
14
15
15
export function verifyRsaJwt ( config ?: VerifyRsaJwtConfig ) : MiddlewareHandler {
16
16
return async ( ctx : Context , next ) => {
17
- const jwtToken = ctx . req . headers
18
- . get ( 'Authorization' )
19
- ?. replace ( / B e a r e r \s + / i, '' ) ;
20
- if ( ! jwtToken || jwtToken . length === 0 ) {
21
- return new Response ( 'Bad Request' , { status : 400 } ) ;
22
- }
23
17
try {
18
+ const jwtToken = ctx . req . headers . get ( "Authorization" ) ?. replace ( / B e a r e r \s + / i, "" ) ;
19
+ if ( ! jwtToken || jwtToken . length === 0 ) {
20
+ throw new Error ( "JWT token not found in Authorization header" ) ;
21
+ }
22
+
24
23
const jwks = await getJwks (
25
24
config ?. jwksUri || ctx . env . JWKS_URI ,
26
25
useKVStore ( config ?. kvStore || ctx . env ?. VERIFY_RSA_JWT ) ,
27
- ctx . env ?. VERIFY_RSA_JWT_JWKS_CACHE_KEY ,
26
+ ctx . env ?. VERIFY_RSA_JWT_JWKS_CACHE_KEY
28
27
) ;
29
28
const result = await verify ( jwtToken , jwks ) ;
30
29
if ( result . payload === null ) {
31
- throw new Error ( ' Invalid token' ) ;
30
+ throw new Error ( " Invalid token" ) ;
32
31
}
33
32
34
33
// Custom validator that should throw an error if the payload is invalid.
@@ -38,8 +37,7 @@ export function verifyRsaJwt(config?: VerifyRsaJwtConfig): MiddlewareHandler {
38
37
ctx . set ( PAYLOAD_KEY , result . payload ) ;
39
38
await next ( ) ;
40
39
} catch ( error ) {
41
- config ?. verbose &&
42
- console . error ( { message : 'verification failed' , error } ) ;
40
+ config ?. verbose && console . error ( { message : "verification failed" , error } ) ;
43
41
44
42
if ( config ?. optional ) {
45
43
await next ( ) ;
0 commit comments