nestjs中的可选身份验证

kar*_*rim 1 javascript node.js typescript passport.js nestjs

我想知道是否有一个装饰器使该req.user对象在控制器方法中可用,如果用户已登录(发送了身份验证标头),如果没有,则将其req.user设为null。

AuthGuard装饰将返回401,如果用户没有登录,所以它不适合我的情况。

dem*_*isx 11

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

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

  authenticate() {
    return this.success({})
  }
}
Run Code Online (Sandbox Code Playgroud)

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

// 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
    }
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)


Kim*_*ern 5

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

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

export const User = createParamDecorator((data, req) => {
  return req.user;
});
Run Code Online (Sandbox Code Playgroud)

由于内置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;
  }

}
Run Code Online (Sandbox Code Playgroud)

确保您没有在抛出错误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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

@Get()
@UseGuards(MyAuthGuard)
getUser(@User() user) {
  return {user};
}
Run Code Online (Sandbox Code Playgroud)

  • 完美的答案。查遍 stackoverflow 和 github 都找不到它。 (3认同)