Node.js,Vue.js和Passport.js。.isAuthenticated()始终返回false?Axios标头可能吗?

Set*_*oni 7 javascript authentication node.js vue.js passport.js

我正在将项目移至Vue.js,但我无法获得任何中间件来检查用户是否已登录或检查用户对工作的所有权。经过无休止的搜索后,我相信问题是我从客户端发送到服务器的标头不包含护照序列化的用户或其他内容?我该如何进行这项工作?

这是我在后端的登录路线:

      router.post("/login", function (req, res, next) {
    if (!req.body.username || !req.body.password) {
      res.send("Error");
    } else if(req.body.username.length > 40 || req.body.password.length > 40){
      res.send("Error");
    } else if (req.body.username) {
      req.body.username = req.body.username.toLowerCase();
      next();
    }
  }, passport.authenticate('local', {
    failureRedirect: '/login'
  }), function(req, res){
        User.findById(req.user.id, function(err, user){
          if(err){
            res.send("User not found");
          } else {
            res.send(user.toJSON());
          }
        })
  });
Run Code Online (Sandbox Code Playgroud)

这是我在客户端的登录页面:

          async login () {
          const response = await AuthenticationService.login({
                username: this.username,
                password: this.password,
            })
            if(response.data == "Error"){
                this.$router.push({
                    name: 'login'
                })
            } else {
            this.$store.dispatch('setUser', response.data._id);
            this.$router.push({
                name: 'home'
            })
            }
        }
Run Code Online (Sandbox Code Playgroud)

这是AuthenticationService.login所引用的axios调用:

    login(credentials){
    return Api().post('login', credentials);
},
Run Code Online (Sandbox Code Playgroud)

Api来自:

import axios from 'axios';

 export default function(){
   return axios.create({
      baseURL: `http://localhost:8081/`
   });
  }
Run Code Online (Sandbox Code Playgroud)

那么,如何在验证用户身份后使前端将正确的标头发送到后端?如您所见,我以vuex状态存储用户ID,但我认为使用它来确认所有权以及用户是否已登录是不安全的,对吗?还是会?我可以轻松地将其发送到请求中,对吗?我觉得那还不够安全,但是我在说什么。

编辑:这是app.js中的护照设置

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(flash());
app.use(cookieParser());

app.use(express.session({ //5a6ba876578447262893ac69
    secret: "sessionSecret",
    resave: false,
    saveUninitialized: false
  }));
app.locals.moment = require('moment');
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
Run Code Online (Sandbox Code Playgroud)

Dan*_*try 6

您的问题是因为您的前端和后端位于不同的域。

饼干,其passport.session()/ express.session()使用维护用户会话,范围限定到特定的域。

当您调用axios.get()受保护的资源时,axios将不会发送或接收cookie,因为localhost:8080它与是不同的域localhost:8081

尝试axios.get('/path/to/your/resource', { withCredentials: true })axios.post('/login', { username, password }, { withCredentials: true })

只要您使用AJAX进行这些调用,即使没有Vue,也应该存在。