如果通过身份验证,则NestJs解析用户

时间:2018-11-11 14:42:06

标签: javascript node.js typescript passport.js nestjs

我想知道是否有一个装饰器可以在控制器方法中使req.user对象可用,如果用户已登录(发送了身份验证标头),如果没有,那么请让req.user为空。

如果用户未登录,AuthGuard装饰器将返回401,因此不适合我的情况。

2 个答案:

答案 0 :(得分:4)

另一种方法是通过创建匿名护照策略:

// In anonymous.strategy.ts
@Injectable()
export class AnonymousStrategy extends PassportStrategy(Strategy, 'anonymous') {
  constructor() {
    super()
  }

  authenticate() {
    return this.success({})
  }
}

然后,在控制器中链接此策略:

// In create-post.controller.ts
@Controller()
export class CreatePostController {
  @UseGuards(AuthGuard(['jwt', 'anonymous'])) // first success wins
  @Post('/posts')
  async createPost(@Req() req: Request, @Body() dto: CreatePostDto) {
    const user = req.user as ExpressUser

    if (user.email) {
      // Do something if user is authenticated
    } else {
      // Do something if user is not authenticated
    }
    ...
  }
}

答案 1 :(得分:3)

没有内置装饰器,但是您可以轻松地自己创建一个。请参见docs中的示例:

import { createParamDecorator } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

export const User = createParamDecorator((data, req) => {
  return req.user;
});

由于内置AuthGuard引发异常,因此您可以创建自己的版本并覆盖请求处理程序:

@Injectable()
export class MyAuthGuard extends AuthGuard('jwt') {

  handleRequest(err, user, info) {
    // no error is thrown if no user is found
    // You can use info for logging (e.g. token is expired etc.)
    // e.g.: if (info instanceof TokenExpiredError) ...
    return user;
  }

}

确保您没有在JwtStrategy中抛出错误:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secretKey',
    });
  }

  async validate(payload) {
    const user = await this.authService.validateUser(payload);
    // in the docs an error is thrown if no user is found
    return user;
  }
}

然后您可以像这样在Controller中使用它:

@Get()
@UseGuards(MyAuthGuard)
getUser(@User() user) {
  return {user};
}