前端登录时记住我功能代码怎么实现
时间: 2024-03-05 09:48:47 浏览: 75
Python+tkinter模拟“记住我”自动登录实例代码
以下是一个简单的前端实现 "记住我" 功能的示例代码:
```javascript
// 登录请求
const login = async (username, password, rememberMe) => {
const data = { username, password };
if (rememberMe) {
localStorage.setItem('rememberMe', true); // 存储 rememberMe 标识到 Local Storage
}
const response = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
const result = await response.json();
if (response.ok) {
if (rememberMe) {
setCookie('token', result.token, 365); // 存储 token 到 Cookie 中,有效期为 365 天
}
return result;
} else {
throw new Error(result.message);
}
};
// 设置 Cookie
const setCookie = (name, value, days) => {
const date = new Date();
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
const expires = '; expires=' + date.toGMTString();
document.cookie = name + '=' + value + expires + '; path=/; HttpOnly; Secure';
};
// 获取 Cookie
const getCookie = (name) => {
const nameEQ = name + '=';
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
};
// 验证 token
const verifyToken = async () => {
const token = getCookie('token');
if (token) {
const response = await fetch('/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': CSRF_TOKEN, // 防止 CSRF 攻击
},
body: JSON.stringify({ token }),
});
if (response.ok) {
const result = await response.json();
return result;
} else {
throw new Error('Authentication failed');
}
} else {
throw new Error('Token not found');
}
};
// 退出登录请求
const logout = async () => {
const rememberMe = localStorage.getItem('rememberMe');
if (rememberMe) {
localStorage.removeItem('rememberMe'); // 删除 rememberMe 标识
document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;'; // 删除 token
}
const response = await fetch('/logout', { method: 'POST' });
if (!response.ok) {
throw new Error('Logout failed');
}
};
```
注意,上述代码仅为示例,实际使用时需要根据具体的后端实现进行相应的修改。另外,为了防止跨站脚本攻击(XSS),在存储和获取 Cookie 时,应该对 Cookie 的值进行编码和解码。
阅读全文