如何在http策略的validate方法中访问请求URL?

问题描述 投票:1回答:1

我想在我的承载策略验证方法中访问保护中存在的上下文对象。我可以将它作为参数与令牌一起传递吗?

承载-auth.guard.ts:

@Injectable()
export class BearerAuthGuard extends AuthGuard('bearer') {
    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
        return super.canActivate(context);
    }
}

http.strategy.ts:

@Injectable()
export class HttpStrategy extends PassportStrategy(Strategy) {
    constructor(private globalService: GlobalService) {
        super();
    }

    async validate(token: string) {
        const customer = await this.globalService.validateCustomer(token);
        if (!customer) {
            throw new UnauthorizedException();
        }
        return customer;
    }
}

我想要这样的东西:

async validate(token: string, context) { // <-- context object as argument
    const customer = await this.globalService.validateCustomer(token);
    if (!customer) {
        throw new UnauthorizedException();
    }
    return customer;
}
javascript node.js typescript passport.js nestjs
1个回答
1
投票

您可以通过将选项request传递给passReqToCallback: true来访问passport-http-bearer对象。那么验证回调中的第一个参数将是request

@Injectable()
export class HttpStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    // Add the option here
    super({ passReqToCallback: true });
  }

  async validate(request: Request, token: string) {
    // Now you have access to the request url
    console.log(request.url);
    const user = await this.authService.validateUser(token);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

在这里查看正在运行的演示

Edit Nest HTTP Auth

© www.soinside.com 2019 - 2024. All rights reserved.