【问题标题】:Unable to implement api key authentication passport NestJS无法实现api密钥认证护照NestJS
【发布时间】: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);
  }
}

这是使用 Jest 测试端点时抛出的错误:

运行我的调试模式时,我可以看到 datasourceToken 策略没问题(我可以正确检索 datasourceToken 并验证它),但我认为问题是在我的 auth 中间件之后发生的。

谢谢你们的见解

【问题讨论】:

    标签: nestjs passport.js


    【解决方案1】:

    函数“done()”有 3 个参数。

    done(error, user, info)
    

    您需要传递 null 作为第一个参数,让 passport 知道在验证时没有错误。

    done(null, true)
    

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 2019-03-01
      • 1970-01-01
      • 2015-07-03
      • 2021-12-18
      • 2012-02-05
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多