我试图创建一个使用Auth0进行身份验证的NestJS项目,并使用passport-jwt
库(与@nestjs/passport
一起使用),尽管我无法使其正常工作。我不确定我要去哪里。我已经读了一遍又一遍的文档,但是仍然找不到问题。
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`).',
);
}
}
}
/* 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;
}
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 {}
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 {}
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
的获取请求有有效的承载令牌会导致错误{"statusCode":401,"error":"Unauthorized"}
。
完整源可在https://github.com/jajaperson/nest-auth0
找到预先感谢;
詹姆斯·詹森
更新
好吧,在放置了bodge-y包装函数 任何地方 之后,我认为 我发现了问题的根源:每次
secretOrKeyProvider
函数正在运行,done
被调用时遇到了非常熟悉的错误(对我来说)SSL Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE
。这是由于我学校的 烦人的防火墙/ CA,这是我一生中最烦人的事情。的 到目前为止,我发现绕过这个问题的唯一方法就是危险NODE_TLS_REJECT_UNAUTHORIZED=0
(我尝试使用NODE_EXTRA_CA_CERTS
,但到目前为止我失败了。由于某些原因(尽管 可能是个不错的选择),我的解决方法在这种情况下不起作用。更新
我设法让
NODE_EXTRA_CA_CERTS
正常工作,导致我跳了起来, 欣喜若狂地尖叫。
答案 0 :(得分:1)
我所要做的(一旦我停止获取UNABLE_TO_VERIFY_LEAF_SIGNATURE
错误,我所要做的就是返回payload
(如果有效)。
@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;
}
}