nestjs / passport

Passport module for Nest framework (node.js) 🔑
https://nestjs.com
MIT License
510 stars 117 forks source link

AuthGuard multiple strategies execution order #414

Closed gpanainte closed 4 years ago

gpanainte commented 4 years ago

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

For one of my API endpoints I want to allow access for both public (Unauthenticated users) and authenticated users. My controller looks like this:

@UseGuards(AuthGuard(['jwt', 'anonymous']))
export class MyController{
@Post()
async createLead(@Headers() headers: any, @Request() request, @Body() data: PayloadDto): Promise<ResponseDto> {
   ...
 }
}

The service for the anonymus strategy looks like this.

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-anonymous';

@Injectable()
export class AnonymousStrategyService extends PassportStrategy(Strategy, 'anonymous') {

  constructor() {
    super();
  }

  authenticate() {
    return this.success({});
  }

}

The issue I have is that the anonymous strategy always "wins" because it is always faster than jwt strategy that takes longer because it has to go to the DB to validate user status.

Is it possible to have configure the execution order: check if user has a JWT token, if true authenticate by token, else if user has no token allow the request as a public user.

Expected behavior

Execute auth strategies in a predetermined order. Ex: check if user has a JWT token, if true authenticate by token, else if user has no token allow the request as a public user.

Minimal reproduction of the problem with instructions

The code base is private, but if is necessary I could create a small project.

What is the motivation / use case for changing the behavior?

Allow multiple and more sophisticated authentication strategies for the same endpoint.

Environment


  "@nestjs/common": "^7.4.2",
  "@nestjs/core": "^7.4.2",
  "@nestjs/jwt": "^7.1.0",
  "@nestjs/passport": "^7.1.0",
  "@nestjs/platform-express": "^7.4.2",


For Tooling issues:
- Node version: XX  
- Platform:  

Others:

gpanainte commented 4 years ago

I'm closing this issue because I have found a workaround based on this suggestion

furkan-bunch commented 1 year ago

i have a scenario where authentication is considered as failed only if all 3 strategies fail, eg i am okay whenever 1 of the strategies are successful. one of the strategies is very quick to fail/succeed and always wins the race. is there a way to change this behaviour via flags?