import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable } from '@nestjs/common'; import { jwtConstants } from './constants'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: jwtConstants.secret, }); } async validate(payload: any) { return { userId: payload.sub, username: payload.username }; } }
时间: 2024-04-05 22:30:39 浏览: 13
这是一个使用Passport和JWT进行用户认证的策略类。其中,Passport是一个用于Node.js应用程序的身份验证中间件,JWT是一个用于Web应用程序的开放标准。在这个策略类中,使用Passport提供的PassportStrategy类继承了JWTStrategy类,并将其用作Passport的身份验证策略。
在constructor()方法中,使用super()调用父类的构造函数,并传入了一个包含jwtFromRequest、ignoreExpiration和secretOrKey属性的对象。其中,jwtFromRequest用于指定从哪里获取JWT,这里使用了从请求头中获取Bearer Token的方式;ignoreExpiration指定是否忽略JWT的过期时间;secretOrKey指定用于签名和验证JWT的密钥或公钥。
在validate()方法中,使用传入的payload参数,即从JWT中解码出的数据,生成一个包含userId和username属性的对象,并作为认证成功的返回值。这个方法由Passport调用,用于验证用户的身份。如果验证成功,Passport会将用户信息添加到请求对象的user属性中,供后续的请求使用。
相关问题
@nestjs/jwt
@nestjs/jwt是一个用于在NestJS应用程序中实现JSON Web Token(JWT)功能的模块。您可以通过运行命令`npm i --save @nestjs/jwt`来安装它。然后,您可以在您的应用程序中导入JwtModule并在其配置中指定一个密钥,如以下代码所示:
```typescript
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
@Module({
imports: [JwtModule.register({ secret: 'hard-to-guess_secret' })],
providers: [...],
})
export class AuthModule {}
```
这样,您就可以在您的应用程序中使用@nestjs/jwt模块提供的功能了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [jwt:基于jsonwebtoken包的JWT实用程序模块:unlocked:](https://download.csdn.net/download/weixin_42114046/15243990)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [如何在 NestJS 中实现 JWT 认证](https://blog.csdn.net/weixin_47967031/article/details/127347203)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
//jwt.strategy.ts ... import { ConfigService } from '@nestjs/config'; import { UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { StrategyOptions, Strategy, ExtractJwt } from 'passport-jwt'; export class JwtStorage extends PassportStrategy(Strategy) { constructor( @InjectRepository(User) private readonly userRepository: Repository<User>, private readonly configService: ConfigService, private readonly authService: AuthService, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: configService.get('SECRET'), } as StrategyOptions); } async validate(user: User) { const existUser = await this.authService.getUser(user); if (!existUser) { throw new UnauthorizedException('token不正确'); } return existUser; } }
这是一个 Nest.js 中用于 JWT 鉴权的策略。它使用了 `passport-jwt` 模块来从请求的 Authorization 头部中提取 JWT Token,并使用 Nest.js 的 ConfigService 来获取应用程序的密钥。在 validate 方法中,它首先调用了 AuthService 的 getUser 方法来获取用户信息,并将其与传入的 user 参数进行比较,如果不匹配则抛出 UnauthorizedException。最后,如果验证通过,它将返回存在的用户信息。