护照策略中的访问响应

发布于 2025-02-06 17:37:20 字数 1406 浏览 2 评论 0原文

我正在使用Nestjs和Passport实施身份验证。

我有一个令牌,到期日期为14天,刷新时间为15分钟(在有效载荷内)。因此,如果用户在15分钟内提出请求,一切正常;但是之后,需要刷新它。我将JWT的签名存储在另一个表中,如果存在,我会制作一个新的令牌,如果不是,我只是投掷未验证的例外。

这是一个挑战:我需要将新创建的JWT令牌设置为响应标头。

这是我的代码:

// jwt.strategy.ts

import { ConfigService } from '@nestjs/config';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { AuthService } from '../auth.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private configService: ConfigService,
    private authService: AuthService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get('JWT_SECRET'),
      passReqToCallback: true,
    });
  }

  async validate(req: any, payload: any) {
    const { refreshTime, sub, phoneNumber } = payload;
    const tokenSignature = req.get('authorization').split('.').reverse()[0];
    if (refreshTime < Date.now()) {
      console.log('REFRESH');
      this.authService.refreshToken(tokenSignature);
      // **Set new token to response header**
    }
    return {
      userId: sub,
      phoneNumber,
      tokenSignature,
    };
  }
}

我是Nestjs的新手,实际上我不知道这是否是这样做的正确地方。

我应该创建一个拦截器之类的东西,甚至应该在authguard内部处理这个问题吗?

I'm implementing an authentication with nestJS and passport.

I have one token, with expiration date of 14 days, and a refreshTime of 15 minutes (inside the payload). So if the user makes a request within 15 minutes, everything goes normal; but after that, it needs to be refreshed. I store signature of jwt inside another table and if it exists, I make a new token, if not I just throw not authenticated exception.

Here is the challenge: I need to set the newly created jwt token to response header.

Here is my code:

// jwt.strategy.ts

import { ConfigService } from '@nestjs/config';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { AuthService } from '../auth.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private configService: ConfigService,
    private authService: AuthService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get('JWT_SECRET'),
      passReqToCallback: true,
    });
  }

  async validate(req: any, payload: any) {
    const { refreshTime, sub, phoneNumber } = payload;
    const tokenSignature = req.get('authorization').split('.').reverse()[0];
    if (refreshTime < Date.now()) {
      console.log('REFRESH');
      this.authService.refreshToken(tokenSignature);
      // **Set new token to response header**
    }
    return {
      userId: sub,
      phoneNumber,
      tokenSignature,
    };
  }
}

I'm new to nestJs, and I actually don't know if this is the right place to do this or not.

Should I create an interceptor or something, or even handle this inside authGuard?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天冷不及心凉 2025-02-13 17:37:20

我可以通过Authguard传递响应对象:

// jwt-auth.guard.ts

import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  canActivate(context: ExecutionContext) {
    const http = context.switchToHttp();
    const res = http.getResponse();
    const req = http.getRequest();
    req.res = res;
    return super.canActivate(context);
  }
}

I could pass the response object from AuthGuard:

// jwt-auth.guard.ts

import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  canActivate(context: ExecutionContext) {
    const http = context.switchToHttp();
    const res = http.getResponse();
    const req = http.getRequest();
    req.res = res;
    return super.canActivate(context);
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文