有时*,访问时document.cookie
在登录页面中,我得到一个空字符串,即使:
- cookie 列在 Chrome 和 Firefox 开发者工具中,
- 我感兴趣的 cookie 的 httpOnly 标志设置为 false,
- 我感兴趣的 cookie 路径设置为“/”。
期望的行为
我的 React 单页应用程序 (SPA) 有一个登录页面,其中包含<form />
用于将登录凭据发送到后端的元素。当收到后端的响应并且身份验证成功时,我检查身份验证 cookie 是否已正确设置。如果是这种情况,将触发重定向,显示登录用户的内容。
实际行为
不幸的是,在像15%登录尝试次数,document.cookie
返回一个空字符串,以防止重定向并使用户保持在登录页面上。紧迫F5
并不能解决问题,但在成功登录请求后手动替换 url 路径时(例如更新 'www.website.tld/login' 到 'www.website.tld/start')用户将被转发到仅适用于登录用户的所需页面。
我无法手动重现该错误。这似乎是随机发生的。但是当它发生时,我查看开发人员控制台,我可以看到来自后端的所有 cookie(设置正确)。
附加信息
- django 服务器在后端运行
- 所需的 cookie 设置为
response.set_cookie('key', 'value', secure=False httponly=False, samesite='strict')
- JS 库(axios、react-router)
Related:
-
JS中无法从document.cookie访问cookie,但浏览器显示cookie存在 https://stackoverflow.com/questions/17508027/cant-access-cookies-from-document-cookie-in-js-but-browser-shows-cookies-exist(仅限http)
-
无法在JS中使用document.cookie访问cookie https://stackoverflow.com/questions/6217795/cant-access-a-cookie-using-document-cookie-in-js(仅限http)
登录页面 (JSX)
import React, { useState } from "react";
import { Redirect } from "react-router-dom";
import axios from "axios";
/**
* We're using cookies.js to read cookies.
* Source: https://github.com/madmurphy/cookies.js
*/
function hasItem(sKey) {
return new RegExp(
"(?:^|;\\s*)" +
encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") +
"\\s*\\="
).test(document.cookie);
}
export const LoginPage = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
function handleSubmit(e) {
e.preventDefault();
function onSuccess(response) {
// handle response
// [...]
// sometimes console.log(document.cookie) returns empty string
if (hasItem("auth_cookie")) {
setIsAuthenticated(true);
} else {
console.warn("Cookie not found!");
}
}
function onFailure(error) {
// handle error
}
const conf = {
headers: new Headers({
"Content-Type": "application/json; charset=UTF-8",
Origin: window.location.origin
})
};
axios
.post("/api/login/", { username, password }, conf)
.then(response => {
onSuccess(response);
})
.catch(error => {
onFailure(error);
});
}
if (isAuthenticated) {
return <Redirect to="/start" />;
}
return (
<div className="login-page">
<form
name="login-form"
method="post"
onSubmit={e => handleSubmit(e)}
action="api/login"
target="hiddenFrame"
>
<iframe className="invisible-frame" src="" name="hiddenFrame" />
<div>
<label htmlFor="username">Email</label>
<input
name="username"
type="text"
onChange={e => setUsername(e.target.value)}
/>
</div>
<div>
<label htmlFor="password">Password</label>
<input
name="password"
type="password"
onChange={e => setPassword(e.target.value)}
/>
</div>
<button type="submit">Submit</button>
</form>
</div>
);
};
路由 (JSX)
import React from "react";
import { Route, Redirect } from "react-router-dom";
const RootLayout = () => {
return (
<div className="root-layout">
<Switch>
<PublicRoute path="/login" component={LoginPage} />
<PrivateRoute path="/" component={App} />
</Switch>
</div>
);
};
/**
* Component that handles redirection when user is logged in already
*/
const PublicRoute = ({ component: ChildComponent, ...remainingProps }) => {
let isAuthenticated = hasItem("auth_cookie");
return (
<Route
render={props =>
isAuthenticated ? <Redirect to="/" /> : <ChildComponent {...props} />
}
{...remainingProps}
/>
);
};
/**
* Component that handles redirection when user has been logged out.
* E.g. when authentication cookie expires.
*/
const PrivateRoute = ({ component: ChildComponent, ...remainingProps }) => {
let isAuthenticated = hasItem("auth_cookie");
return (
<Route
render={props =>
!isAuthenticated ? (
<Redirect to="/login" />
) : (
<ChildComponent {...props} />
)
}
{...remainingProps}
/>
);
};
const App = () => (
<Switch>
<Route exact path="/" render={() => <Redirect to="/start" />} />
<Route exact path="/start" component={StartPage} />
<Route exact path="/blog" component={BlogPage} />
{/*...*/}
</Switch>
);
* I know, that's probably not how a post should start...