gpt4 book ai didi

node.js - 如何在Nestjs中实现多种 Passport JWT身份验证策略

转载 作者:行者123 更新时间:2023-12-03 14:53:02 28 4
gpt4 key购买 nike

我有一个针对用户的现有身份验证,它已经可以正常工作了。用于用户身份验证的 token 将在一小时内过期。
我想使用消耗我的Nestjs API的第三个API来实现另一种单独的身份验证策略。第三方API有单独的端点, token 应在24小时后过期。该API必须保持与我的应用的连接24小时。
我不介意使用其他程序包来实现此目的。
我还需要创建一个名为thirdParty Guard的保护程序,以便仅第3部分API即可访问该端点。
这是我的jwt.strategy.ts

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.SECRETKEY
});
}

async validate(payload: any, done: VerifiedCallback) {
const user = await this.authService.validateUser(payload);
if (!user) {
return done(
new HttpException('Unauthorised access', HttpStatus.UNAUTHORIZED),
false,
);
}
//return user;
return done(null, user, payload.iat)
}
}
ApiKey策略
@Injectable()
export class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy) {
constructor(private authService: AuthService) {
super({
header: 'api_key',
prefix: ''
}, true,
(apikey: string, done: any, req: any, next: () => void) => {
const checkKey = this.authService.validateApiKey(apikey);
if (!checkKey) {
return done(
new HttpException('Unauthorized access, verify the token is correct', HttpStatus.UNAUTHORIZED),
false,
);
}
return done(null, true, next);
});
}
}
这是auth.service.ts
@Injectable()
export class AuthService {
constructor(private userService: UserService) { }

async signPayLoad(payload: any) {
return sign(payload, process.env.SECRETKEY, { expiresIn: '1h' });

}

async validateUser(payload: any) {
const returnuser = await this.userService.findByPayLoad(payload);
return returnuser;
}

validateApiKey(apiKey: string) {
const keys = process.env.API_KEYS;
const apiKeys = keys.split(',');
return apiKeys.find(key => apiKey === key);
}
}

最佳答案

通过上述设置,如果您使用的是Passport-HeaderAPIKey,请尝试在Guard中添加headerapikey。下面的代码为我工作。
引用:NestJS extending guard

import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard as NestAuthGuard } from '@nestjs/passport';

@Injectable()
export class AuthGuard extends NestAuthGuard(['jwt', 'headerapikey']) {
constructor(private readonly reflector: Reflector) {
super();
}

canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
context.getHandler(),
context.getClass(),
]);

if (isPublic) {
return true;
}

return super.canActivate(context);
}
}

关于node.js - 如何在Nestjs中实现多种 Passport JWT身份验证策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62671831/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com