我正在尝试创建一个使用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找到
提前致谢; 詹姆斯詹森
UPDATE
好吧,在将bodge-y包装函数放在任何地方之后,我想我已经找到了问题的根源:每次运行
secretOrKeyProvider
函数时,done
都会以令人难以置信的熟悉(对我来说)错误SSL Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE
进行调用。这是因为我学校的烦人的防火墙/ CA,这是我生命中最烦人的事情。到目前为止,我发现解决这个问题的唯一方法是做危险的NODE_TLS_REJECT_UNAUTHORIZED=0
(我尝试过使用NODE_EXTRA_CA_CERTS
,但到目前为止我失败了)。由于某种原因(虽然可能是一个好的)我的解决方法在这种情况下不起作用。UPDATE
我设法让
NODE_EXTRA_CA_CERTS
工作,让我狂喜地尖叫起来。
所有我必须做的(一旦我停止得到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;
}
}