passport-oauth2客户端如何使用接收到的配置文件数据



我有一个独立的oauth2身份提供程序正在运行。现在,我正在开发一个消费者,该消费者将使用这个独立的提供商对用户进行身份验证。

我正在学习这个关于护照和谷歌认证的教程:

我正试图使用这些信息来使用passport-oauth2作为客户端工作。我按照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>

我得到了这个错误:

错误:无法将用户序列化到会话at pass(/home/user/job/NodeJS/test consumer/second/node_modules/papassport/lib/authenticator.js:281.19)在Authenticator.serializeUser(/home/user/job/NodeJS/test-customer/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-customer/second/node_modules/passport-outh2/lib/strategy.js:177:20)在OAuth2Strategy.pasport.use.OAuth2Strategy[as_verify](/home/user/job/NodeJS/test-customer/second/app.js:31:5)在/home/user/job/NodeJS/test-consumer/second/node_modules/passport-outh2/lib/strategy.js:193:24在OAuth2Strategy.userProfile(/home/user/job/NodeJS/test-customer/second/node_modules/passport-outh2/lib/strategy.js:275:10)在loadIt(/home/user/job/NodeJS/test consumer/second/node_modules/passport-outh2/lib/strategy.js:345:17)

欢迎所有帮助。

谢谢

您需要添加序列化程序:

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

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

首先需要覆盖userProfile

这是的源代码

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

最新更新