通过“passport-jwt"使用 Auth0 进行 NestJS 身份验证 [英] NestJS Authentication with Auth0 via `passport-jwt`

查看:50
本文介绍了通过“passport-jwt"使用 Auth0 进行 NestJS 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 passport-jwt 库(结合 @nestjs/passport)创建一个使用 Auth0 进行身份验证的 NestJS 项目,尽管我我无法让它工作.我不确定我哪里出错了.我一遍又一遍地阅读文档,但仍然找不到问题.

I'm trying to create a NestJS project that uses Auth0 for authentication, with the passport-jwt library (in conjunction with @nestjs/passport), though I am unable to get it to work. I'm not sure where I'm going wrong. I've read the docs over and over again but still can't find the problem.

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { passportJwtSecret } from 'jwks-rsa';
import { xor } from 'lodash';
import { JwtPayload } from './interfaces/jwt-payload.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: 'http://localhost:3000',
      issuer: `https://${process.env.AUTH0_DOMAIN}/`,
    });
  }

  validate(payload: JwtPayload) {
    if (
      xor(payload.scope.split(' '), ['openid', 'profile', 'email']).length > 0
    ) {
      throw new UnauthorizedException(
        'JWT does not possess the requires scope (`openid profile email`).',
      );
    }
  }
}

/src/auth/interfaces/jwt-payload.interface

/* Doesn't do much, not really relevant */
import { JsonObject } from '../../common/interfaces/json-object.interface';

export interface JwtPayload extends JsonObject {
  /** Issuer (who created and signed this token) */
  iss?: string;
  /** Subject (whom the token refers to) */
  sub?: string;
  /** Audience (who or what the token is intended for) */
  aud?: string[];
  /** Issued at (seconds since Unix epoch) */
  iat?: number;
  /** Expiration time (seconds since Unix epoch) */
  exp?: number;
  /** Authorization party (the party to which this token was issued) */
  azp?: string;
  /** Token scope (what the token has access to) */
  scope?: string;
}

/src/auth/auth.module.ts

import { Module } from '@nestjs/common';
import { JwtStrategy } from './jwt.strategy';
import { PassportModule } from '@nestjs/passport';

@Module({
  imports: [PassportModule.register({ defaultStrategy: 'jwt' })],
  providers: [JwtStrategy],
  exports: [JwtStrategy],
})
export class AuthModule {}

/src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';

@Module({
  imports: [AuthModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

/src/app.controller.ts

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from '@nestjs/passport';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @Get('protected')
  @UseGuards(AuthGuard())
  getProtected(): string {
    return 'This route is protected';
  }
}

localhost:3000/protected 的 get 请求 WITH 有效的不记名令牌导致错误 {"statusCode":401,"error":"未经授权"}.

A get request to localhost:3000/protected WITH a valid bearer token results in the error {"statusCode":401,"error":"Unauthorized"}.

可以在 https://github.com/jajaperson/nest-auth0

提前致谢;
詹姆斯·詹森

Thanks in advance;
James Jensen

好的,在将 bodge-y 包装函数EVERYWHERE 放在之后,我想我找到了问题的根源:每次secretOrKeyProvider 函数运行,完成以令人难以置信的熟悉(对我而言)错误调用SSL 错误:UNABLE_TO_VERIFY_LEAF_SIGNATURE.这是由于我学校的烦人的防火墙/CA,这是我一生中最烦人的事情.这到目前为止我发现解决这个问题的唯一方法是做危险的事情NODE_TLS_REJECT_UNAUTHORIZED=0(我曾尝试使用NODE_EXTRA_CA_CERTS,但到目前为止我失败了).出于某种原因(虽然可能很好)我的解决方法在这种情况下不起作用.

UPDATE

Okay, after putting bodge-y wrapper functions EVERYWHERE, I think I've found the source of the problem: Every time the secretOrKeyProvider function is run, done gets called with the incredibly familiar (for me) error SSL Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE. This is due to my school's annoying firewall/CA, which is the most annoying thing in my life. The only way I've found to get around this so far is doing the dangerous NODE_TLS_REJECT_UNAUTHORIZED=0 (I have tried using NODE_EXTRA_CA_CERTS, but so far I've failed). For some reason (though probably a good one) my workaround doesn't work in this situation.

我设法让 NODE_EXTRA_CA_CERTS 工作,这让我跳起来欣喜若狂地尖叫起来.

I managed to get NODE_EXTRA_CA_CERTS to work, causing me to jump up and down screaming ecstatically.

推荐答案

所有我必须做的(一旦我停止获得 UNABLE_TO_VERIFY_LEAF_SIGNATURE)错误,我所要做的就是返回 payload 如果它有效.

All I had to do (once I stopped getting the UNABLE_TO_VERIFY_LEAF_SIGNATURE) error, all I had to do was return payload if it was valid.

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: 'http://localhost:3000',
      issuer: `https://${process.env.AUTH0_DOMAIN}/`,
    });
  }

  validate(payload: JwtPayload): JwtPayload {
    if (
      xor(payload.scope.split(' '), ['openid', 'profile', 'email']).length > 0
    ) {
      throw new UnauthorizedException(
        'JWT does not possess the requires scope (`openid profile email`).',
      );
    }
    return payload;
  }
}

同样,可以在 https://github.com/jajaperson/nestjs-auth0.

这篇关于通过“passport-jwt"使用 Auth0 进行 NestJS 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆