簡體   English   中英

Node.js,Vue.js和Passport.js。 .isAuthenticated()總是返回false? Axios標題可能嗎?

[英]Node.js, Vue.js and Passport.js. .isAuthenticated() always returns false? Axios headers possibly?

我正在將一個項目轉移到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());
          }
        })
  });

這是我在客戶端的登錄頁面:

          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'
            })
            }
        }

以下是AuthenticationService.login引用的axios調用:

    login(credentials){
    return Api().post('login', credentials);
},

Api來自:

import axios from 'axios';

 export default function(){
   return axios.create({
      baseURL: `http://localhost:8081/`
   });
  }

那么在用戶通過身份驗證后,如何讓前端向后端發送正確的標頭? 正如您所看到的,我將用戶ID存儲在vuex狀態,但我不認為用於確認所有權以及用戶是否登錄是安全的,對吧? 或者是嗎? 我可以輕松地在請求中發送它,是嗎? 我覺得這不夠安全,但我正在談論的是Idk。

編輯:這是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());

您的問題是因為您的前端和后端位於不同的域上。

passport.session() / express.session()用於維護用戶會話的cookie限定在特定域中。

當您在受保護資源上調用axios.get()時,axios將不會發送或接收cookie,因為localhost:8080localhost:8081的不同域。

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

只要您使用AJAX進行這些調用,即使沒有Vue,這也會存在。

requests.js

 let axiosConfig = { withCredentials: true, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:3000/', 'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE' } } 

server.js

 var express = require('express'); var app = express(); var cors = require('cors'); app.use(cors({credentials: true, origin: 'http://localhost:8080'})) 

app.use(cors({credentials:true,origin:' http:// localhost:8080 '}))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM