Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs passport authentication with multiple strategies

Tags:

nestjs

I have multiple authentication strategies, example for one of them:

@Injectable()
export class EmployeeStrategy extends PassportStrategy(Strategy, 'employee') {
  constructor(
    private authService: AuthService,
    @Inject(appConfig.KEY)
    configService: ConfigType<typeof appConfig>,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.EMPLOYEE_KEY,
    });
  }

  async validate({ phone }: JwtPayload) {
    const employee = await this.authService.authByRole(phone, Role.Employee);

    if (!employee) {
      throw new UnauthorizedException('insufficient scope');
    }

    return employee;
  }

And some others mostly like this one. But because i throw unauthorized exception inside it, i cannot use multiple of them at the same route/controller. E.g.

  @UseGuards(AuthGuard(['employee', 'admin']))

The first one that crashes leading to error. How to solve that problem?

like image 388
xxx_coder_noscope Avatar asked Jul 01 '20 05:07

xxx_coder_noscope


1 Answers

@xxx_coder_noscope Your vision of the strategy is a bit wrong. The strategy here is a way how to get a special token, secret key, etc from a defined place(HTTP header, query, param, cookies, etc). The entity returned from the validate() method will be injected to request object as user property.

Later via creating an EmployeeGuard as EmployeeGuard implements CanActivete and overriding canActivate() method check user role by type and return boolean for allowing or decline access to endpoint

like image 81
Павел Калиниченко Avatar answered Oct 19 '22 07:10

Павел Калиниченко