Git Product home page Git Product logo

passport-oauth2's Introduction

passport-oauth2

General-purpose OAuth 2.0 authentication strategy for Passport.

This module lets you authenticate using OAuth 2.0 in your Node.js applications. By plugging into Passport, OAuth 2.0-based sign in can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

Note that this strategy provides generic OAuth 2.0 support. In many cases, a provider-specific strategy can be used instead, which cuts down on unnecessary configuration, and accommodates any provider-specific quirks. See the list for supported providers.

Developers who need to implement authentication against an OAuth 2.0 provider that is not already supported are encouraged to sub-class this strategy. If you choose to open source the new provider-specific strategy, please add it to the list so other people can find it.

๐Ÿง  Understanding OAuth 2.0 โ€ข :heart: Sponsors


Advertisement
Learn OAuth 2.0 - Get started as an API Security Expert
Just imagine what could happen to YOUR professional career if you had skills in OAuth > 8500 satisfied students


npm build coverage ...

Install

$ npm install passport-oauth2

Usage

Configure Strategy

The OAuth 2.0 authentication strategy authenticates users using a third-party account and OAuth 2.0 tokens. The provider's OAuth 2.0 endpoints, as well as the client identifer and secret, are specified as options. The strategy requires a verify callback, which receives an access token and profile, and calls cb providing a user.

passport.use(new OAuth2Strategy({
    authorizationURL: 'https://www.example.com/oauth2/authorize',
    tokenURL: 'https://www.example.com/oauth2/token',
    clientID: EXAMPLE_CLIENT_ID,
    clientSecret: EXAMPLE_CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/example/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ exampleId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));

Authenticate Requests

Use passport.authenticate(), specifying the 'oauth2' strategy, to authenticate requests.

For example, as route middleware in an Express application:

app.get('/auth/example',
  passport.authenticate('oauth2'));

app.get('/auth/example/callback',
  passport.authenticate('oauth2', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

Related Modules

Contributing

Tests

The test suite is located in the test/ directory. All new features are expected to have corresponding test cases. Ensure that the complete test suite passes by executing:

$ make test

Coverage

All new feature development is expected to have test coverage. Patches that increse test coverage are happily accepted. Coverage reports can be viewed by executing:

$ make test-cov
$ make view-cov

License

The MIT License

Copyright (c) 2011-2016 Jared Hanson <http://jaredhanson.net/>

passport-oauth2's People

Contributors

cwspear avatar enzy avatar itsjw avatar jaredhanson avatar natalan avatar pdehaan avatar ptmt avatar quentin-danjou avatar sjudson avatar suprememoocow avatar tomhughes avatar tsabolov avatar tug avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

passport-oauth2's Issues

Refresh access token?

Should it automatically get new access token using refresh token when access token is expired? Or at least provide an API to do so?

Bearer token question

Hi,

I have a question regarding the token when its successfully retrieved after the user is authorised. I assume the token gets added to the headers? Does it get add as a Bearer Authorisation token? Or do I need to add in extra logic to accomplish this?

Thanks

TokenError

My OAuth2-Server emits this error Message:

{ statusCode: 400, data: '{"error":"invalid_client"}' }

whenever there is something wrong with app id or app secret. This leads to a very prominent and ugly error message for the user(s) (right in the browser):

TokenError
at OAuth2Strategy.parseErrorResponse (/app/node_modules/passport-oauth2/lib/strategy.js:320:12)
at OAuth2Strategy._createOAuthError (/app/node_modules/passport-oauth2/lib/strategy.js:367:16)
at /app/node_modules/passport-oauth2/lib/strategy.js:166:46
at /app/node_modules/oauth/lib/oauth2.js:195:7
at passBackControl (/app/node_modules/oauth/lib/oauth2.js:125:9)
at IncomingMessage. (/app/node_modules/oauth/lib/oauth2.js:143:7)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)

What can be done, that I can either catch this error or at least have it be less end-of-the-worldy for the app users?

Error in strict mode

I'm on io.js that is run with --use_strict parameter. My script fails with the following error when trying to sign in with google OAuth2:

Error.captureStackTrace(this, arguments.callee);
                                         ^
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
    at new InternalOAuthError (/Users/konstantintsabolov/dev/node-boilerplate/node_modules/passport-google-oauth/node_modules/passport-oauth/node_modules/passport-oauth2/lib/errors/internaloautherror.js:15:42)

As the error said, it's because of accessing arguments.callee in the InternalOAuthError constructor. Do you plan to refactor the code to make it strict-compatible?

Cannot use 'postmessage' as the callback url

On the client side, I'm using gapi to grab an authorization code from google and then passing that code to passport-google-oauth via a REST service.

Google is expecting passport to get an access token, by setting the callback to 'postmessage', otherwise a "redirect_uri_mismatch" error is returned (and yes all of my settings are correct in google's console). Unfortunately, the authenticate method on lines 140-148 (of passport-oauth2/lib/strategy.js) see 'postmessage' as a relative url and change it by calling url.resolve().

My question is, can I implement this change and forward over a pull request, or is this not something you see as an issue?

state query parameter drops out in v1.4.0 (used to work in v1.3.0)

The microservice that I am working on started failing during the oauth handshake because the state query parameter gets lost in the pipeline.
I noticed some changes in the params handling in the version upgrade of passport-oauth2 package from v1.3.0 to v1.4.0.

Here are some debugging info I can provide for now. Please let me know if you need anymore information.

NodeJS version: v6.9.1
Express version: v4.14.0

This is the options sent to the request:

{ 
  authorizationURL: 'https://localhost:3000/login/oauth/authorize?state=%2Ftoken',
  scope: 'openid cloud_controller.write cloud_controller.read',
  response_type: 'code',
  redirect_uri: 'https://localhost:5000/auth/callback' 
}

The request used to result in the following redirect location in v1.3.0:

https://localhost:3000/login/oauth/authorize?state=%2Ftoken&scope=openid%20cloud_controller.write%20cloud_controller.read&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A5000%2Fauth%2Fcallback&client_id=test

However, it is redirected to the following:

https://localhost:3000/login/oauth/authorize?authorizationURL=https%3A%2F%2Flocalhost:3000%2Flogin%2Foauth%2Fauthorize%3Fstate%3D%252Ftoken&scope=openid%20cloud_controller.write%20cloud_controller.read&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A5000%2Fauth%2Fcallback&client_id=test

Formerly those extra query params were merged into the authorizationURL which would preserve state query param.
Now it's attaching the whole url with state query param, as authorizationURL query param, to the parsed url href (https://localhost:3000/login/oauth/authorize in this case).
As a result, the redirect location no longer has state query parameter in the url causing an issue whenever it is returned back to the callback url (redirect_uri) after the authentication.

Is this an expected behavior/change for v1.4.0? Please let me know if this change is something that I need to modify on my side to stay on track.

Profile info of user empty

I am connecting my node app to Microsoft Outlook using passport-oauth2 where I am experiencing some major error where it asks for permissions from the user and take me to redirectURL but it is not able to get me the profile info of user and return an empty object of profile.Below is some of my code i used:

passport.js

const OutlookStrategy=require('passport-oauth2').Strategy;
passport.use(new OutlookStrategy({

authorizationURL: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
tokenURL: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
clientID: configAuth.outlookAuth.clientID,
clientSecret: configAuth.outlookAuth.clientSecret,
callbackURL: configAuth.outlookAuth.redirectURL
},
function(accessToken, refreshToken, profile, cb) {
console.log(accessToken);
console.log(profile); <-------------- This is empty object-------------------------|
console.log(refreshToken);
console.log(cb);

}
));

routes.js

router.get('/auth/outlook',
passport.authenticate('oauth2',{
scope: outlookScope
})
);

router.get('/auth/outlook/callback',
passport.authenticate('oauth2',{
failureRedirect: '/' }),
function(req, res) {
// Successful authentication, redirect home.
// var authCode = req.code;
res.redirect('/account');
});

OAuth 2 url parameters

there currently isn't support for adding values to the URL parameters, when the oauth2 lib makes the initial oauth call

i would like to add access_type=offline for example

Passing user specified parameter to authorizationParams()

Hello.

My oauth2 provider handles multiple idP(s), and I can specify which one to use by setting "selected_idp" parameter to authorize URL

http://www.cilogon.org/oidc

I see that I can add arbitrary parameters to authorize URL by overriding authorizationParams() function, but this function doesn't allow accessing user request parameter.

Can you add an additional option parameter to authenticate() so that I could do something like

router.get('/signin', function(req, res, next) {
    passport.authenticate('oauth2', {
        authorize_params: function() {
            return {selected_idp: req.query.idp}
        }
    })(req, res, next);
});

??

dynamic authorizationUrl

flickr uses a so called frob that has to be included in the authorization request url. i think it has to be different for each authorization request, therefore it must be retrieved everytime the authorizationUrl is returned.
is there a convenient way to do so right now? if not, would it be possible to make the authorizationUrl option a function?

see 9.2 Not web-based applications

Doc is not up to date about "callback" or strategy does not respoect passport usage

I can see this example in the README

app.get('/auth/example/callback',
  passport.authenticate('oauth2', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

But, when I'm using this passport strategy, the success function is called with a user object, the same I give to the done function from the verify function.

I dont know why this strategy translate call to verify done like this https://github.com/jaredhanson/passport-oauth2/blob/master/lib/strategy.js#L176

          function verified(err, user, info) {
            if (err) { return self.error(err); }
            if (!user) { return self.fail(info); }
            self.success(user, info);
          }

but that's quite surprising and non passport standard, or maybe that's caused by a change from passport?

response_type hard coded

I'm implementing a passport provider for visual studio online and they use response_type=Assertion (docs @ https://www.visualstudio.com/en-us/docs/integrate/get-started/auth/oauth ). Unfortunately passport-oauth2 hardcodes response_type=code. Would you be open to a pull request that allows derived strategies to override the response_type? I got my passport provider working by just copying the entire authorize implementation, but it seems like I shouldn't have had to do that.

https://github.com/mattdot/passport-visualstudio/blob/master/lib/strategy.js

How to set proxy in passport-oauth2

I see there is one option to set proxy.
Is it possible to do the follwing in passport-oauth2

Steps

I would like to add httpsProxyAgent to node-auth. Does the current implementation has option to add agent option to node-oauth.

This is what I would need...

var HttpsProxyAgent = require('https-proxy-agent');
if (process.env['https_proxy']) {
httpsProxyAgent = new HttpsProxyAgent(process.env['https_proxy']);
}

Finally, set the httpsProxyAgent to the request options right before _executeRequest gets called like this:

options.agent = httpsProxyAgent

Pass through response from server

In node-oauth, the changelog states the following:

0.9.7
OAuth2: Pass back any extra response data for calls to getOAuthAccessToken (Thanks to Tang Bo Hao)

This change is not respected/followed by passport-oauth2 in that these parameters are not plummed through to _loadUserProfile and other related functions. Additional data passed back from the server beyond just the access token should be given to the user-controlled functions as well.

this._oauth2.getOAuthAccessToken(code, params,
  function(err, accessToken, refreshToken, params) {
    if (err) { return self.error(self._createOAuthError('Failed to obtain access token', err)); }

    self._loadUserProfile(accessToken, function(err, profile) { // <--- Should pass additional data

Happy to submit a pull request if this is deemed worth addressing!

npm test error

I am not able to run npm test

[email protected] test C:\folder1\pp-oauth2
node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/.t
est.js test/__/
.test.js

'node_modules' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! weird error 1
npm ERR! not ok code 0

Question about oauth2 and user session

Hey all,

I'm using this module to integrate with an OAuth 2.0 server. Everything works fine, but as part of the login, I want to simple store the access_token in the express session, and do not authenticate again till the token expires.

Which is the recommended way to handle this? Because I have read the code, and I didn't found a way to manage this in a clear way. Should I use 2 authentication strategies (first check in the session, and if the data is not present, just use the oauth2 strategy)?

Thanks in advance

Undocumented Strategy constructor options

Looking through the code trying to figure out how to do CSRF state values, I noticed a bunch of undocumented options in the Strategy constructor:

customHeaders
scope
scopeSeparator
state
sessionKey
proxy
skipUserProfile

Any reason they're not documented? state seems particularly important.

Resource parameter is missing in the authorization request.

I'm attempting to authenticate against ADFS 3.0 OAuth2 provider. I'm receiving an error:
The resource parameter is missing in the authorization request. Send the resource parameter that contains the resource identifier's value.
I can't find a way in the passport-oauth2 strategy to pass additional parameters.

I was able to fix this by adding an option:
resource: EXAMPLE_CLIENT_SECRET

and in the strategy.js I had to add:

OAuth2Strategy.prototype.authorizationParams = function(options) { return { resource: options.resource}; };

Problem I'm having is changing the strategy.js get's blow away during my CI deploy. Is there away to set this when creating a new OAuth2Strategy?

Getting AccessToken + RefreshToken + Profile back from an oAuth2 request

My understanding of Passport callbacks is a little underdeveloped, so apologies in advance.

I'm trying to log in to Gmail using the passport-oauth2 strategy. Here's my code:

passport.use(new OAuth2Strategy({
        authorizationURL: 'https://accounts.google.com/o/oauth2/auth',
        tokenURL: 'https://accounts.google.com/o/oauth2/token',
        clientID: configAuth.googleAuth.clientID,
        clientSecret: configAuth.googleAuth.clientSecret,
        callbackURL: configAuth.googleAuth.callback2
      },
      function(accessToken, refreshToken, profile, done) {
        process.nextTick(function() {
            console.log("Token is ");
            console.log(util.inspect(accessToken, false, null));

            console.log("Refresh is ");
            console.log(util.inspect(refreshToken, false, null));
            console.log("Profile is ");
            console.log(util.inspect(profile, false, null));
        });
      })
    );

This gives me:

Token is 
undefined
Refresh is 
{ access_token: '{an access token}',
  token_type: 'Bearer',
  expires_in: 3599,
  id_token:'{a really long string}' }
Profile is
{}

If I make the callback function the following

function(req, token, refreshToken, profile, done) {}

Then I get back:

Token is 
'{access token}'
Refresh is 
undefined
Profile is
{}

Any ideas on what I'm doing wrong here? Is the callback reliant on the order of objects being requested, like:

function(foo, bar, moo, mah){
  // foo = accesstoken
  // bar = refreshtoken
  // moo = profile
  // mah = done
}

Or does it just pass in whatever objects you call for (so order is not important?)

Error: unable to verify the first certificate

Hi. My org uses an internal oauth2 implementation with our own internal certificates and CAs - which are obviously not part of nodejs's default truststore.

The first call to authenticate successfully (in "app.get('/'....") work fine as my browser is redirected to the ID provider to enter or check my creds. The second call to authenticate (in "app.get('/callback'...") fails because the POST to validate the token is done by nodejs/express (not my browser).

I'm looking for any advice on how I can get the the passport-oauth family of packages to respect a new truststore? Would it require code change/PR on this repo or is it possible to set those options more globally?

Getting data from resources server by only the Authorization header with bearer token

Can I use the bearer token to retrieve data from resources server (some OAuth2 provider's resources server, let's name it "Foo Bar") with the same passport strategy directly?

Assume I have configured the following passport strategy in my web application:

passport.use('fooBar', new OAuth2Strategy(fooBarPassportConfig,
  function (req, accessToken, refreshToken, profile, done) {
    ...
  }
));

I want something like:

myApiRoute.use('/*', function (req, res, next) {
  passport.authenticate('fooBar')(req, res, next);
});

When HTTP request comes to myApiRoute, I first lookup my database to find who is it, then get his bearer token and go through the fooBar strategy to try to get the latest profile from Foo Bar, then I can access to req.user in my controllers and models.

I tried the above code, but no luck.

usage with connect-ensure-login not honoring returnTo from session?

Forgive me if I am misunderstanding how these pieces fit together. I am attempting to use passport-oauth2 along with connect-ensure-login.

I have a secured route:

// secured route
app.get('/secured',
  login.ensureLoggedIn('/auth/example'),
  function(req,res) {
    res.send('secured');
  });

I have the following authorization routes, per the readme:

app.get('/auth/example',
  passport.authenticate('oauth2'));

app.get('/auth/example/callback',
  passport.authenticate('oauth2', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/');
  });

However, I wish to use connect-ensure-login's session.returnTo feature, so that any route that requires the user to be logged in can be redirected back to once the oauth flow is complete, instead of having the login route always redirect to "home" or some other URL. I've taken a peek at the source of this module, but I am still a bit new to the passport library in general, so it's possible I'm missing how to get this to work. Is this possible?

Thanks

Ability to specify response_type?

integrating with Basecamp it generates this URL

https://launchpad.37signals.com/authorization/new?response_type=code&redirect_uri=&client_id=MYCLIENTID

which yields this response from Basecamp:

:error: "Unsupported type: nil. We support user_agent and web_server."

Is it possible to specify a different response type in Passport Oauth2?

No mechanism to verify state param from authenticate options

One can set state param in OAuth2Strategy constructor options.
this._state = options.state;

Then it will be verified:

if (this._state) {
  ...
  if (state !== req.query.state) {
    return this.fail({ message: 'Invalid authorization request state.' }, 403);
  }
}

But if I set state in authenticate call options

function(req, res, next) {
  var options = {
    state: req.csrfToken()
  };
  return passport.authenticate('facebook', options)(req, res, next);
}

it will not be verified and there is no possibility to do that by myself, request automaticaly goes to provider for access_token

For example let's check it on facebook
Request to
http://localhost:3000/fb/callback?code=SHOULD_NEVER_BE_CHECKED&state=something
should throw an exception "incorrect state" but I see facebook "incorrect code format" message instead

Oauth error gets buried

Issue
Strategy's loadUserProfile reports a generic error without context to what happened.

Cause
It appears that the first callback argument to node-oauth's getOAuthAccessToken
isn't intended to report back oauth errors

So when for example oauth server returns "error=bad_verification_code&error_description=The+code+passed+is+incorrect+or+expired.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fv3%2Foauth%2F%23bad-verification-code"

  1. the passport callback is called with null as error and undefined as access_token and refresh_token.
  2. "if(err)" is skipped and self._loadUserProfile is called with undefined accessToken
  3. a generic error is returned ('failed to fetch user profile' in this case) and the original cause is buried.

Solution?
Shouldn't getOAuthAccessToken callback do "if (err || params['error'])" and pass "err || params" to _createOAuthError?

Using passport-oauth2 to gain OAuth2 support for Twitter auth

As passport-twitter still goes for OAuth v1, I decided to try with passport-oauth2 to accomplish Twitter login with out sessions for my app.

This is what I tried:

passport.use(new OAuth2Strategy({
    authorizationURL: 'https://api.twitter.com/oauth/authenticate',
    tokenURL: 'https://api.twitter.com/oauth/access_token',
    clientID: process.env.TWITTER_FINALCUT_CONSUMER_KEY,
    clientSecret: process.env.TWITTER_FINALCUT_CONSUMER_SECRET,
    callbackURL: 'http://localhost:9248/auth/login/redirect/tw'
    },
    function (access_token,refreshToken,profile,done) {
        console.log(accessToken,Object.keys(profile));
        return done(null, profile, {tokens: {accessToken: accessToken, refreshToken: refreshToken}});
}));

However when reaching the url for starting the auth process, I'm redirected to this Twitter screen. I can't figure out what's wrong with what I'm doing.

Any suggestions?

enter image description here

customHeaders option and default POST data conflict

I have to use customHeaders to send a Authorization header during the getAccessToken call.
this header contain base64 clien_id:client_secret.

It work very well and thanks for this usefull option.

But the problem is that the OAuth2 server reject my request with a 403 because the parameters client_id and client_secret are sent in the post_data too.

Is there any way to avoid this behavior ?

I have see nothing in the source for this. Do you think this use case deserve to add a new options ?

Dynamic clientID and clientSecret

My app allows many different domains to be used so I need to store clientID and clientSecret in the database with each domain in the database. Can you give me pointers on what I'd need to do to make this work in passport?

After looking at the code for passport-facebook, passport-oauth2 and node-oauth2 then it looks like I would have to change those to somehow reset the oauth2 object with the dynamically on each authorize call in a similar place as the dynamic callbackURL is supported.

pass options to authenticate

For a less than standard OAuth implementation, I needed an additional GET param added to the authorization url. After some pocking around, I found, that simply adding an options object to the passport.authenticate('oauth2', {options}) call, would be enough. But you don't pass them through to the oauth2 module. If I changed this return {}; to return options; it would work.
Do you consider this a good idea?

Support for meta-redirect instead of 302 redirect

In some unusual circumstances, we'd like to do a "meta-redirect" instead of the standard HTTP redirect. I.e. serve a 200 response with a meta tag and http-equiv=refresh to trigger the browser to load the authorizationUrl.

<html><head><meta http-equiv="refresh" content="0;url=#{authorizationUrl}"></head><body></body></html>

Something like specifying an option would be great:

passport.use(new OAuth2Strategy({
    authorizationURL: 'https://www.example.com/oauth2/authorize',
    tokenURL: 'https://www.example.com/oauth2/token',
    clientID: EXAMPLE_CLIENT_ID,
    clientSecret: EXAMPLE_CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/example/callback",
    redirectMethod: "meta-refresh" // This would trigger this behavior
  }

Specifically, we're seeing redirects blocked by appcache as described here and this method of redirect would allow us to work around it. As far as I can tell, there's no security constraints. Let me know if I'm missing anything.

Dynamic redirect_uri from queryString ?

It is common that login page with a param url=xxx, will jump to url after login successfully.

Now callbackURL is static, could only be configured as a unique value.

Maybe it's better if it can have some dynamic param from url query string.

Additional 'meta' options to expand on scope

First off thanks for the work you've done on these strategies!

I'm working with a custom oAuth2 strategy sub-classed off of this and the Github strategy. Everything works great for basic retrieval of profile information but there are some scopes that require additional authorization parameters in a meta field. The oAuth is for a payment provider Coinbase. This is a sample callback URL they are expecting with the scope and additional parameters:

https://www.coinbase.com/oauth/authorize?
    response_type=code&
    client_id=YOUR_CLIENT_ID&
    redirect_uri=YOUR_CALLBACK_URL&
    scope=wallet:transactions:send&
    meta[send_limit_amount]=50&
    meta[send_limit_currency]=USD&
    meta[send_limit_period]=day

I tried a couple different ways to add the parameters, including as just another option parameter and even hardcoding the URL but neither were accepted. I was wondering if you had any recommendations for how to extend this class to accept additional parameters?

Wrong client secret silently fails to authenticate

I had a problem where my client secret had a trailing newline. When the client secret doesn't match, authentication validation on the client side of course fails, but there is no indication of what happened. I couldn't find any way to get any kind of debugging or error output without hacking up the source. There should be a clear indicator that the client secret is the problem, other than packet-tracing and decrypting traffic between client and oauth2 server.

Dynamic token URL?

I'm writing an oAuth 2.0 flow for integrating with Vend POS and they return a domain_prefix along with the authorization code which is supposed to be used as a subdomain when requesting an access token i.e https://{domain_prefix}.vendhq.com/api/1.0/token. What's the best way of achieving that?

Vend docs: https://developers.vendhq.com/documentation/oauth.html

response_type is hardcoded to 'code'

I'm working on a strategy for VisualStudioOnline and need to change the response_type for the Authenticate request.

According to their documentation the request_type value needs to be 'Assertion' rather than 'code.'

The base strategy set the params.response_type after the authorizationParams are provided so I don't see how I can set it without duplicating the entire method in my strategy. Am I missing something simple?

Is this project active?

Based on the information I see on github, this project feels like "without support". Could you please tell me the current status?

Thanks!

req.query no longer an object, but a function

Hey there,

Noticed you turned passport-oauth into a meta package, neat! I'm trying to get this set up to authorize against an oauth2orize endpoint, and I'm running into a problem.

In short, I'm stuck at the authorize dialog, and even though the code is sent back to the callback, the callback sends me right back to the dialog again.

Upon inspection of the code, I found this conditional:

  if (req.query && req.query.code) {

... which kickstarts the code-to-token exchange (I hope), but if not matched, would restart the auth process over again (sounds familiar, no?)

So I added a console.log:

console.log(req.query);

and got this:

function getQuery() {
  if (this._query !== undefined)
    return (this._query);

  this._query = this.getUrl().query || {};
  return (this._query);
}

Function?

console.log(req.query()); // code=BneCqI...


  • I know it's not oauth2orize, because I cloned it straight from the repo, cd'd into the example app, and ran it.
  • Perhaps this is because I am running express 4?

The 'resource' parameter is missing in the authorization request.

I'm trying to implement SSO (single sign on) using passport-oauth2 generic strategy.

First I configure passport:

var passport = require('passport');
var OAuth2Strategy = require('passport-oauth2').Strategy;

passport.use('oauth2', new OAuth2Strategy({
      authorizationURL: 'provider/adfs/oauth2/authorize',
      tokenURL: 'provider/adfs/oauth2/token',
      clientID: 'my-id ,
      clientSecret: 'secret',
      callbackURL: 'https://localhost:44301/sso/consume'
    },
    function (accessToken, refreshToken, profile, done) {
      done(null, profile);
    }
));

then I specify 2 endpoints:

first:

app.get('/auth', passport.authenticate('oauth2'));

and second:

app.get('/sso/consume',
passport.authenticate('oauth2', { successRedirect: '/success', failureRedirect: '/fail' }));

And as it's said in passport docs I initialize passport:

app.use(passport.initialize());

The first round goes alright (I think) because browser gets redirected to my callbackURL ('sso/consume')

but on that page I see this error:

AuthorizationError: MSIS9601: The 'resource' parameter is missing in the authorization request.     Send the 'resource' parameter that contains the resource identifier's value.
   at OAuth2Strategy.authenticate (c:\epark\web-ui\node_modules\passport-oauth2\lib\strategy.js:126:25)
   at attempt (c:\epark\web-ui\node_modules\passport\lib\middleware\authenticate.js:348:16)
   at authenticate (c:\epark\web-ui\node_modules\passport\lib\middleware\authenticate.js:349:7)
  at Layer.handle [as handle_request] (c:\epark\web-ui\node_modules\express\lib\router\layer.js:95:5)
   at next (c:\epark\web-ui\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (c:\epark\web-ui\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (c:\epark\web-ui\node_modules\express\lib\router\layer.js:95:5)
   at c:\epark\web-ui\node_modules\express\lib\router\index.js:277:22
   at Function.process_params (c:\epark\web-ui\node_modules\express\lib\router\index.js:330:12)
   at next (c:\epark\web-ui\node_modules\express\lib\router\index.js:271:10)

Do you know what is causing this issue?

Can't get full response in callback

passport.use('oAuth2', new OAuth2Strategy(
{
authorizationURL: '...',
tokenURL: '...',
clientID: '...',
clientSecret: '...',
callbackURL: '...'
},
function(accessToken, refreshToken, profile, done) {
// Here i get arguments accessToken and refreshToken,
// empty profile ({}) and cb done
// but oauth lib got with access_token so much more params
// [
// 'access_token',
// 'expires_in',
// 'refresh_expires_in',
// 'refresh_token',
// 'token_type',
// 'id_token',
// 'not-before-policy',
// 'session_state'
// ]
// and i can't get their in this callback
}
));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.