admin管理员组

文章数量:1122832

I'm creating a Nestjs REST/GraphQL API. I have a global Auth Guard for JWT and API Key and a decorator that sets metadata on a method in order to skip the global Auth. This works perfectly for the REST endpoint, but I can't seem to set or access the metadata for the GraphQL resolver method.

This endpoint is for creating an API Key. The idea is that I disable the Auth Guard that extends the API Key and JWT auth and add just the JWT Auth Guard. The AuthMetaData decorator is supposed to set the auth metadata key to ${JwtOrApiKeyAuthGuard.name}Skip.

/// jwt-apiKey-auth.guard.ts
import { ContextType, ExecutionContext, Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { GqlExecutionContext } from '@nestjs/graphql'
import { AuthGuard } from '@nestjs/passport'

import { AUTH_METADATA_KEY } from '../decorators/auth-metadata.decorator'

@Injectable()
export class JwtOrApiKeyAuthGuard extends AuthGuard(['api-key', 'jwt']) {
  constructor(private readonly reflector: Reflector) {
    super()
  }

  getContext(
    context: ExecutionContext,
  ): ExecutionContext | GqlExecutionContext {
    if (context.getType<ContextType | 'graphql'>() === 'graphql') {
      return GqlExecutionContext.create(context)
    } else {
      return context
    }
  }

  getRequest(context: ExecutionContext) {
    if (context.getType<ContextType | 'graphql'>() === 'graphql') {
      return GqlExecutionContext.create(context).getContext().req
    } else {
      return context.switchToHttp().getRequest()
    }
  }

  canActivate(context: ExecutionContext) {
    const ctx: ExecutionContext | GqlExecutionContext = this.getContext(context)

    const authMetadata = this.reflector.getAllAndOverride<string | string[]>(
      AUTH_METADATA_KEY,
      [ctx.getHandler(), ctx.getClass()],
    )

    if (
      authMetadata &&
      authMetadata.includes(`${JwtOrApiKeyAuthGuard.name}Skip`)
    ) {
      return true
    }

    return super.canActivate(ctx)
  }
}

/// auth-metadata.decorator.ts
import { applyDecorators, SetMetadata } from '@nestjs/common'
import { Extensions } from '@nestjs/graphql'

export const AUTH_METADATA_KEY = 'auth'
export const AuthMetaData = (...metadata: string[]) =>
  applyDecorators(
    SetMetadata(AUTH_METADATA_KEY, metadata),
    Extensions({ [AUTH_METADATA_KEY]: metadata.join(',') }),
  )
/// api-key.resolver.ts
  @UseGuards(JwtAuthGuard)
  @AuthMetaData(`${JwtOrApiKeyAuthGuard.name}Skip`)
  @Mutation(() => CreateApiKeyResponseDto, {
    name: 'createApiKey',
    description: 'Create an API Key',
  })
  async create(
    @GetUser() user,
    @Args('data') createApiKeyDto: CreateApiKeyDto,
  ): Promise<CreateApiKeyResponseDto> {
    if (createApiKeyDto.userId !== user.id && user.role !== UserRole.ADMIN) {
      throw new ForbiddenException(
        'You are not allowed to create an API Key for another user',
      )
    }
    return this.apiKeyService.create(createApiKeyDto)
  }

I had previously just the SetMetadata method in the AuthMetaData decorator, but based on the documentation I believe I need the Extensions call as well.

The metadata keeps coming back as undefined.

本文标签: Nestjs GraphQL access Resolver method metadataStack Overflow