首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Nestjs Passport-jwt更好的未经授权策略

Nestjs Passport-jwt更好的未经授权策略
EN

Stack Overflow用户
提问于 2022-03-18 12:33:06
回答 1查看 782关注 0票数 0

只需在NestJS:docs.nestjs.com中查看身份验证文档

以下是代码:

代码语言:javascript
复制
import { ExtractJwt, Strategy } from 'passport-jwt';  
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

根据docs,当请求包含jwt且jwt有效时,将调用valid方法。当请求头中缺少jwt,或者jwt无效或过期时,我想知道是否存在回调方法。我想返回响应错误与消息,他们的令牌已过期或丢失.

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-18 14:48:56

您可以实现自定义策略,并检查您喜欢的标题或cookie。这是我在应用程序上使用的一个(简称)示例。

代码语言:javascript
复制
import { JwtService } from '@nestjs/jwt';
import { Strategy } from 'passport-custom';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'custom-jwt') {
  constructor(private readonly jwtService: JwtService) {
    super();
  }

  async validate(req: Request): Promise<any> {
    const token = req.cookies.auth ?? req.headers.authorization;
    if (!token) {
      throw new UnauthorizedException();
    }

    const user = this.jwtService.decode(token, {
      json: true
    });

    if (!user) {
      throw new UnauthorizedException();
    }
    if (this.isExpired(user)) {
      throw new UnauthorizedException();
    }

    return user;
  }

  private isExpired(user: JwtUserDto): boolean {
    // ...
  }
}

该代码在"auth"-cookie或“授权”-header中检查jwt令牌,并通过返回用户,将解码用户(如果有效)附加到请求。

使用它:export class JwtAuthGuard extends AuthGuard('custom-jwt')

这只是一个例子,看看它是如何工作的。您可能需要调整它以满足您的需要。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71527077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档