我有一个正在运行的独立oauth2身份提供程序。 现在,我正在开发一个消费者,它将使用此独立的提供程序对用户进行身份验证。
我关注this tutorial关于护照和Google身份验证:
我正在尝试使用此信息来使用通行证-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 [作为_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) 加载时(/home/user/job/NodeJS/test-consumer/second/node_modules/passport-oauth2/lib/strategy.js:345:17)
欢迎所有帮助。
谢谢
答案 0 :(得分:0)
您需要添加序列化器:
passport.serializeUser(function(user, done) {
done(null, user);
});
我现在正在使用此模块,但是配置文件始终返回空。
答案 1 :(得分:0)
首先,您需要覆盖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;
};
您还可以检查克隆我的源代码