问题描述
这似乎是一个多余的问题,但是请先听我说:
This might seem like a redundant question, but please hear me out first:
我正在使用React前端和Node后端.我正在使用JWT处理用户身份验证.现在,我在实际使用JWT和执行身份验证时遇到了麻烦.这就是我被困住的地方:
I'm working with a React Frontend and a Node Backend. I'm using JWT to deal with user authentication. Right now, I'm having trouble actually working with the JWT and performing the authentication. Here's where I'm stuck:
〜我尝试在后端将令牌设置为http cookie.如果我与邮递员一起工作,我会看到已设置令牌.但是,当我使用req.cookies.token尝试接收令牌cookie以便在后端执行验证时,得到了一个未定义的值.我是否应该以某种方式将cookie从前端发送到后端?我觉得这是我所缺少的部分.
~ I try setting the token as an http cookie in my backend. If i work with postman, I see the token being set. However, when I use req.cookies.token to try and receive the token cookie to perform validation in the backend, I get an undefined value. Am I supposed to be sending the cookie from the frontend to the backend somehow? I feel like this is the part that I am missing.
请告知!
推荐答案
因此,我可以为您提供使用 express-session 和 connect-mongodb-session来处理会话的替代解决方案这一直是服务器会话处理的流行且有些安全的解决方案
SO I can give you an alternative solution to handling session making use of express-session and connect-mongodb-session this has tend to been the popular and somewhat secure solution for server session handling
首先,您需要以下软件包
npm我的express-session connect-mongodb-session
或yarn add express-session connect-mongodb-session
npm i express-session connect-mongodb-session
or yarn add express-session connect-mongodb-session
现在,我们有了设置mongoStore和express-session中间件所需的软件包:
//Code in server.js/index.js (Depending on your server entry point)
import expressSession from "express-session";
import MongoDBStore from "connect-mongodb-session";
import cors from "cors";
const mongoStore = MongoDBStore(expressSession);
const store = new mongoStore({
collection: "userSessions",
uri: process.env.mongoURI,
expires: 1000,
});
app.use(
expressSession({
name: "SESS_NAME",
secret: "SESS_SECRET",
store: store,
saveUninitialized: false,
resave: false,
cookie: {
sameSite: false,
secure: process.env.NODE_ENV === "production",
maxAge: 1000,
httpOnly: true,
},
})
);
现在会话中间件已经准备就绪,但是现在您必须设置cors来接受您的ReactApp,以便传递cookie并由服务器在其中设置
//Still you index.js/server.js (Server entry point)
app.use(
cors({
origin: "http://localhost:3000",
methods: ["POST", "PUT", "GET", "OPTIONS", "HEAD"],
credentials: true,
})
);
现在我们的中间件都已设置完毕,让我们看看您的登录路径
router.post('/api/login', (req, res)=>{
//Do all your logic and now below is how you would send down the cooki
//Note that "user" is the retrieved user when you were validating in logic
// So now you want to add user info to cookie so to validate in future
const sessionUser = {
id: user._id,
username: user.username,
email: user.email,
};
//Saving the info req session and this will automatically save in your mongoDB as configured up in sever.js(Server entry point)
request.session.user = sessionUser;
//Now we send down the session cookie to client
response.send(request.session.sessionID);
})
现在我们的服务器已准备就绪,但现在我们必须修复如何在客户端中发出请求,以便此流程可以100%正常工作:
下面的代码:用于处理登录的React App
//So you will have all your form logic and validation and below
//You will have a function that will send request to server
const login = () => {
const data = new FormData();
data.append("username", username);
data.append("password", password);
axios.post("http://localhost:5000/api/user-login", data, {
withCredentials: true, // Now this is was the missing piece in the client side
});
};
现在,您拥有的所有服务器会话Cookie都为httpOnly
这篇关于如何在Node.JS中访问HTTP Cookie-JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!