Search code examples
node.jsexpressoauth-2.0passport.js

passport-oauth2 client how to use profile data received


I have a stand alone oauth2 identity provider that is working. Now I'm developing a consumer that will authenticate users with this stand alone provider.

I'm following this tutorial about passport and Google Auth:

I'm trying to use this information to use passport-oauth2 to work as a client. I have made some changes in the code provided in the tutorial above by following the official documentation on passoprt-oauth2.

I think that I have some problem in the callback function where expressjs receive the confirmation of authentication and info about the user. I don't understand how to use this information.

Here is the code of my app.js

const express = require('express');

const app = express();

const passport = require('passport');
const OAuth2Strategy = require('passport-oauth2');
const cookieSession = require('cookie-session');

// cookieSession config
app.use(cookieSession({
    maxAge:24*60*60*1000,
    keys: ['secret-personalize']
}));


app.use(passport.initialize());
app.use(passport.session());

//Strategy config


passport.use(new OAuth2Strategy({
    authorizationURL: 'http://localhost:3000/dialog/authorize',
    tokenURL: 'http://localhost:3000/oauth/token',
    clientID: 'xyz123',
    clientSecret: 'ssh-password',
    callbackURL: "/auth/oauth2/callback"
  },

  (accessToken, refreshToken, profile, done) => {
    console.log(profile);
    done(null, profile);

  }
  ));
  // Used to decode the received cookie and persist session

  passport.deserializeUser((user, done) => {
    done(null, user);

  });

// Middleware to check if the User is authenticated

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


function isUserAuthenticated(req, res, next){

    if (req.user){
        next();
    } else {
        res.send('you must login!');
    }
}



// Routes

app.get('/', (req, res) => {

res.render('index.ejs');
});


// The middleware receives the data from AuthPRovider and runs the function on Strategy config

app.get('/auth/oauth2/callback', passport.authenticate('oauth2'), (req,res) => {
    res.redirect('/secret');
});



// secret route

app.get('/secret', isUserAuthenticated, (req, res) =>{

    res.send('You have reached the secret route');

});


// Logout route

app.get('/logout',(req, res) => {

    req.logout();
    res.redirect('/');

});

    app.listen(8000, () => {
        console.log('Server Started 8000');
    });

and this is for views/index.ejs

 <ul>
    <li><a href="/auth/oauth2">Login</a></li>
    <li><a href="/secret">Secret</a></li>
    <li><a href="/logout">Logout</a></li></ul>

I got this error:

Error: Failed to serialize user into session at pass (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/authenticator.js:281:19) at Authenticator.serializeUser (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/authenticator.js:299:5) at SessionManager.logIn (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/sessionmanager.js:14:8) at IncomingMessage.req.login.req.logIn (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/http/request.js:50:33) at OAuth2Strategy.strategy.success (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/middleware/authenticate.js:248:13) at verified (/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:177:20) at OAuth2Strategy.passport.use.OAuth2Strategy [as _verify] (/home/user/job/NodeJS/test-consumer/second/app.js:31:5) at /home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:193:24 at OAuth2Strategy.userProfile (/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:275:10) at loadIt (/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:345:17)

Every help is welcome.

Thanks you


Solution

  • You need to add serializer:

    passport.serializeUser(function(user, done) {
      done(null, user);
    });
    

    I'm using this module now, but the profile always returns empty.