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
- Store the Secret: First, store the JWT's
secretOrKeywithin the deployment environment's environment variables. This can be achieved by setting it in the environment configuration file (e.g.,.envfile) or in the cloud service configuration.
bashJWT_SECRET=your_secret_key
- Configure Module: In NestJS, use
ConfigModuleandConfigServiceto securely access environment variables. First, ensure the@nestjs/configmodule is installed.
bashnpm install @nestjs/config
Import ConfigModule into your module:
typescriptimport { ConfigModule } from '@nestjs/config'; @Module({ imports: [ConfigModule.forRoot({ isGlobal: true, // Make configuration globally available })], }) export class AppModule {}
- Use Secret: In the JWT strategy configuration, use
ConfigServiceto dynamically retrievesecretOrKey.
typescriptimport { 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:
- 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.
bashnpm install aws-sdk
- Create Service: Create a service to handle interactions with the remote configuration service.
typescriptimport { 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; } }
- Configure JWT Strategy: Use this service to dynamically provide
secretOrKeyin the JWT strategy.
typescriptconstructor(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 回复