我目前正在使用 NestJS 创建一个 Rest API(顺便说一下,它真的很酷)。
在此 API 中,我使用 JWT(JSON Web 令牌)来允许用户根据其角色登录并查看不同的资源。
但是,我想实现一个 API 密钥系统来保护 API 本身。我不希望任何开发人员能够使用我的 API。我希望他通过这个 API 密钥来使用我的 API。
通过 URL 中的查询:https://domaine.com?api_key=${API_KEY}或通过标头:
GET /v1/some-resource
Host: docmaine.com
Accept: application/json
X-API-KEY: MyAwes0m3API_KeY
Run Code Online (Sandbox Code Playgroud)
您有教程、课程或曲目可以为我提供建议吗?
Jay*_*iel 24
为什么不创建一个警卫来检查该标头的有效性?
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private readonly apiKeyService: ApiKeyService) {} // made up service for the point of the exmaple
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
const key = req.headers['X-API-KEY'] ?? req.query.api_key; // checks the header, moves to query if null
return this.apiKeyService.isKeyValid(key);
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以@UseGuards(ApiKeyGuard)在任何路由上使用,或者全局绑定它,并且您已经为您的服务器进行了一些基本身份验证。
| 归档时间: |
|
| 查看次数: |
6839 次 |
| 最近记录: |