Jam*_*sen 7 jwt typescript passport.js auth0 nestjs
我正在尝试创建一个 NestJS 项目,该项目使用 Auth0 进行身份验证,并带有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`).',
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
/* 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;
}
Run Code Online (Sandbox Code Playgroud)
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 {}
Run Code Online (Sandbox Code Playgroud)
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 {}
Run Code Online (Sandbox Code Playgroud)
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';
}
}
Run Code Online (Sandbox Code Playgroud)
对localhost:3000/protected WITH有效承载令牌的get 请求会导致错误{"statusCode":401,"error":"Unauthorized"}。
可以在https://github.com/jajaperson/nest-auth0上找到完整的源代码
提前致谢;
詹姆士詹森
更新
好的,在将 bodge-y 包装函数放在EVERYWHERE 之后,我想我已经找到了问题的根源:每次运行该
secretOrKeyProvider函数时,done都会以非常熟悉的(对我而言)错误调用SSL Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE。这是由于我学校烦人的防火墙/CA,这是我一生中最烦人的事情。到目前为止,我发现解决这个问题的唯一方法是做危险的事情NODE_TLS_REJECT_UNAUTHORIZED=0(我曾尝试使用NODE_EXTRA_CA_CERTS,但到目前为止我失败了)。出于某种原因(虽然可能是一个很好的原因),我的解决方法在这种情况下不起作用。更新
我设法开始
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;
}
}
Run Code Online (Sandbox Code Playgroud)
同样,完整的(现在可用的)源代码可以在https://github.com/jajaperson/nestjs-auth0找到。
| 归档时间: |
|
| 查看次数: |
3755 次 |
| 最近记录: |