How to get token claims on NestJS Passport?

Viewed 540

I'm building my back-end using NestJS using JWT for authentication. On routes that required the token to be authenticated, is there a way for me to decode the token and get all the property of it?

On my token I have a property that I need to verify on a method, how can I do that?

I'm using NestJS Passport AuthGuard as argument on @UseGuard().

1 Answers

You can implement your Guard to check permissions for your token using this code

permissions.guard.ts

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';


@Injectable()
export class PermissionsGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const routePermissions = this.reflector.get<string[]>(
      'permissions',
      context.getHandler(),
    );

    const userPermissions = context.getArgs()[0].user.scope.split(" ") ?? [];

    if (!routePermissions) {
      return true;
    }

    const hasPermission = () =>
      routePermissions.every(routePermission =>
        userPermissions.includes(routePermission),
      );

    return hasPermission();
  }
}

permissions.decorator.ts

import { SetMetadata } from '@nestjs/common';

export const Permissions = (...args: string[]) => SetMetadata('permissions', args);

and finally you have to insert the guard and the permission inside the controller.

@ApiTags('Product')
@ApiOAuth2([])
@Controller('catalog')
@UseGuards(AuthGuard('jwt'), PermissionsGuard)
@Permissions('products3:view')
export class ApiCatalogController {
constructor(private productSv: ApiCatalogService) {}

@Get("properties/:name")
@Permissions("read:properties")
async getCatalogProperties() {}

When you request for the oauth token using the implicit flow, you have to use include "read:properties" inside the scope, unless you will receive an 403 error. The oauth server will give you the token only if you have the permissions and return you the jwt token with the requested scopes.

Hope to solve your problem

Related