Search code examples
node.jstypescriptnestjsgrpcgrpc-node

Using Auth0 with NestJS on gRPC Methods


I am trying to implement NestJS Guards for Authentication and Authorization to my gRPC Services, which are implemented in NestJS.

@GrpcMethod(USER_SERVICE_NAME, 'GetUser')
private getUser(req: GetUserRequest): Promise<GetUserResponse> {
    return this.userService.getUser(req);
}

By now I found out how to implement it for regular HTTP requests, following this tutorial. But as far as I can see this gets the JWT from a regular http request.

Now how can I apply that to gRPC requests. I also found this package, but here I am not sure how I would set the cache, rateLimit, and hash-algorithm options.


Solution

  • Now how can I apply that to gRPC requests. I also found this package, but here I am not sure how I would set the cache, rateLimit, and hash-algorithm options.

    In that package you linked to, you can see in the readme you are expected to implement your own IAuthService.

    They have provided an example in which they call the jwt.verify method using the token provided to the IAuthService through the params argument.

    The JWT token is extracted from the gRPC request's metadata as seen here.

    You can select the algorithm you want to use in the third options parameter of the jwt.verify function.

    // Extract taken from the package's readme.
    const options = {
      // For example...
      algorithms: ['HS256', 'HS384']
    };
    
    return new Promise(function (resolve, reject) {
      jwt.verify(token, getKey, options, (err, decoded) => {
        if (err) reject(err);
        resolve(decoded);
      });
    }).then((user) => user);
    

    Regarding cache I do not know exactly what you mean maybe the maxAge option on the jwt.verify function?

    maxAge: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span zeit/ms.

    Regarding rate limiting you can probably implement that on top of your Controller method using this example from the NestJS documentation.