如何自定义一个 Passport Strategy 来实现基于 API Key 的认证?
解读
国内主流场景里,B 端开放接口、内部微服务调用、Serverless 函数网关,都习惯用“一个固定字符串”做身份标识,而不是走 OAuth2/JWT 全套流程。NestJS 官方文档只给了 JWT、Local、OAuth2 的“现成包”,面试时如果直接说“装个包就行”,会被追问“不依赖现成包怎么做”。
核心考点:
- 懂 Passport 的“Strategy 规范”——只要继承 passport-strategy 并实现 authenticate(req) 方法即可;
- 懂 NestJS 的依赖注入——把 Strategy 声明成 Provider,并注册到 AuthModule;
- 懂装饰器与守卫——用 @UseGuards(AuthGuard('apikey')) 一键生效;
- 懂国内安全合规——Key 必须可吊销、可刷新、可区分环境,不能写死代码里。
答到这四层,才算“企业级落地思维”。
知识点
- passport-strategy 抽象类:authenticate(req, options) 是唯一切入点,成功调用 this.success(user, info),失败调用 this.fail/unauthorized。
- NestJS 的 PassportModule.register({ defaultStrategy: 'apikey' }) 只是语法糖,真正生效的是 PassportStrategy 基类。
- 自定义 Strategy 要同时提供 validate(payload) 给 NestJS 做 IoC,否则守卫拿不到 user 对象。
- 国内云厂商(阿里云、腾讯云)网关通常把 API Key 放在 X-Ca-Key、X-TC-Key 头,代码里不要写死 header 名,用配置中心动态取。
- 为了通过等保测评,Key 必须加密落库(AES-256+KMS),接口返回不能带明文 Key,面试时主动提一嘴,能体现安全意识。
答案
-
安装依赖
npm i passport passport-strategy @nestjs/passport @nestjs/config -
创建策略文件 src/auth/apikey.strategy.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, HeaderAPIKeyStrategy } from 'passport-headerapikey';
import { AuthService } from './auth.service';
@Injectable()
export class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy, 'apikey') {
constructor(
private configService: ConfigService,
private authService: AuthService,
) {
super(
{ header: configService.get<string>('API_KEY_HEADER'), prefix: '' },
true,
async (apikey: string, done: (err, user) => void) => {
const user = await this.authService.validateApiKey(apikey);
if (!user) return done(new UnauthorizedException('Invalid Key'), null);
done(null, user);
},
);
}
}
- 在 AuthModule 注册
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { ApiKeyStrategy } from './apikey.strategy';
import { AuthService } from './auth.service';
@Module({
imports: [PassportModule.register({ defaultStrategy: 'apikey' })],
providers: [AuthService, ApiKeyStrategy],
exports: [PassportModule],
})
export class AuthModule {}
- 守卫使用
import { Controller, Get, UseGuards, Request } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('open')
@UseGuards(AuthGuard('apikey'))
export class OpenController {
@Get('profile')
getProfile(@Request() req) {
return { user: req.user };
}
}
- 验证逻辑(示例)
async validateApiKey(key: string): Promise<User | null> {
const hash = createHash('sha256').update(key).digest('hex');
return this.userRepo.findOne({ where: { apiKeyHash: hash, revokedAt: IsNull() } });
}
至此,一个可吊销、可配置、可单元测试的 API Key 认证策略完成。
拓展思考
- 多策略并存:同一套服务既要支持内网 API Key,也要支持外部 OAuth2,可在控制器层用 @UseGuards(AuthGuard(['apikey', 'jwt'])),并配合策略优先级与黑白名单。
- 动态刷新:把 Key 存到 Redis 并设置 TTL,调用方走“旧 Key 续期”接口,实现无停机轮换,满足金融客户“密钥 90 天强制更换”合规要求。
- 链路追踪:在 Strategy 的 validate 阶段把 keyId 写入 AsyncLocalStorage,后续日志、监控都能关联到“哪个租户”调用,方便故障定位。
- 性能优化:Key 的哈希查询走 Redis Bloom 过滤器,先过滤再查库,可把 QPS 提升 3 倍,面试时主动提性能数据,能体现高并发经验。