Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

javascript - Problem with Passport NodeJs authentication

I am using Passport Local for authentication. But whenever I try to login it is just using failureRedirect and not creating Cookie. I have checked my code so many times but it still does the same. What I have observed that my passport.js file is not executing for some resion.

My App Index File

//Main app index file
const express=require('express');
const cookieParser=require('cookie-parser');
const app=express();
const port=8000;
const layout=require('express-ejs-layouts');
const db=require('./config/mongoose');
const session=require('express-session');
const passport=require('passport');
const localStrategy=require('./config/passport-local-strategy');

app.use(express.urlencoded({ extended: true }));

app.use(cookieParser());

app.use(express.static('./assets'));

app.use(layout);

app.set('layout extractStyles',true);
app.set('layout extractScripts',true);

app.set('view engine','ejs');
app.set('views','./views');

app.use(session({
    name:'Codeial',
    secret:'Something',
    saveUninitialized:false,
    resave:false,
    cookie:{
        maxAge:(1000*60*100)
    }
}));

app.use(passport.initialize());
app.use(passport.session());

app.use('/',require('./routes'));

app.listen(port,function(err){
    if(err)
    {
        console.log(`Error:${err}`);
        return;
    }
    console.log(`Sever runs on port:${port}`);
});
question from:https://stackoverflow.com/questions/65943052/problem-with-passport-nodejs-authentication

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just find one bug in serializeUser, put user.id in callback not done try and don't use return in serializeUser and deserializeUser like this:

passport.serializeUser(function(user, done) {
    done(null, user.id);
  });
  
  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });
  });

and remove this line in Passport file, because don't need to exports

module.exports=passport;

and use bodyParser module to parse body of requests to json

const bodyParser = require('body-parser');
app.use(bodyParser.json())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...