Nest.js权限管理系统开发jwt登录
warning:
这篇文章距离上次修改已过186天,其中的内容可能已经有所变动。
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.get<string>('JWT_SECRET'),
});
}
async validate(payload: any) {
// 这里可以添加验证逻辑,比如检查jwt是否在黑名单中
if (payload.isBlacklisted) {
throw new UnauthorizedException('Token is blacklisted');
}
// 返回用户信息,这些信息可以用于应用的权限管理
return payload;
}
}
这段代码定义了一个JWT策略,用于处理用户登录时获取的JWT。在验证JWT时,它会检查JWT是否在黑名单中,如果在,则抛出一个未授权的异常。如果JWT没有被封禁,那么它会返回包含在JWT内的用户信息。这个例子展示了如何在Nest.js中结合配置服务来使用JWT,并在验证阶段添加额外的安全措施。
评论已关闭