rkusa / koa-passport-example

koa-passport usage example
https://github.com/rkusa/koa-passport
262 stars 74 forks source link

Getting redirect loop while dooing facebook authentication #3

Closed bhanuc closed 10 years ago

bhanuc commented 10 years ago

Hi , I was trying to test the facebook integration but I get redirect loop when I try to login using facebook(after I successfully login) My routes are : //============================================= // route for facebook authentication and login //=============================================

    default_router.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));

    //=============================profile=================================
    // handle the callback after facebook has authenticated the user
    //==============================================================

        default_router.get('/auth/facebook/callback', parse,
            passport.authenticate('facebook', {
                successRedirect : '/app',
                failureRedirect : '/'
            }));

and my authenticate function is :

     passport.use(new FacebookStrategy({
clientID: authconfig.facebookAuth.clientID,
clientSecret: authconfig.facebookAuth.clientSecret,
callbackURL: authconfig.facebookAuth.callbackURL

},

// facebook will send back the token and profile
function(token, refreshToken, profile, done) {

    // asynchronous
    process.nextTick(function() {

        // find the user in the database based on their facebook id
        User.findOne({ 'facebook.id' : profile.id }, function(err, user) {

            // if there is an error, stop everything and return that
            // ie an error connecting to the database
            if (err)
                return done(err);

            // if the user is found, then log them in
            if (user) {
                return done(null, user); // user found, return that user
            } else {
                // if there is no user found with that facebook id, create them
                var newUser            = new User();

                // set all of the facebook information in our user model
                newUser.facebook.id    = profile.id; // set the users facebook id                   
                newUser.facebook.token = token; // we will save the token that facebook provides to the user                    
                newUser.facebook.name  = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
                newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first

                // save our user to the database
                newUser.save(function(err) {
                    if (err)
                        throw err;

                    // if successful, return the new user
                    return done(null, newUser);
                });
            }

        });
    });

}));
rkusa commented 10 years ago

What does your /app route (especially the logic ensuring a logged in user) look like?

bhanuc commented 10 years ago

@rkusa /app route is mounted on a 2nd router filtered by middleare that checks the the autentication of requests as shown below

      app.use(default_router.middleware());

            // =====================================
            // check the login ==============================
            // =====================================
        app.use(function* (next) {
          if (this.req.isAuthenticated()) {
            yield next;
          } else {
            this.redirect('/login')
          }
        });

        var secured = new Router();

        secured.get('/app', function* (){
            var userdetails = this.req.user;
            this.body = yield render('view.ejs',{ user : userdetails});
        })

        app.use(secured.middleware())

And here is the request flow from my browser http://s8.postimg.org/gbt0nmfqd/Screenshot_03082014_01_23_24_PM.png http://s8.postimg.org/vyka0ztid/Screenshot_03082014_01_22_10_PM.png

rkusa commented 10 years ago

What is the value of authconfig.facebookAuth.callbackURL?

bhanuc commented 10 years ago

@rkusa 'facebookAuth' : { 'clientID' : 670657392948407,//'your-secret-clientID-here', // your App ID 'clientSecret' : '1beefd26e84f7e7adb4eb8a371c41af8',//'your-client-secret-here', // your App Secret 'callbackURL' : 'http://localhost:3000/auth/facebook/callback' }

rkusa commented 10 years ago

Just saw, that I forgot to update the example to use koa-passport@0.2.0. Prior to this version you have to add this middleware:

app.use(function*(next) {
  this.req.query = this.query // connect compatibility
  yield next
})

So I think updating koa-passport to 0.2.0 or adding this middleware should solve your issue.

Please let me know if it works.

bhanuc commented 10 years ago

:+1: Works Awesome .. Thanks

bhanuc commented 10 years ago

@rkusa I sometime get this error Error at Strategy.OAuth2Strategy._createOAuthError (/home/bhanuc/web/dazer/node_modules/passport-facebook/node_modules/passport-oauth2/lib/strategy.js:340:17) at /home/bhanuc/web/dazer/node_modules/passport-facebook/node_modules/passport-oauth2/lib/strategy.js:173:43 at /home/bhanuc/web/dazer/node_modules/passport-facebook/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:162:18 at ClientRequest. (/home/bhanuc/web/dazer/node_modules/passport-facebook/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:133:5) at ClientRequest.EventEmitter.emit (events.js:104:17) at TLSSocket.socketErrorListener (_http_client.js:239:9) at TLSSocket.EventEmitter.emit (events.js:126:20) at net.js:888:16 at process._tickCallback (node.js:664:11) in the console and internal server error in the front end .Any help ?

rkusa commented 10 years ago

I am not able to reproduce this error :confused: Have you found a way to manually reproduce this error?

bhanuc commented 10 years ago

Actually Even I am not able to reciprocte ... I just restarted and it worked fine ... so I thought it might be some error that resulted from my code ... will keep an eye open for this one .. :+1: thanks btw