如何在Nestjs中实施多种护照JWT身份验证策略

时间:2020-07-01 07:34:31

标签: node.js typescript authentication passport.js nestjs

我有一个针对用户的现有身份验证,它已经可以正常工作了。用于用户身份验证的令牌在一小时内到期。

我想使用消耗我的Nestjs API的第三个API实施另一种单独的身份验证策略。第三方API有单独的端点,令牌应在24小时后过期。该API必须保持与我的应用程序连接24小时。

我不介意使用其他软件包来实现这一目标。

我还需要创建一个名为thirdParty Guard的保护程序,以便仅第三部分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.strategy.ts

@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);
    }
}

1 个答案:

答案 0 :(得分:0)

通过上述设置,如果您使用的是 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier,请尝试在 Guard 中添加 Passport-HeaderAPIKey。以下代码对我有用。

参考:NestJS extending guard

headerapikey