NestJS/GraphQL/Passport - 从警卫处获取未经授权的错误

Ell*_*e G 10 passport-local graphql nestjs nestjs-passport

我正在尝试按照本教程进行操作,并且正在努力将实现转换为 GraphQL。

本地策略.ts

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authenticationService: AuthenticationService) {
    super();
  }

  async validate(email: string, password: string): Promise<any> {
    const user = await this.authenticationService.getAuthenticatedUser(
      email,
      password,
    );

    if (!user) throw new UnauthorizedException();

    return user;
  }
}
Run Code Online (Sandbox Code Playgroud)

本地警卫.ts

@Injectable()
export class LogInWithCredentialsGuard extends AuthGuard('local') {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const ctx = GqlExecutionContext.create(context);
    const { req } = ctx.getContext();
    req.body = ctx.getArgs();

    await super.canActivate(new ExecutionContextHost([req]));
    await super.logIn(req);
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

身份验证.type.ts

@InputType()
export class AuthenticationInput {
  @Field()
  email: string;

  @Field()
  password: string;
}
Run Code Online (Sandbox Code Playgroud)

身份验证.resolver.ts

@UseGuards(LogInWithCredentialsGuard)
@Mutation(() => User, { nullable: true })
logIn(
  @Args('variables')
  _authenticationInput: AuthenticationInput,
  @Context() req: any,
) {
  return req.user;
}
Run Code Online (Sandbox Code Playgroud)

突变

mutation {
  logIn(variables: {
    email: "email@email.com",
    password: "123123"
  } ) {
    id
    email
  }
}
Run Code Online (Sandbox Code Playgroud)

即使上述凭据正确,我仍收到未经授权的错误。

Moh*_*jad 10

问题出在你的LogInWithCredentialsGuard.

您不应该覆盖canAcitavte方法,您所要做的就是使用正确的 GraphQL 参数更新请求,因为在 API 请求的情况下,Passport 会自动从req.body. 使用 GraphQL,执行上下文是不同的,因此您必须在req.body. 为此,getRequest需要使用方法。

由于 GraphQL 和 REST API 的执行上下文不同,您必须确保您的防护在这两种情况下都能工作,无论是控制器还是突变。

这是一个工作代码片段

@Injectable()
export class LogInWithCredentialsGuard extends AuthGuard('local') {
  // Override this method so it can be used in graphql
  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    const gqlReq = ctx.getContext().req;
    if (gqlReq) {
      const { variables } = ctx.getArgs();
      gqlReq.body = variables;
      return gqlReq;
    }
    return context.switchToHttp().getRequest();
  }
}
Run Code Online (Sandbox Code Playgroud)

你的突变会像

@UseGuards(LogInWithCredentialsGuard)
@Mutation(() => User, { nullable: true })
logIn(
  @Args('variables')
  _authenticationInput: AuthenticationInput,
  @Context() context: any, // <----------- it's not request
) {
  return context.req.user;
}
Run Code Online (Sandbox Code Playgroud)