I've been trying all day but I couldn't solve it.
The problem is as follows;
I made an oauth2 system for my own website. But it gives me the error in the title.
I guess it doesn't detect the callback coming from the server side?
res.redirect('http://localhost:2000/callback?code=' + response.data.accessToken);
//Example => http://localhost:2000/callback?code=97a1438b602c76a680297426306785ec9ef49f43
The piece of code where I got the error;
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
let token = 'http://localhost:3000/oauth/token';
let authorization = 'http://localhost:3000/login';
let temproraydata = {};
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var passport = require('passport');
var OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
passport.use(new OAuth2Strategy({
authorizationURL: authorization,
tokenURL: token,
clientID: 'application',
clientSecret: 'secret',
callbackURL: "http://localhost:2000/callback",
passReqToCallback: true
},
function (accessToken, refreshToken, profile, done) {
console.log(accessToken);
console.log(refreshToken);
temproraydata = profile;
return done(null, profile);
}
));
app.get('/provider', passport.authenticate('oauth2', { session: false }));
app.get('/callback',
passport.authenticate('oauth2', {
successRedirect: '/',
failureRedirect: '/login'
}));
app.listen(2000, function () {
console.log("Listening on port 2000");
});
this is error;
images
I've been working on it all day. I have done oauth server side but I am having problems on user side. I can't figure it out, I'm waiting for your help.
Related
I am trying to get session data, using passport js. When I use the /test or /test2 route, I get the session data. If I try to console.log in these routes, I get the whole session data. But when I try it with /user_data, I dont seem to get the expected response. Where am I going wrong here? I am using passport.js and express session. When going through the /user_data route, I get the following output:
Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}
Here is the code I am using, it is fairly dirty as of now as I am trying to tinker around.
const express = require('express')
const app = express()
const session = require('express-session');
const port = 3000
const passport =require("passport")
const GoogleStrategy = require('passport-google-oauth2').Strategy;
const bodyParser = require("body-parser");
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new GoogleStrategy({
clientID:"some.com",
clientSecret:"some_secret",
callbackURL: "http://localhost:3000/auth/google/callback",
passReqToCallback : true
},
function(request, accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'SECRET'
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/failed", (req, res) => {
res.send("Failed")
})
app.get("/success", (req, res) => {
res.send(`Welcome ${req.user.email}`)
})
app.get('/auth/google',
passport.authenticate('google', {
scope:
['email', 'profile']
}
));
app.get('/auth/google/callback',
passport.authenticate('google', {
failureRedirect: '/failed',
}),
function (req, res) {
res.redirect('/')
}
);
app.get("/test",(req,res)=>{
let sess = req.session;
console.log(sess);
var email=sess.passport.user.email;
var netid=email.split('#')[0];
req.session.netid=netid;
console.log(netid);
// console.log(sess.user.id);
res.send("test")
});
app.get("/test2",(req,res)=>{
let sess = req.session;
console.log(sess);
var netid=sess.netid;
console.log(netid);
res.send("test2")
});
app.get("/user_data",(req,res)=>{
var sess = req.session;
console.log(sess.passport);
res.send(sess.passport);
});
app.get('/logout', function(req, res){req.logOut();res.redirect('/');});
app.get('/', (req, res) => {res.sendFile(__dirname + "/pages/index.html");})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
In theory user_data is just another endpoint and on that basis it should work just like test and test2.
However, user_data could be a reserved name. Try changing that endpoint to something else.
Trying to use passport.js for linkedins oauth protocol (passport-linkedin-oauth2), i face this issue: when running 'node server', i get the following error:
PATH/node_modules/express/lib/router/index.js:139
debug('dispatching %s %s', req.method, req.url);
TypeError: Cannot read property 'method' of undefined
this is my server.js file:
const express = require('express');
const bodyParser = require("body-parser");
const path = require('path');
const passport = require('passport');
const session = require("express-session");
const app = new express();
const os = require('os');
const keys = require('./keys.js');
const listrategy = require('passport-linkedin-oauth2').Strategy;
require('events').EventEmitter.defaultMaxListeners = 15;
const PORT = process.env.PORT || 4000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static("public"));
const INDEX = path.join(__dirname, 'index.html');
const server = app().get('/',(req, res) => res.sendFile(INDEX))
passport.use(
new listrategy (
{
clientID: keys.linkedin.clientID,
clientSecret: keys.linkedin.clientSecret,
callbackURL: "/auth/linkedin/callback",
scope: ['r_emailaddress', 'r_liteprofile','w_member_social'],
state:true
},function (accessToken,refreshToken,profile,done) {
process.nextTick(function () {
console.log('profile',profile);
return done(null, profile);
});
})
);
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.use(session({resave: false, saveUninitialized: true, secret: 'recudorPegarevAecirP', cookie: { maxAge: 60000 }}));
app.use(passport.initialize());
app.use(passport.session());
app.listen(PORT);
I have got a valid linkedin secret and ID.
I am guessing something is wrong with the order of my declarations, or misusing the syntax. However, I don't know what. Could you help?
Thanks very much in advance.
You are trying to export router as router() somewhere in the other files and because of which is giving this error
just write router instead of router() while exporting the router file.
I am using passport.js google strategy for user authentication.
I am using OAUTH2.
When I launch my server and hit API through browser, it launches google signin page.
But when I hit API from react front-end, it never launches the googles signin page.
Please find below server code,
const bodyParser = require('body-parser');
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const app = express();
const cors = require('cors');
app.use(passport.initialize());
app.use(passport.session());
app.use(cors());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
passport.use('google', new GoogleStrategy({
clientID: "clientID", -- my client id
clientSecret: "clientSecret", -- my clientsecret
callbackURL: "callbackURL" -- url
},
function (accessToken, refreshToken, profile, done) {
// User.findOrCreate({ googleId: profile.id }, function (err, user) {
// console.log(err,user);
// return done(err, user);
// });
console.log(profile);
return done(err, user);
}
));
app.get('/googleauth',
passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));
passport.serializeUser(function (user, done) {
done(null, user);
})
passport.deserializeUser(function (user, done) {
done(null, user);
})
app.listen(4000, () => {
console.log("REST server started on port 4000");
});
Axios call from react code,
handleJGoogleLogin(e) {
e.preventDefault();
var current = this;
axios.get('http://localhost:4000/googleauth')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
I am stuck here, looking for some help.
Thanks in advance
The call from the react front-end is a bit different for the OAuth flow. Instead of the normal back-end call using fetch or axios
make the call like this:
window.open(`http://localhost:${backend-port}/auth/google`, "_self");
This command will make a get request to the back-end server AND open that google sign in window at the same time.
Took me a lot of time to figure this out but this is the way...
I think that Passport thing only works on the server. It is probably doing a redirect or something like that.
A few things under your passport.use add in another parameter
passport.use('google', new GoogleStrategy({
clientID: "clientID", -- my client id
clientSecret: "clientSecret", -- my clientsecret
callbackURL: "callbackURL" -- url
proxy: true
},
change:
const GoogleStrategy = require('passport-google-
auth').OAuth2Strategy;
to:
const GoogleStrategy = require('passport-google-oauth20').Strategy;
add in a second scope of profile
app.get('/googleauth',
passport.authenticate('google', { scope:
['https://www.googleapis.com/auth/plus.login','profile'] }));
Can you post your react code?
i'm developing application on cloud9 enviroment. using:
node 4.43
express 4.13.4
i have integrated my Demo Auth0 account into my on-dev application.
i am able to login (being redirected to the first page of my app), but when i'm printing req.isAuthenticated() i'm getting false. also req.user is undefined.
i have followed the quick start of auth0 for node.js.
i'm attaching the three files that are mainly invovled:
app.js:
var express = require('express'),
app = express(),
BodyParser = require("body-parser"),
mongoose = require("mongoose"),
student = require ("./models/student"),
students_class = require("./models/class"),
// =============
// auth0
// =============
passport = require('passport'),
strategy = require('./models/setup-passport'),
cookieParser = require('cookie-parser'),
session = require('express-session');
app.use(cookieParser());
app.use(session({ secret: 'FpvAOOuCcSBLL3AlGxwpNh5x-U46YCRoyBKWJhTPnee2UELMd_gjdbKcbhpIHZoA', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
app.get('/login',passport.authenticate('auth0', { failureRedirect: '/url-if-something-fails' }),
function(req, res) {
res.send(req.user);
if (!req.user) {
throw new Error('user null');
}
res.redirect("/", {username: req.user});
});
mongoose.connect("mongodb://localhost/myapp");
// ============================
// routes
// ============================
var classRoutes = require("./routes/class"),
indexRoutes = require("./routes/index"),
studentRoutes = require("./routes/student"),
assocRroutes = require ("./routes/assoc");
// ============================================
// configuring the app
// ============================================
app.set("view engine", "ejs");
app.use(express.static ("public"));
app.use(BodyParser.urlencoded({extended: true}));
app.use(classRoutes);
app.use (indexRoutes);
app.use(studentRoutes);
app.use(assocRroutes);
app.listen(process.env.PORT, process.env.IP, function() {
console.log('Attendance Server is Running ....');
});
setup-passport.js
var passport = require('passport');
var Auth0Strategy = require('passport-auth0');
var strategy = new Auth0Strategy({
domain: 'me.auth0.com',
clientID: 'my-client-id',
clientSecret: 'FpvAOOuCcSBLL3AlGxwpNh5x-U46YCRoyBKWJhTPnee2UELMd_gjdbKcbhpIHZoA',
callbackURL: '/callback'
}, function(accessToken, refreshToken, extraParams, profile, done) {
// accessToken is the token to call Auth0 API (not needed in the most cases)
// extraParams.id_token has the JSON Web Token
// profile has all the information from the user
return done(null, profile);
});
passport.use(strategy);
// This is not a best practice, but we want to keep things simple for now
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
module.exports = strategy;
index.js (the actual fisrt page where i want to re-direct after successful login:
var express = require("express");
var passport = require('passport');
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn();
var router = express.Router();
var student = require ("../models/student");
//INDEX
router.get("/callback", function(req, res) {
student.find({}, function(err, student) {
console.log(req.isAuthenticated())
if (err) {
console.log(err);
} else {
res.render("home/index.ejs", {
students: student
});
}
});
});
module.exports = router;
any suggestion what could go wrong?
also wierd for me that on app.js, the guide is initializing the variable strategy but actually never seem to use it.
BUMP
You are not calling passport.authenticate() in the /callback endpoint. See for comparison: https://auth0.com/docs/quickstart/webapp/nodejs#5-add-auth0-callback-handler
// Auth0 callback handler
app.get('/callback',
passport.authenticate('auth0', { failureRedirect: '/url-if-something-fails' }),
function(req, res) {
if (!req.user) {
throw new Error('user null');
}
res.redirect("/user");
});
I would like to know how (if possible) it is possible to get a persistent token from Facebook as the authentication from Passport only gives a short-time token (from what i read).
If this is possible, i would to know how to allow the user to be still logged in whenever he reconnects to my website.
here is my (yet not really consistent) code :
var passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy;
var express = require('express'),
app = express();
passport.use(new FacebookStrategy({
clientID: "xxxxx",
clientSecret: "xxxxxx",
callbackURL: "/auth/facebook/callback"
},
function(accessToken, refreshToken, profile, done)
{
done(null, profile);
}
));
app.get('/login', function(req, res)
{
res.end('Login with Facebook') ;
})
app.get('/', function(req, res)
{
res.end('logged in !') ;
})
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['user_event'] }));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { successRedirect: '/',
failureRedirect: '/login' }));
var server = app.listen(8080);