乐闻世界logo
搜索文章和话题

How to get the JWT's secretOrKey from remote in NestJS?

1个答案

1

In NestJS, obtaining the JWT's secretOrKey typically requires prioritizing security and maintainability. The ideal approach is not to hardcode secretOrKey in the code but rather dynamically retrieve it via environment variables or remote configuration services. The following is one implementation approach:

Using Environment Variables

  1. Store the Secret: First, store the JWT's secretOrKey within the deployment environment's environment variables. This can be achieved by setting it in the environment configuration file (e.g., .env file) or in the cloud service configuration.
bash
JWT_SECRET=your_secret_key
  1. Configure Module: In NestJS, use ConfigModule and ConfigService to securely access environment variables. First, ensure the @nestjs/config module is installed.
bash
npm install @nestjs/config

Import ConfigModule into your module:

typescript
import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot({ isGlobal: true, // Make configuration globally available })], }) export class AppModule {}
  1. Use Secret: In the JWT strategy configuration, use ConfigService to dynamically retrieve secretOrKey.
typescript
import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy, ExtractJwt } from 'passport-jwt'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(private configService: ConfigService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: configService.get<string>('JWT_SECRET'), }); } async validate(payload: any) { return { userId: payload.sub, username: payload.username }; } }

Using Remote Configuration Services

If you need to retrieve secretOrKey from a remote configuration service (e.g., AWS Secrets Manager, Azure Key Vault), follow these steps:

  1. Integrate Remote Service Client: First, select an appropriate client library and integrate it into your NestJS application. For example, if using AWS Secrets Manager, install the AWS SDK.
bash
npm install aws-sdk
  1. Create Service: Create a service to handle interactions with the remote configuration service.
typescript
import { Injectable } from '@nestjs/common'; import * as AWS from 'aws-sdk'; @Injectable() export class SecretsService { private secretsManager = new AWS.SecretsManager(); async getSecretValue(secretId: string): Promise<string> { const data = await this.secretsManager.getSecretValue({ SecretId: secretId }).promise(); return data.SecretString; } }
  1. Configure JWT Strategy: Use this service to dynamically provide secretOrKey in the JWT strategy.
typescript
constructor(private configService: ConfigService, private secretsService: SecretsService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKeyProvider: async (request, rawJwtToken, done) => { try { const jwtSecret = await this.secretsService.getSecretValue('JWT_SECRET_ID'); done(null, jwtSecret); } catch (err) { done(err, null); } }, }); }

This approach ensures the security of secretOrKey and allows updating the key without redeploying the application. By implementing this, we can effectively secure the JWT.

2024年8月15日 20:55 回复

你的答案