mikenicholson / passport-jwt

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

JwtStrategy.prototype.authenticate should check the return type of self._jwtFromRequest(req) for more complex token retrieval scenarios. #186

Open sbaker opened 5 years ago

sbaker commented 5 years ago

https://github.com/mikenicholson/passport-jwt/blob/6b92631dfbde7143b9e046093dbf332107bce82e/lib/strategy.js#L93

options._jwtFromRequest may return a Promise in some scenarios.

Currently, We issue reference tokens that basically are pointers to the actual JWT on our IDP. I have to make an HTTP call to our IDP for exchanging the reference token for the actual JWT forcing me to return a promise.

const jwtFromAuthHeader = ExtractJwt.fromAuthHeaderAsBearerToken();
const jwtReferenceTokenToJwtExchange = async req => {
  var referenceToken = jwtFromAuthHeader(req)
  const body = "reference_token=${referenceToken}&token=${referenceToken}&client_id={{CLIENT_ID}}&client_secret={{CLIENT_SECRET}}&grant_type=exchange&scope={{SCOPES}}";
  var response = await axios.post(opts.openidConfig.token_endpoint, body, {"headers": {"Authorization": "Bearer ${referenceToken}"}});
  return response.data.access_token;
}

const opts = {
  jwtFromRequest: jwtReferenceTokenToJwtExchange,
  issuer: process.env.IDP_URL,
  passReqToCallback: true,
  secretOrKeyProvider: secretOrKeyProvider,
  algorithms: []
}
canslaughter commented 2 years ago

There is no need to add this functionality. You could simply add a custom middleware that performs any async task you need, then put the result in the request object. Finally, extract the custom req field inside jwtFromRequest and return it so passport-jwt can process it.

sbaker commented 2 years ago

I agree it can be done that way as well as others. In knowing what I've learned I think that this functionality is and will be needed . This PR doesn't change any existing functionality only adds more flexibility for the developer.