登录后

时间:2018-12-07 17:12:40

标签: express passport.js

我正在尝试制作一个快速应用程序,让您登录到我的Vue应用程序。登录工作正常,但是将用户重定向到检查身份验证的新页面后,出现错误,提示用户未经过身份验证。

APP.JS文件

const express = require('express');
const axios = require('axios');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieSession = require('cookie-session')
const keys = require('./config/keys')
const passport = require('passport');
const passportSetup = require('./config/passport-setup');

//initializing express app
const app = express();

//CORS headers

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    if ('OPTIONS' == req.method) {
         res.send(200);
     } else {
         next();
     }
    });

//body-parser for form parsing
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


//cookie session
app.use(cookieSession({
    name : 'session',
    keys: [keys.session.cookieKey],
    maxAge : 24*60*60*1000, // 24 hrs
    domain : 'http//:localhost:8080'
}));

//initialize passport 

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


//initializing log-in route
app.use('/authentication', require('./routes/logInRoute'));
//initializing sign-up route
app.use('/authentication', require('./routes/signUpRoute'));



//connecting to database
mongoose.connect('mongodb://127.0.0.1/crypto', { useNewUrlParser: true })

PASSPORT-SETUP.JS文件

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user-model');

passport.serializeUser((user,done)=>{
    console.log('serialize called');
    done(null, user.id);
});

passport.deserializeUser((id,done)=>{
    console.log('deserialize called')
    User.findById(id, (error,user)=>{
        done(error,user);
    })

});


passport.use(
    new LocalStrategy({
        usernameField : 'email',
        passwordField : 'password',
    },
    (username,password,done) => {
        console.log('strategy called')
        User.findOne({email:username}, (err,user)=>{
            if(err){return done(err);}
            if(!user) {return done(null,false)}
            if(user.password !=password){return done(null,false); }
            console.log('user found');
            return done(null,user);
        });
    }
));

LOGINROUTE.JS文件

const router = require('express').Router()
const passport = require('passport');

const authMiddleware = (req,res,next) =>{
    console.log(req.session);
    console.log('middleware fired');
    console.log(req.isAuthenticated())
    if(!req.isAuthenticated()){

        res.status(401).send('You are not authenticated');
    }else{
        return next();
    }
}

router.post('/login', (req,res,next) =>{
    passport.authenticate("local", (err,user,info)=>{
        if(err){
            return next(err);
        }

        if(!user){
            return res.status(400).send([user, "cannot log in", info]);
        }
        req.login(user, err=>{
            console.log(req.session);
            res.send ("Logged in");
        });
    }) (req,res,next);
} )

router.get('/user', authMiddleware, (req,res)=>{
    user.find(user=>{
        console.log('searching for user')
        return user.id === req.session.passport.user
    });

    console.log([user,req.session]);

    res.send({user:user});
})

module.exports = router;

通过VUE APP初始化呼叫

getUserdata(){
     this.axios.get('http://127.0.0.1:3000/authentication/user', {
       withCredentials: true
     })
      .then((response)=>{
        self.$set(this,'user',response.data.user)
      })
      .catch((errors)=>{
        console.log(errors)
        this.$router.push('/');
      })

}

到目前为止,我所做的一切没有任何结果:

  • 在任何护照中间件之前放置会话中间件;
  • 添加了CORS标头以接受凭据和withCredentials:呼叫的真实标头;
  • 不是使用标准身份验证,而是使用req.login添加了自定义回调;
  • 尝试配置vue.config.js代理我的请求,以防我的应用由于跨域交互而无法保留会话;

我遇到的问题:

  • 从未调用Passport.deserializeUser()

这是我的第一个应用程序,我是一个大菜鸟,因此,如果我犯了任何明显的错误,对不起。谢谢您的宝贵时间。

编辑#1:

此刻,我正在尝试使用Express-Session而不是Cookie-Session,而我终于找到了目标。

app.use(require('express-session')({
    secret: 'crackalackin',
    resave: true,
    saveUninitialized: true,
    cookie : { secure : false, maxAge : (4 * 60 * 60 * 1000) }, // 4 hours

}));

在寻找解决方案之前,我发现这篇文章:https://github.com/jaredhanson/passport/issues/452,所以我尝试在代码中使用console.log(sessionStorage)并得到以下结果:

  //this is when I am logging in  
Session {                                                                                              
      cookie:                                                                                              
       { path: '/',                                                                                        
         _expires: 2018-12-07T21:24:31.206Z,                                                               
         originalMaxAge: 14400000,                                                                         
         httpOnly: true,                                                                                   
         secure: false },                                                                                  
      passport: { user: '5c066a79624c6a0b888d7888' } }    
       //this is when I am being redirected                                          
    Session {                                                                                              
      cookie:                                                                                              
       { path: '/',                                                                                        
         _expires: 2018-12-07T21:24:31.293Z,                                                               
         originalMaxAge: 14400000,                                                                         
         httpOnly: true,                                                                                   
         secure: false } }                                                                                 
    MemoryStore {                                                                                          
      _events:                                                                                             
       [Object: null prototype] {                                                                          
         disconnect: [Function: ondisconnect],                                                             
         connect: [Function: onconnect] },                                                                 
      _eventsCount: 2,                                                                                     
      _maxListeners: undefined,                                                                            
      sessions:                                                                                            
       [Object: null prototype] {                                                                          
         FIZ6y81PZH2qwd0fLVkQcZddeECrjJFN:                                                                 
          '{"cookie":{"originalMaxAge":14399999,"expires":"2018-12-07T21:24:31.190Z","secure":false,"httpOn
    ly":true,"path":"/"}}',                                                                                
         'j2eQDhhENf_Zt-wo5PmckZXTxExPTkix':                                                               
          '{"cookie":{"originalMaxAge":14400000,"expires":"2018-12-07T21:24:31.219Z","secure":false,"httpOn
    ly":true,"path":"/"},"passport":{"user":"5c066a79624c6a0b888d7888"}}' },                 

您可以看到用户ID存储在某个地方。仍在调查中

**** 已解决! ****

发出axios请求时,您必须这样做

this.axios.create({withCredentials : true}).get(URL)
      .then((response)=>{
        console.log(response)
      })
      .catch((errors)=>{
        console.log(errors)
        this.$router.push('/');
      })
  }

现在cookie已从浏览器正确发送到服务器,deserializeUser()被调用,并且req.isAuthenticated()为true:)

请确保在您的服务器中配置CORS头,可在此处找到代码。 Express会话设置也没有更改。希望这会对某人有所帮助,因为说实话,我花了很长时间才弄清楚。

0 个答案:

没有答案