Reputation: 37
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
Upvotes: 1
Views: 6384
Reputation: 21
Good one. Alternatively if your params give you back an id_token, you could just use JWT to decode it as follows:
const oktaStrategy = new Strategy({
authorizationURL: '{url}/oauth2/default/v1/authorize',
tokenURL: '{url}/oauth2/default/v1/token',
clientID: "xxxxxxxxxxxxx",
clientSecret: "XXXXXXX",
callbackURL: '{myurl}/callback',
}, (accessToken, refershToken, params, profile, done) => {
const decoded = jwtDecode(params['id_token']);
done(null, decoded);
});
Upvotes: 0
Reputation: 287
First you need to override the userProfile
This is the source code
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)
}
Create a profile
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;
};
You can also check clone my source code
https://github.com/faisallarai/nodejs-oauth-server.git
Upvotes: 0
Reputation: 242
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.
Upvotes: 1