【问题标题】:How to implement multiple passport jwt authentication strategies in NestjsNestjs中如何实现多个passport jwt认证策略
【发布时间】:2020-10-21 14:32:26
【问题描述】:

我有一个已经可以正常工作的现有用户身份验证。用户身份验证令牌会在一小时内过期。

我想实现另一个单独的身份验证策略,即使用我的 Nestjs API 的第三个 API。第三方 API 有单独的端点,令牌应在 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.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);
    }
}

【问题讨论】:

  • 你弄明白了吗?

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


【解决方案1】:

通过上述设置,如果您使用的是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);
  }
}

【讨论】:

  • 你有实现这个技巧的 GitHub 存储库吗?
  • 不,我没有这方面的回购。我已经在我的一个办公室项目中实现了它。
猜你喜欢
  • 2020-06-09
  • 2021-06-11
  • 1970-01-01
  • 2022-12-24
  • 2020-03-24
  • 2018-03-05
  • 2020-03-27
  • 2019-03-28
  • 2021-08-10
相关资源
最近更新 更多