【发布时间】:2022-12-24 10:49:21
【问题描述】:
我在这里尝试使用 passport-headerapikey 库实现基于令牌的身份验证。
到目前为止,这是我尝试过的方法,出于某种原因,我从找不到的地方弹出了 500 服务器错误。
这是我的身份验证系统的结构(我的 graphQL 查询也有一个并行的基于 JWT 令牌的策略)。
应用模块
@Module({
imports: [
AuthModule,
],
controllers: [AppController],
providers: [
AppService
],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(AuthMiddleware).forRoutes('/datasource/:id');
}
}
认证模块
@Module({
imports: [
PassportModule,
],
providers: [
AuthService,
DatasourceTokenStrategy,
],
controllers: [],
exports: [AuthService],
})
export class AuthModule {}
datasourceToken.strategy
@Injectable()
export class DatasourceTokenStrategy extends PassportStrategy(
HeaderAPIKeyStrategy,
'datasourceToken',
) {
constructor(private authService: AuthService) {
super(
{ header: 'datasourceToken', prefix: '' },
true,
(apikey, done, req) => {
const checkKey = authService.validateDatasourceToken(apikey);
if (!checkKey) {
return done(false);
}
return done(true);
},
);
}
}
authMiddleware.strategy
import {
Injectable,
NestMiddleware,
UnauthorizedException,
} from '@nestjs/common';
import * as passport from 'passport';
@Injectable()
export class AuthMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
passport.authenticate(
'datasourceToken',
{ session: false, failureRedirect: '/api/unauthorized' },
(value) => {
if (value) {
next();
} else {
throw new UnauthorizedException();
}
},
)(req, res, next);
}
}
运行我的调试模式时,我可以看到 datasourceToken 策略没问题(我可以正确检索 datasourceToken 并验证它),但我认为问题是在我的 auth 中间件之后发生的。
谢谢你们的见解
【问题讨论】:
标签: nestjs passport.js