【问题标题】:passport-oauth2 client how to use profile data receivedpassport-oauth2 客户端如何使用收到的配置文件数据
【发布时间】:2019-09-30 23:08:19
【问题描述】:

我有一个独立的 oauth2 身份提供程序正在工作。 现在我正在开发一个消费者,它将通过这个独立的提供者对用户进行身份验证。

我正在关注 this tutorial 关于护照和 Google 身份验证:

我正在尝试使用这些信息来使用 passport-oauth2 作为客户端。我按照official documentation on passoprt-oauth2 对上面教程中提供的代码进行了一些更改。

我认为我在 expressjs 接收身份验证确认和有关用户的信息的回调函数中存在一些问题。我不明白如何使用这些信息。

这是我的 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');
    });

这是针对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>

我收到了这个错误:

错误:无法将用户序列化到会话中 通过时(/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/authenticator.js:281:19) 在 Authenticator.serializeUser (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/authenticator.js:299:5) 在 SessionManager.logIn (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/sessionmanager.js:14:8) 在 IncomingMessage.req.login.req.logIn (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/http/request.js:50:33) 在 OAuth2Strategy.strategy.success (/home/user/job/NodeJS/test-consumer/second/node_modules/passport/lib/middleware/authenticate.js:248:13) 在验证(/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:177:20) 在 OAuth2Strategy.passport.use.OAuth2Strategy [as _verify] (/home/user/job/NodeJS/test-consumer/second/app.js:31:5) 在/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:193:24 在 OAuth2Strategy.userProfile (/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:275:10) 在 loadIt (/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:345:17)

欢迎任何帮助。

谢谢你

【问题讨论】:

    标签: node.js express oauth-2.0 passport.js


    【解决方案1】:

    你需要添加序列化器:

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

    我现在正在使用这个模块,但配置文件总是返回空。

    【讨论】:

      【解决方案2】:

      首先你需要覆盖用户配置文件

      这是源代码

      const passport = require('passport')
      // const { Strategy: GoogleStrategy } = require('passport-google-oauth20')
      const { Strategy: GithubStrategy } = require('passport-github')
      const { Strategy: OAuth2Strategy } = require('passport-oauth2')
      const { GITHUB_CONFIG, OAUTH2_CONFIG} = require('../config')
      const Profile = require('./profile')
      
      module.exports = () => {
          // Allow passport to serialize and deserialize users into sessions
          passport.serializeUser((user, cb) => cb(null, user))
          passport.deserializeUser((obj, cb) => cb(null, obj))
      
          // The callback that is invoked when an OAuth provider sends back user
          // information. Normally, you would save the user to the database
          // in this callback and it would be customized for each provider
          const callback = (accessToken, refreshToken, params, profile, cb) => {
              console.log('access-token',accessToken)
              console.log('refresh-token',refreshToken)
              console.log('profile',profile)
              console.log('params',params)
              return cb(null, profile)
          }
      
          // Adding each OAuth provider's startegy to passport
          // passport.use(new GoogleStrategy(GOOGLE_CONFIG, callback))
          passport.use(new GithubStrategy(GITHUB_CONFIG, callback))
          const DjangoStrategy = new OAuth2Strategy(OAUTH2_CONFIG, callback)
          DjangoStrategy.userProfile = function(accessToken, done) {
              var self = this;
              this._userProfileURL = 'http://localhost:8001/accounts/profile/';
              this._oauth2.get(this._userProfileURL, accessToken, function (err, body, res) {
                  var json;
      
                  if (err) {
                  if (err.data) {
                      try {
                      json = JSON.parse(err.data);
                      } catch (_) {}
                  }
      
                  if (json && json.message) {
                      return done(new APIError(json.message));
                  }
                  return done(new InternalOAuthError('Failed to fetch user profile', err));
                  }
      
                  try {
                  json = JSON.parse(body);
                  } catch (ex) {
                  return done(new Error('Failed to parse user profile'));
                  }
      
                  console.log('json', json)
      
                  var profile = Profile.parse(json);
                  profile.provider  = 'oauth2';
                  profile._raw = body;
                  profile._json = json;
                  done(null, profile);
              });
              }
          passport.use(DjangoStrategy)
      }
      
      

      创建个人资料

      profile.js
      
      exports.parse = function(json) {
          if ('string' == typeof json) {
            json = JSON.parse(json);
          }
      
          var profile = {};
          profile.id = String(json.id);
          profile.displayName = json.name;
          profile.username = json.username;
          profile.email = json.email;
      
          return profile;
        };
      

      您也可以查看克隆我的源代码

      https://github.com/faisallarai/nodejs-oauth-server.git

      【讨论】:

        猜你喜欢
        • 2020-06-19
        • 1970-01-01
        • 1970-01-01
        • 2020-08-20
        • 2015-06-24
        • 2019-08-18
        • 1970-01-01
        • 2014-10-06
        • 2018-03-06
        相关资源
        最近更新 更多