Use AuthGuard with gRPC Metadata

The solution for “Use AuthGuard with gRPC Metadata” can be found here. The following code will assist you in solving the problem.

import {Injectable, CanActivate, ExecutionContext} from ‘@nestjs/common’;
import {Observable, throwError} from ‘rxjs’;
import {JwtService} from ‘@nestjs/jwt’;

@Injectable()
export class GrpcAuthGuard implements CanActivate {

constructor(private jwtService: JwtService) {

}

canActivate(context: ExecutionContext): boolean | Promise | Observable {
const type = context.getType();
const prefix = ‘Bearer ‘;
let header;
if(type===’rpc’) {
const metadata = context.getArgByIndex(1); // metadata
if (!metadata) {
return false;
}
header = metadata.get(‘Authorization’)[0];
}

if (!header || !header.includes(prefix)) {
return false;
}

const token = header.slice(header.indexOf(‘ ‘) + 1);
try {
const valid = this.jwtService.verify(token);
return true;
} catch (e) {
return false;
}
}
}

Thank you for using DeclareCode; We hope you were able to resolve the issue.

More questions on [categories-list]

0
inline scripts encapsulated in