@@ -8,11 +8,10 @@ import * as JsonWebToken from "jsonwebtoken";
88import { JwtHeader } from "jsonwebtoken" ;
99import jwksClient from "jwks-rsa" ;
1010import * as process from "process" ;
11- import { Reflector } from "@nestjs/core " ;
11+ import { Request } from "express " ;
1212
1313/**
14- * Jwt based auth guard. Checks for valid JWT token which is signed by another service/microservice.
15- * Should be used for microservice communication.
14+ * Jwt based auth guard. Can be used for microservice-microservice communication, or for websockets.
1615 */
1716@Injectable ( )
1817export class JwtAuthGuard implements CanActivate {
@@ -22,8 +21,6 @@ export class JwtAuthGuard implements CanActivate {
2221 jwksUri : this . JWKS_URI ,
2322 } ) ;
2423
25- constructor ( private readonly reflector : Reflector ) { }
26-
2724 /**
2825 * @param jwtHeader - JWT header, from the decoded token
2926 * @private
@@ -39,35 +36,24 @@ export class JwtAuthGuard implements CanActivate {
3936 }
4037 }
4138
42- /**
43- * This same logic should be applied to all services/microservices.
44- * @param context
45- */
4639 async canActivate ( context : ExecutionContext ) : Promise < boolean > {
47- const ctx = context . switchToHttp ( ) ;
48- const ctxType = context . getType < "http" | "rmq" > ( ) ;
40+ const ctxType = context . getType < "http" | "ws" | "rpc" > ( ) ;
4941
5042 if ( ctxType !== "http" ) {
51- this . logger . warn (
52- `Warning: JwtAuthGuard can't be used in a non-HTTP context! ` ,
43+ throw new Error (
44+ `JwtAuthGuard not configured for context: ${ ctxType } ` ,
5345 ) ;
54-
55- return true ;
5646 }
5747
58- const isPublic = this . reflector . get < boolean > (
59- "isPublic" ,
60- context . getHandler ( ) ,
61- ) ;
48+ const request : Request = context . switchToHttp ( ) . getRequest ( ) ;
6249
63- if ( isPublic ) {
64- return true ;
65- }
50+ return this . validateToken ( request . headers . authorization ) ;
51+ }
52+
53+ private async validateToken ( token : string | undefined ) {
54+ const bearerToken = token ?. split ( "Bearer " ) [ 1 ] ;
6655
67- const headers = ctx . getRequest ( ) . headers ;
68- const authorization = headers . authorization as string ;
69- const bearerToken = authorization ?. split ( "Bearer " ) [ 1 ] ;
70- if ( ! authorization || ! bearerToken ) {
56+ if ( ! token || ! bearerToken ) {
7157 return false ;
7258 }
7359
0 commit comments