[英]Node.js, Vue.js and Passport.js. .isAuthenticated() always returns false? Axios headers possibly?
I'm moving a project over to Vue.js and I can't get any of my middleware to check if users are logged in or to check user ownership of things to work. 我正在将一个项目转移到Vue.js,我无法获取任何中间件来检查用户是否已登录或检查用户对所用内容的所有权。 After searching endlessly, I believe that the problem is that the headers I send from my client to server don't contain the passport serialized user or something?
经过无休止的搜索,我认为问题是我从客户端发送到服务器的标头不包含护照序列化用户或其他东西? How can I make this work?
我怎样才能做到这一点?
Here is my login route on the back-end: 这是我在后端的登录路线:
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());
}
})
});
Here is my login page on the client side: 这是我在客户端的登录页面:
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'
})
}
}
Here is the axios call that AuthenticationService.login is referencing: 以下是AuthenticationService.login引用的axios调用:
login(credentials){
return Api().post('login', credentials);
},
Api comes from: Api来自:
import axios from 'axios';
export default function(){
return axios.create({
baseURL: `http://localhost:8081/`
});
}
So how do I make the front-end send the right headers to the back-end after a user is authenticated? 那么在用户通过身份验证后,如何让前端向后端发送正确的标头? As you can see, I store the user id in a vuex state, but I don't think that would be safe to use to confirm ownership and whether or not users are logged in, right?
正如您所看到的,我将用户ID存储在vuex状态,但我不认为用于确认所有权以及用户是否登录是安全的,对吧? Or would it?
或者是吗? I could easily just send that over in the requests, is that right?
我可以轻松地在请求中发送它,是吗? I feel like that's not safe enough, but Idk what I'm talking about.
我觉得这不够安全,但我正在谈论的是Idk。
EDIT: Here is the passport setup in app.js 编辑:这是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());
Your issue is because your frontend and backend are on different domains. 您的问题是因为您的前端和后端位于不同的域上。
Cookies, which passport.session()
/ express.session()
use to maintain a user session, are scoped to a specific domain. passport.session()
/ express.session()
用于维护用户会话的cookie限定在特定域中。
When you call axios.get()
on the protected resource, axios will not send or receive cookies because localhost:8080
is a different domain to localhost:8081
. 当您在受保护资源上调用
axios.get()
时,axios将不会发送或接收cookie,因为localhost:8080
是localhost:8081
的不同域。
Try axios.get('/path/to/your/resource', { withCredentials: true })
and axios.post('/login', { username, password }, { withCredentials: true })
尝试
axios.get('/path/to/your/resource', { withCredentials: true })
和axios.post('/login', { username, password }, { withCredentials: true })
This would have been present even without Vue so long as you're using AJAX to make these calls. 只要您使用AJAX进行这些调用,即使没有Vue,这也会存在。
requests.js 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 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 '})) app.use(cors({credentials:true,origin:' http:// localhost:8080 '}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.