GithubHelp home page GithubHelp logo

jaredhanson / passport-github Goto Github PK

View Code? Open in Web Editor NEW
535.0 19.0 289.0 68 KB

GitHub authentication strategy for Passport and Node.js.

Home Page: https://www.passportjs.org/packages/passport-github/?utm_source=github&utm_medium=referral&utm_campaign=passport-github&utm_content=about

License: MIT License

JavaScript 99.65% Makefile 0.35%

passport-github's People

Contributors

4lejandrito avatar alyssais avatar edlea avatar genbit avatar jaredhanson avatar mattbornski avatar okhomenko avatar pdehaan avatar rragan avatar simison avatar suprememoocow 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  avatar  avatar  avatar

passport-github's Issues

TypeError: Cannot read property '0' of undefined

Hi, I use the development of the account test is no problem, but the use of other non developer account landing on this issue

GET /auth/github 302 7.058 ms - 0
events.js:141
throw er; // Unhandled 'error' event
^

TypeError: Cannot read property '0' of undefined
at /Applications/XAMPP/xamppfiles/htdocs/html/baoniu-voting-app/config/passport.js:75:62
at Query. (/Applications/XAMPP/xamppfiles/htdocs/html/baoniu-voting-app/node_modules/mongoose/lib/model.js:3352:16)
at /Applications/XAMPP/xamppfiles/htdocs/html/baoniu-voting-app/node_modules/mongoose/node_modules/kareem/index.js:244:21
at /Applications/XAMPP/xamppfiles/htdocs/html/baoniu-voting-app/node_modules/mongoose/node_modules/kareem/index.js:127:16
at nextTickCallbackWith0Args (node.js:415:9)
at process._tickCallback (node.js:344:13)

有关认证的逻辑

想请教一下,授权码模式下,在第一步认证,在第一步认证的时候,就是走authorize的请求的时候,可不可以是post的形式请求,我想post形式传递一些必要的参数

Does passport-github provide secure authentication?

The README says this module "authenticates users using a GitHub account and OAuth 2.0 tokens", but sites like https://oauth.net/articles/authentication/ warn against using OAuth tokens for authentication:

OAuth APIs do not provide any mechanism of audience restriction for the returned information. In other words, it is very possible to take a naive client, hand it the (valid) token from another client, and have the naive client treat this as a "log in" event. After all, the token is valid and the call to the API will return valid user information. The problem is of course that the user hasn't done anything to prove that they're present, and in this case they haven't even authorized the naive client.

Is passport-github safe to use in spite of this warning?
I asked essentially the same question here: http://security.stackexchange.com/questions/140595/is-it-safe-for-users-of-my-api-to-sign-in-with-github-using-passport-github

GitHub Enterprise Support

Can this be generalized a bit to work with GitHub Enterprise? Things are pretty similar except that urls look like https://corpGitHubDomain/api/v3/......

The only place that needs changing appears to be:

Strategy.prototype.userProfile = function(accessToken, done) {
this._oauth2.get('https://api.github.com/user', accessToken, function (err, body, res) {
if (err) { return done(new InternalOAuthError('failed to fetch user profile', err)); }

If that url can be supplied as an option, then it works fine with our corporate GitHub.

Maybe something like this in function Strategy

this.userProfileURL = options.userProfileURL || 'https://api.github.com/user';

and change the reference to:

this._oauth2.get(this.userProfileURL, accessToken, function (err, body, res) {

npm publish 0.1.7

The last version available on npmjs is the 0.1.5 and this repo is 0.1.7, could you please publish it ?

Use the Authorization HTTP header instead of `access_token` query parameter

Today I got an email containing the following.

Hi @timqian,

On February 3rd, 2020 at 22:22 (UTC) your application (repo-analytics) used an access token (with the User-Agent passport-github) as part of a query parameter to access an endpoint through the GitHub API:

https://api.github.com/user/emails

Please use the Authorization HTTP header instead as using the access_token query parameter is deprecated.

Depending on your API usage, we'll be sending you this email reminder once every 3 days for each token and User-Agent used in API calls made on your behalf.
Just one URL that was accessed with a token and User-Agent combination will be listed in the email reminder, not all.

Visit https://developer.github.com/changes/2019-11-05-deprecated-passwords-and-authorizations-api/#authenticating-using-query-parameters for more information.

Thanks,
The GitHub Team

InternalOAuthError: failed to fetch user profile

Hello i'm having this issue before GitHub Authentication

InternalOAuthError: failed to fetch user profile
   at /home/matheus/.src/ContactList/node_modules/passport-github/lib/passport-github/strategy.js:90:28
   at passBackControl (/home/matheus/.src/ContactList/node_modules/oauth/lib/oauth2.js:132:9)
   at IncomingMessage.<anonymous> (/home/matheus/.src/ContactList/node_modules/oauth/lib/oauth2.js:157:7)
   at IncomingMessage.emit (events.js:203:15)
   at endReadableNT (_stream_readable.js:1145:12)
   at process._tickCallback (internal/process/next_tick.js:63:19)

my passport code:

`const passport = require("passport");
const GitHubStrategy = require("passport-github").Strategy;
const Usuario = require("../app/models/Usuario");

module.exports = () => {
    passport.use(new GitHubStrategy({
        clientID: "My client Id",
        clientSecret: "My client secret",
        callbackURL: "http://localhost:3000/auth/github/callback"
    }, function(accessToken, refreshToken, profile, done) {
        Usuario.findOrCreate(
            {"login": profile.username},
            {"nome": profile.username},
            (erro, usuario) => {
                if(erro) {
                    console.log(erro);
                    return done(erro);
                }
                return done(null, usuario);
            }
        );
    }));

    passport.serializeUser((usuario, done) => {
        done(null, usuario._id);
    });

    passport.deserializeUser((id, done) => {
        Usuario.findById(id).exec()
        .then(usuario => {
            done(null, usuario);
        });
    });
}`

Thanks in advance

Failed to fetch user profile

After I configuration for my express4.x server with github, the server shows the error: Failed to fetch user profile.

error: at /root/passport-github/examples/login/node_modules/passport-github2/lib/strategy.js:96:19

Email

I get this:
emails: [ { value: undefined } ],
in response... so is it valid? because I need email info...

this is request:
app.get('/auth/github', passport.authenticate('github', { scope : "user:email"}));
and this is callback:
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function (req, res) { res.redirect('/'); });

Access token as query parameter is deprecated (cannot fetch emails)

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

GitHub has deprecated passing the access token as a query param and it should now be passed in the Authentication field of the headers. (https://developer.github.com/changes/2020-02-10-deprecating-auth-through-query-param/)

Here is the diff that solved my problem:

diff --git a/node_modules/passport-github/lib/strategy.js b/node_modules/passport-github/lib/strategy.js
index 0f4b07f..b036650 100644
--- a/node_modules/passport-github/lib/strategy.js
+++ b/node_modules/passport-github/lib/strategy.js
@@ -135,7 +135,8 @@ Strategy.prototype.userProfile = function(accessToken, done) {
 
     
     if (self._scope && self._scope.indexOf('user:email') !== -1) {
-      self._oauth2._request('GET', self._userProfileURL + '/emails', { 'Accept': 'application/vnd.github.v3+json' }, '', accessToken, function(err, body, res) {
+      self._oauth2.useAuthorizationHeaderforGET(true)
+      self._oauth2.get(self._userProfileURL + '/emails', accessToken, function(err, body, res) {
         if (err) {
           // If the attempt to fetch email addresses fails, return the profile
           // information that was obtained.

This issue body was partially generated by patch-package.

Stateless example (or bug?)

Do you know how we can get the token in /auth/github/callback? I'm not sure how to proceed if not...is there another example on how this would be achieved? To make the call to /login/oauth/access_token in the callback there with the code parameter is marked as expired, presumably because it was already used earlier (I'm guessing).

Please deprecate this package in favor of `passport-github2`

Hello @jaredhanson - can you please deprecate this per #15 (comment)?

You will need to do the following:

  • npm deprecate passport-github "This package is deprecated and no longer maintained. Please use passport-github2 instead"
  • Archive the repository on GitHub and put a notice at the top of README in the GitHub description of "This package is deprecated and no longer maintained. Please use passport-github2 instead"

InternalOAuthError: Failed to fetch user profile

While putting my app that uses passport Github on production I got this issue:

InternalOAuthError: Failed to fetch user profile
    at /app/node_modules/passport-github2/lib/strategy.js:98:19
    at passBackControl (/app/node_modules/passport-github2/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:123:9)
    at IncomingMessage.<anonymous> (/app/node_modules/passport-github2/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:142:7)
    at IncomingMessage.emit (events.js:129:20)
    at IncomingMessage.wrapped (/app/node_modules/newrelic/lib/transaction/tracer/index.js:157:28)
    at IncomingMessage.wrappedEmit [as emit] (/app/node_modules/newrelic/lib/transaction/tracer/index.js:201:46)
    at _stream_readable.js:908:16
    at wrapped (/app/node_modules/newrelic/lib/transaction/tracer/index.js:157:28)
    at process._tickDomainCallback (node.js:381:11)
    at process.wrappedFunction (/app/node_modules/newrelic/lib/transaction/tracer/index.js:271:51)

I can reach the github login page but it failed during the callback and gives me an Internal Server Error.
The app is well configured (clientID, clientSecret and callback url) plus I can't reproduce that on local.
Here are my scopes : { scope: ['read:org', 'user:email'] }

Any idea from where it can come from?

(I also tried passport github2, same issue)

InternalOAuthError: failed to fetch user profile

I am aware of this issue: #48

Though I'm not sure if they were having this specific message.

status: 403
message: Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.

But it seems this is different, and only appears on latest versions of node. It's happening when running on versions 5.8.0 and 5.9.1. Before that it had been working for me on version 4.2.4

I'm using version 0.1.5 of passport-github. Version 1.1.0 breaks with: _this.oauth2.useAuthorizationHeaderforGET is not a function so does passport-github2.

Probably, this problem is not specific to passport-github and more related to underlying libraries.

Thanks in advance. Any advice will be greatly appreciated.

Question - forwarding request info (headers/cookies) to servers in your farm

hi Jared, we are using passport with a couple of Node.js servers at a startup - but we have some questions about how to use passport with proxy requests.

We aren't currently using this exactly - but imagine for the moment that we are:
https://www.npmjs.com/package/express-http-proxy

Are you willing to provide any info as to best practices regarding a browser request to server A which in turn makes a request to server B - we want the same client to be authenticated in the same way on both servers. Currently if the web client makes a request directly to both servers, the client is authenticated, but if he authenticates with A and then A sends a request to server B, then of course, that second request contains none of the auth info that is needed to authenticate the client on server B.

Considering we own both servers A and B, should we just include the headers and cookies from the original request in our request from server A to B?

is this considered a good practice? Any info would be helpful, thanks!

Github Enterprise - InternalOAuthError: Failed to obtain access token

This might be an enterprise specific issue perhaps?

Here is my code

passport.js

passport.use(new GitHubStrategy({
    clientID: config.github.id,
    clientSecret: config.github.secret,
    callbackURL: 'http://127.0.0.1:3001/auth/github/callback',
    authorizationURL: 'https://github.our_domain.com/login/oauth/authorize'
  },
  function(accessToken, refreshToken, profile, cb) {
    console.log("accessToken==" + accessToken)
    User.findOrCreate({ githubId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));

server.js

app.get('/login/github',
  passport.authenticate('github', {session: false })
);

app.get('/auth/github/callback',
  passport.authenticate('github', { failureRedirect: '/login' }),
  (req, res) => {
    res.redirect('/');
  }
);

When I hit /login/github it bounces out to Github Enterprise, I give the app permissions, it then hits the callback and lands on http://127.0.0.1:3001/auth/github/callback?code=random_code with the above error.

Am I missing anything else? From what I understand (and I understand very little) it should obtain the token and I should be good to start hitting the GHE API.

Thanks!

'access_token' not present in the passport-github2 request

I have registered an OAuth App via my Github account. I am basically trying to authorize my node requests(by sending access_token as part of request cookies) so I can access few APIs on another server. Hence I am using the github-passport2 package. I have setup the github strategy etc. & it seems to be all according to the doc. The flow works well too.

My Issue

After logging into Github(authorized) & getting redirected back to my /auth/github/callback, I ideally should be authorized and should have an access_token in the req. But I don't have it! Because of this I am not able to authorize my future requests with an access_token.

Important to note is that, this access_token is automatically attached when the request is initiated from a browser/client(using withCredentials: true parameter). The same access_token via node doesn't seem to be retrievable.

passport.use(new GitHubStrategy({
    clientID: GITHUB_CLIENT_ID,
    clientSecret: GITHUB_CLIENT_SECRET,
    callbackURL: "http://localhost:8080/auth/github/callback",
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {
      return done(null, profile);
    });
  }
));

app.get('/auth/github', passport.authenticate('github', { scope: [ 'user:email' ] }), function(req, res){
  // The request will be redirected to GitHub for authentication, so this
  // function will not be called.
});

app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
  console.log(req); // <- This ideally should have the access_token? but doesn't
});

Any help is much appreciated

deserialize is never called..

Visiting /p/foo
Returns

[2015-06-22 22:15:02.736] [INFO] console - Trying to access a pad /p/foo
[2015-06-22 22:15:02.736] [WARN] console - isAuthenticated false
[2015-06-22 22:15:02.736] [WARN] console - passing back to auth as not authenticated
[2015-06-22 22:15:04.122] [INFO] console - successful auth through Github
[2015-06-22 22:15:04.123] [INFO] console - serialized user { provider: 'github', ...  omitted ...  }
[2015-06-22 22:15:04.128] [INFO] console - Redirecting back to home after succesful auth

Then trying to visit another pad without stopping / starting Etherpad or closing browser returns..

[2015-06-22 22:16:10.500] [INFO] console - Trying to access a pad /p/oWtSRH2g01
[2015-06-22 22:16:10.500] [WARN] console - isAuthenticated false
[2015-06-22 22:16:10.500] [WARN] console - passing back to auth as not authenticated
[2015-06-22 22:16:11.827] [INFO] console - successful auth through Github
[2015-06-22 22:16:11.827] [INFO] console - serialized user { provider: 'github',

So the isAuthenticated persistence isn't being kept

https://github.com/JohnMcLear/ep_oauth/blob/master/auth.js#L28 -- Am I okay to not use app.use(express.methodOverride()); and the other express calls in the example app?

These methods don't seem to be responsible for persistence.. I'm ultimately going to write to/read from the database layer but for now I want a clean sample/example to do proof of concept.

passport-oauth is at 0.1.x. Should be updated to latest.

Any chance it can be updated to the latest version of passport-oauth? I'm trying to use with passport-facebook, but it seems that my app likes to use the 0.1.x version libs instead of the latest when using passport-facebook, which breaks my app as my serializeUser does not get a res object.

Howto use it with Client / Server style ?

In Frontend i use a Backbone-MVC Application, this app call github authorize url and recieve the Answer (github code).

Then the Frontend-App post the Code to the Server-App, which should use passport-github to verify and load the data.

The backend use MVC-Style too, not directly call the passport functions in express-routes, example:

UserController.prototype.loginByGitHub = function(req, res)
{
  passport.authenticate("github", function(err, user, info) {
    console.log(err);
    console.log(user);
    console.log(info);
    // if ok login / register user
    // ....
  })(req, res);
};

One problem is in passport-oauth/strategies/oauth2.js
if (req.query && req.query.code) {
is always empty, because i post the data.

But if i change the line to
if (req.body && req.body.code) {
i got TypeError: Property 'next' of object # is not a function, line 128

Is there an ohter way to use the verification on the server-side with passport-github?

tokens not working

I am not sure if it's only with me or everyone has a problem with the package. My function never gets called? Is there a problem with the package?
This function never gets called:-

async (accessToken, refreshToken, userProfile, cb) => {
        console.log(userProfile);
        const profile = userProfile as unknown as UserProfile;
        let user = await getRepository(User).findOne({
          where: { githubId: profile.id },
        });

My code:-

    new GitHubStrategy(
      {
        clientID: process.env.ID,
        clientSecret: process.env.SECRET,
        callbackURL: "http://localhost:4000/graphql",
      },
      async (accessToken, refreshToken, userProfile, cb) => {
        console.log(userProfile);
        const profile = userProfile as unknown as UserProfile;
        let user = await getRepository(User).findOne({
          where: { githubId: profile.id },
        });
        if (!user) {
          user = await createUser({
            username: profile.username || "",
            email: profile.emails as unknown as string,
            githubId: profile.id,
            pictureUrl: profile._json.avatar_url,
          });
        }
        cb(null, {
          user,
          accessToken,
          refreshToken,
        });
      }
    )
  );```

"Unauthorized" when using example app

Hi Jared,

This is looking great, and I'm hopeful to use this in my app. One quick question, though (and this may be how I've set up my app on github).

When I run the example application included in the repo, and replace the GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET with my own credentials, after clicking Login with Github, it takes me to the following URL: http://localhost:3000/auth/github?error=redirect_uri_mismatch, and I get an Unauthorized error in the browser.

Obviously the error is a there's an inconsistency in the redirect_uri (which, from my understanding, is the "callback URL" on github's applications page).

So, what I did was make the callback URL on github's applications page blank, which I assumed would let me set it programmatically via the callbackURL parameter when initializing a new GitHubStrategy. But that's not working.

Do you have any ideas on what I may be doing wrong? I've tried to set the callbackURL on github's apps page and programmatically, but I'm still getting the redirect_uri_mismatch error.

Any help would be appreciated, and thanks for this!

Failed to access through accessToken

Maybe I understand wrongly the utility of the accessToken (first argument returned by the callback when creating the strategy) because when I am trying to sign in it does not work correctly:

var github = require('octonode');

passport.use(new Strategy({
  clientID: clientID,
  clientSecret: clientSecret,
  callbackURL: callbackURL
},
function(accessToken, refreshToken, profile, done) {
  var client = github.client(accessToken);
  // Client is not signed in...
}

passport-github always goes to failureRedirect

When I register through Github to my web app, I allow my app to access my profile. It writes my profile to the database no problem. But then I go to the failureRedirect on the client, which should not happen since I approved it.

Routes:

router.get('/github/callback', passport.authenticate('github', {
    failureRedirect: '/errorforsure'
}), function(req, res) {
    res.redirect('/');
});

router.get('/github', passport.authenticate('github', {
        scope: ['user']
}));

InternalOAuthError: Failed to fetch user profile

I got this error
InternalOAuthError: Failed to fetch user profile
at C:\Esercizi\node2\node_modules\passport-github2\lib\strategy.js:98:19
at ClientRequest. (C:\Esercizi\node2\node_modules\oauth\lib\oauth2.js:162:5)
at ClientRequest.emit (node:events:537:28)
at TLSSocket.socketErrorListener (node:_http_client:465:9)
at TLSSocket.emit (node:events:537:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

const githubStrategy = new passportGitHub2.Strategy(
{
clientID: config.CLIENT_ID,
clientSecret: config.CLIENT_SECRET,
callbackURL: config.CALLBACK_URL,
// skipUserProfile: true

},
function (
accesToken: string,
refreshToken: string,
profile: { [key: string]: string },
done: (error: null, user: Express.User) => void
) {
const user: Express.User = {
username: profile.username,
};

done(null, user);

}
);

I am afraid this fail and i don'know why
passport.authenticate("github", {
scope: ["user:email"],
})

I double checked the ID and secret and the call back url. It's all fine, even the call backurl is fine and I can contact github.
I am able to receive the login page of github, authorize the use but then i receive this error. Any clue?

Provide consented scopes in callback

Hi!

The Github API returns the consented scopes in a scope field along with the access token. It would be cool if this metadata was provided in the verification callback. This is useful in applications that deal with multiple access levels.

returning 404 error does not close the connection

im using passport.js for authentication of requests in my upload enpoints but there is an issue event if the user is unauthorized the multipart data is contiuning to send to server . there is a need to close the tcp connection during this senarios . and dont see a configuration for it yet

redirect back to specific address

Hi, currently I'm able to redirect the user to a "failureRedirect" and to a "successRedirect". Is it possible to redirect the user to the current route of the application? Like, I have the login button at the header and it's constant to every route of my application. Now, if a user is on a different route and try to log in, they are getting redirect to root route. I want to redirect them to the current route they are in at that point.

Could you please let me know if it's possible? I'm using the following code:

// github authentication route
app.get(
  '/api/user/authViaGitHub',
  passport.authenticate('github')
);

// callback route from github
app.get(
  // this should match callback url of github app
  '/api/user/authViaGitHub/callback',
  passport.authenticate('github', { failureRedirect: '/signIn/failed' }),
  (req, res) => { res.redirect('/'); }
);

I was thinking of sending a query with current route. But while the callback occurs, I'm not sure how should I redirect back according to the query since they are different requests.

Revoke?

Is there a way to revoke access?

TokenError: The client_id and/or client_secret passed are incorrect.

I write app demo just like the example code:

passport.use(new GitHubStrategy({
        clientID: process.env.GITHUB_CLIENT_ID as string,
        clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
        callbackURL: "http://127.0.0.1:3000/auth/github/callback"
    },
    function(accessToken, refreshToken, profile, callback) {
        return callback(null, {});
    }
));

passport.serializeUser((user, done) => {
    console.log('serializeUser');
    done(null, 1);
});

passport.deserializeUser((id, done) => {
    console.log('deserializeUser');
    done(null, {});
});

// app.use(helmet());
// app.use(cors());
app.use(express.json());
app.use(session({
    store: new MemoryStore({
        checkPeriod: 86400000 // prune expired entries every 24h
    }),
    secret: process.env.SESSION_SECRECT as string,
    resave: false,
    saveUninitialized: false,
    cookie: {
        secure: true,
        httpOnly: true,
    }
}));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(passport.initialize());
app.use(passport.session());

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

app.get('/auth/github/callback',
    passport.authenticate('github', { failureRedirect: '/login_failed' }),
    function(req, res) {
        res.redirect('/');
    });

however, when I try to login, I get the error:

TokenError: The client_id and/or client_secret passed are incorrect.
    at Strategy.OAuth2Strategy.parseErrorResponse (/Users/guangyi.li/Desktop/side-project/tenet/node_modules/passport-oauth2/lib/strategy.js:358:12)
    at Strategy.OAuth2Strategy._createOAuthError (/Users/guangyi.li/Desktop/side-project/tenet/node_modules/passport-oauth2/lib/strategy.js:405:16)
    at /Users/guangyi.li/Desktop/side-project/tenet/node_modules/passport-oauth2/lib/strategy.js:175:45
    at /Users/guangyi.li/Desktop/side-project/tenet/node_modules/passport-github/lib/strategy.js:79:16
    at /Users/guangyi.li/Desktop/side-project/tenet/node_modules/oauth/lib/oauth2.js:209:7
    at passBackControl (/Users/guangyi.li/Desktop/side-project/tenet/node_modules/oauth/lib/oauth2.js:134:9)
    at IncomingMessage.<anonymous> (/Users/guangyi.li/Desktop/side-project/tenet/node_modules/oauth/lib/oauth2.js:157:7)
    at IncomingMessage.emit (events.js:327:22)
    at IncomingMessage.EventEmitter.emit (domain.js:482:12)
    at endReadableNT (_stream_readable.js:1221:12)

It seem the issue happened here, the returned access token is undefined:

Snip20200803_12

but I found my github oauth already have one user, and the user also have the oauth app authorized. So what's wrong with my code ?

Failure flash

is there some option like
{ failureFlash: true }
in callback function ??

I would like to display custom message if, for example, saving user into db fails ...

Failed to fetch user profile (status: 401 data: {"message":"Requires authentication"})

Hi,

I just tried to use passport-github, it seems to be straightforward to implement. But I have an error that I don't understand.

I created an application on Github. I set the correct client id and client secret. And when I click signup with Github I have the following error:

GET /auth/github 302 2ms - 432
failed to fetch user profile (status: 401 data: {"message":"Requires authentication"})
    at Strategy.userProfile (/Users/yyyyyyy/Workspace/xxxxxxxx/node_modules/passport-github/lib/passport-github/strategy.js:90:28)
    at passBackControl (/Users/yyyyyyy/Workspace/xxxxxxxx/node_modules/passport-github/node_modules/passport-oauth/node_modules/oauth/lib/oauth2.js:105:9)
    at IncomingMessage.exports.OAuth2._executeRequest.request.on.callbackCalled (/Users/yyyyyyy/Workspace/xxxxxxxx/node_modules/passport-github/node_modules/passport-oauth/node_modules/oauth/lib/oauth2.js:124:7)
    at IncomingMessage.EventEmitter.emit (events.js:126:20)
    at IncomingMessage._emitEnd (http.js:366:10)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
    at CleartextStream.socketOnData [as ondata] (http.js:1367:20)
    at CleartextStream.CryptoStream._push (tls.js:526:27)
    at SecurePair.cycle (tls.js:880:20)
    at EncryptedStream.CryptoStream.write (tls.js:267:13)
GET /auth/github/callback?code=<a code> 500 872ms

However, the user seems to be correctly created: the application user counter (on Github) has been incremented to 1.

I think the error is on my side, do you have some idea to help me?

Thanks a lot for your work on passport

How to use passport-github in a REST API Architecture?

I am building a vue.js client which needs to be authenticated through github oauth using an express server. It's easy to do this using server side rendering but implementing it in REST API has been troublesome for me.

I have set the homepage url as "http://localhost:3000" where the server runs and I want the authorization callback url to be "http://localhost:8080" (which hosts the client). I am redirecting to "http://localhost:3000/auth/github/redirect" instead, and in its callback redirecting to "http://localhost:8080". The problem I am facing is that I am unable to send user data to the vuejs client through res.redirect. I am not sure if I am doing it the right way.

router.get("/github", passport.authenticate("github"));

router.get(
  "/github/redirect",
  passport.authenticate("github", { failureRedirect: "/login" }),
  (req, res) => {
    // res.send(req.user);
    res.redirect("http://localhost:8080/"); // req.user should be sent with this
  }
);

Nodejs Passportjs Reactjs CORS issue

Dear All I am using github login for my react.js application with passport github2 strategy
My React.js app is running on port 3000
and the Node.js server is running on port 5000

This is error I am getting when I try to login with github, please see the screenshot

image

Access to XMLHttpRequest at 'https://github.com/login/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2FXX.XX.71.24%3A5000%2Fapi%2Fv1%2Fauth%2Fgithub%2Fcallback&scope=user%3Aemail&client_id=f34f1df531540449d402' (redirected from 'http://XX.XX.71.24:3000/api/v1/auth/github') from origin 'http://XX.XX.71.24:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

CORS is enabled on my server as other endpoints are working fine
Here is the CORS settings

image

this my github app setting

image

Allow scope to be an array

It makes sense that we store a list of scope permissions as an array rather than a comma separated string.

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.