我目前正在使用Passport.js将JWT身份验证实现到NestJS应用程序中。
在我的一些GraphQL解析器中,我需要访问当前经过身份验证的用户。我知道护照会将经过身份验证的用户附加到请求对象(至少我希望这是正确的),但我不知道如何访问解析器内的请求对象。
我跟着问题https://github.com/nestjs/nest/issues/1326和提到的链接https://github.com/ForetagInc/fullstack-boilerplate/tree/master/apps/api/src/app/auth问题。我看到一些代码使用@Res() res: Request
作为GraphQL解析器方法中的方法参数,但我总是为undefined
获取res
。
这些是我目前的实现:
GQLAuth
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { GqlExecutionContext } from '@nestjs/graphql';
import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';
import { AuthenticationError } from 'apollo-server-core';
@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
const { req } = ctx.getContext();
console.log(req);
return super.canActivate(new ExecutionContextHost([req]));
}
handleRequest(err: any, user: any) {
if (err || !user) {
throw err || new AuthenticationError('GqlAuthGuard');
}
return user;
}
}
需要访问当前用户的解析器
import { UseGuards, Req } from '@nestjs/common';
import { Resolver, Query, Args, Mutation, Context } from '@nestjs/graphql';
import { Request } from 'express';
import { UserService } from './user.service';
import { User } from './models/user.entity';
import { GqlAuthGuard } from '../auth/guards/gql-auth.guard';
@Resolver(of => User)
export class UserResolver {
constructor(private userService: UserService) {}
@Query(returns => User)
@UseGuards(GqlAuthGuard)
whoami(@Req() req: Request) {
console.log(req);
return this.userService.findByUsername('aw');
}
}
JWT战略
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { JwtPayload } from './interfaces/jwt-payload.interface';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.SECRET,
});
}
async validate(payload: JwtPayload) {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
授权和创建JWT令牌工作正常。 GraphQL guard也适用于不需要访问用户的方法。但对于需要访问当前经过身份验证的用户的方法,我认为无法获得它。
有没有办法完成这样的事情?
与往常一样,在您完成搜索数小时/天没有找到解决方案后,最后向StackOverflow发布问题,您将在几分钟内找到答案......
https://github.com/nestjs/graphql/issues/48#issuecomment-420693225向我指出了创建用户装饰器的正确方向
// user.decorator.ts
import { createParamDecorator } from '@nestjs/common';
export const CurrentUser = createParamDecorator(
(data, req) => req.user,
);
然后在我的解析器方法中使用它:
import { User as CurrentUser } from './user.decorator';
@Query(returns => User)
@UseGuards(GqlAuthGuard)
whoami(@CurrentUser() user: User) {
console.log(user);
return this.userService.findByUsername(user.username);
}
现在一切都按预期工作。所以这个答案的所有学分都归https://github.com/cschroeter所有