mikenicholson / passport-jwt

Passport authentication using JSON Web Tokens
MIT License
1.97k stars 215 forks source link

Scopes or Similar #180

Open JKing-B16 opened 5 years ago

JKing-B16 commented 5 years ago

It would be nice to have a way of passing through the scope option of passport.authenticate to help determine if the JWT token is not just valid, but valid for a given scope.

For my application I hacked together this paraphrased solution:

class JWTScopeStrategy extends JWTStrategy {
  authenticate(req, options) {
    req.scope = options.scope;
    return super.authenticate(req, options);
  }
}

//... further along ...///

new JWTScopeStrategy({
    passReqToCallback: true,
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: (Config as any).JWT_SECRET,
  }, (req, jwtPayload: any, cb) => {
    const user = getUser(qwtPayload);
    if (user.canScope(req.scope)) {
      cb(null,user);
    } else {
     cb(`Not allowed scope`)
    }
  });

// ... initializing ...//

app.use(  '/path', passport.authenticate('jwt', {session: false, scope: ['my_scope']}), myRouter );
hacker-DOM commented 5 years ago

+1

Flash619 commented 4 years ago

It would be useful to at the very least have a method of adding the scope claim value to the request, similar to how user is injected. I'm currently working with NestJS and am required to nest my scope array under my user object to access it in the request for my guards to work.

2coo commented 4 years ago

+1

Legion2 commented 3 years ago

I think how this an potentially other similar features can be made possible is to pass the options object of the authenticate method to the _verify callback method. Currently the options parameter is unused https://github.com/mikenicholson/passport-jwt/blob/96a6e5565ba5a6f3301d91959a0f646e54446388/lib/strategy.js#L90

I would open a PR for this, but I think this is a breaking change, because adding a new parameter to this callback will change the order and number of the existing callback parameter. @mikenicholson how would you like to handle this?

Outternet commented 2 years ago

May I ask why audience and issuer are not sufficient, in what senario is a scope needed that cannot be achieved with the previous one.