Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript nestjs中的可选身份验证_Javascript_Node.js_Typescript_Passport.js_Nestjs - Fatal编程技术网

Javascript nestjs中的可选身份验证

Javascript nestjs中的可选身份验证,javascript,node.js,typescript,passport.js,nestjs,Javascript,Node.js,Typescript,Passport.js,Nestjs,我想知道是否有一个修饰符使req.user对象在控制器方法中可用,如果用户已登录(已发送Authaurization标头),如果没有,则让req.user为空 如果用户未登录,AuthGuard装饰程序将返回401,因此它不适合我的情况。没有内置装饰程序,但您可以自己轻松创建一个。请参见下面的示例: 由于内置的AuthGuard引发异常,因此您可以创建自己的版本并覆盖请求处理程序: @Injectable() export class MyAuthGuard extends AuthGuard(

我想知道是否有一个修饰符使
req.user
对象在控制器方法中可用,如果用户已登录(已发送Authaurization标头),如果没有,则让
req.user
为空


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

没有内置装饰程序,但您可以自己轻松创建一个。请参见下面的示例:

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

}
确保您的
jwt策略中没有抛出错误

@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;
  }
}
然后您可以在
控制器中使用它,如下所示:

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

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

// 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
    }
    ...
  }
}

如果你还没有,看看:完美答案。在stackoverflow和githubs中找不到它。我找不到@Userdecorator@jeromerg这是一个自定义的decoator,在这个答案的第一个代码段中定义。谢谢,我认为使用它更灵活。因为有时我们需要拒绝未经身份验证的用户。我用我的Graphql Guard实现了它``从'@nestjs/common'导入{Injectable,ExecutionContext}从'@nestjs/passport'导入{GqlExecutionContext}从'@nestjs/Graphql'@Injectable()导出类EveryonEqlAuthGuard扩展了AuthGuard(['jwt','anonymous']{getRequest(上下文:ExecutionContext){const ctx=GqlExecutionContext.create(上下文)return ctx.getContext().req}```
// 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
    }
    ...
  }
}