Reputation: 533
I am looking for a way to authorize an rpc via NestJS grpc microservices. Basically I want to attach a token in the grpc client, which has to be validated by the grpc server. I found this issue, but I did not get where exactly grpc.Metadata
pass as a second argument.
Upvotes: 2
Views: 5851
Reputation: 533
I found a way to solve this. For sure not the most elegant solution, but it works for now. A simplified example:
// gRPC client
@Get(':id')
async call(@Param() params) {
const metadata = new grpc.Metadata();
// add relevant data to the metadata object (e.g from request header)
metadata.add('role', 'admin');
return this.userService.findOne({ id: +params.id}, metadata);
}
// Service
interface UserService {
findOne(data: {id: number}, metadata: grpc.Metadata): Observable<any>;
}
// gRPC server
@GrpcMethod('UserService', 'FindOne')
async findOne(data: UserById, metadata: grpc.Metadata) {
const meta = metadata.getMap();
// do something with the metadata...
console.log(meta.role);
const items: User= [
{ id: 1, name: 'User 1' },
{ id: 2, name: 'User 2' },
{ id: 3, name: 'User 3' },
];
return items.find(({ id }) => id === data.id);
}
Upvotes: 3