首页  >  文章  >  web前端  >  网络安全:用于存储令牌的 localStorage 与 cookie

网络安全:用于存储令牌的 localStorage 与 cookie

WBOY
WBOY原创
2024-08-28 06:08:02298浏览

Web Security: localStorage vs cookie for storing tokens

最安全的做法是将令牌存储在应用程序状态中。但是,需要注意的是,如果用户刷新应用程序,令牌将被重置。这可能会导致用户身份验证状态丢失。

这就是为什么令牌需要存储在 cookie 或 localStorage/sessionStorage 中。

localStorage VS 存储 token 的 cookie

在 localStorage 中存储身份验证令牌可能会带来安全风险,特别是在存在跨站脚本 (XSS) 漏洞的情况下,可能会导致恶意行为者窃取令牌。

选择将令牌存储在使用 HttpOnly 属性配置的 cookie 中,可以增强安全性,因为客户端 JavaScript 无法访问它们。在我们的示例应用程序中,我们利用 js-cookie 进行 cookie 管理,假设真正的 API 将强制执行 HttpOnly 属性以增强安全性,并且应用程序无法从客户端访问 cookie。

使用 React 和 Typescript 实现

要在使用 js-cookie 的 React TypeScript 应用程序中实现安全令牌管理,其中真正的 API 将强制执行 HttpOnly 属性,您可以按照以下步骤操作:

1。了解设置

HttpOnly Cookie:这些 Cookie 由服务器设置,无法通过 JavaScript 访问,从而更安全地抵御 XSS 攻击。
假设:服务器将处理 HttpOnly cookie 的设置和管理。您的客户端代码将专注于通过 API 响应和请求处理令牌。

2。 React TypeScript 设置

首先,确保您安装了 js-cookie:

npm install js-cookie

3。设置令牌管理

import React, { createContext, useContext, useEffect, useState } from 'react';
import Cookies from 'js-cookie';

interface AuthContextType {
  token: string | null;
  login: (token: string) => void;
  logout: () => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [token, setToken] = useState<string | null>(null);

  // Assuming the token is returned from a server and set as an HttpOnly cookie
  useEffect(() => {
    const fetchTokenFromServer = async () => {
      // Example API call to authenticate and retrieve token (token management handled by server)
      try {
        const response = await fetch('/api/authenticate', {
          method: 'POST',
          credentials: 'include', // This sends the HttpOnly cookie to the server
        });

        if (response.ok) {
          setToken(await response.text()); // Assume token returned in response body for simplicity
        }
      } catch (error) {
        console.error('Error fetching token:', error);
      }
    };

    fetchTokenFromServer();
  }, []);

  const login = (token: string) => {
    // If your server returns the token via a non-HttpOnly cookie or body, store it as needed
    Cookies.set('token', token); // Only use this if the token is not HttpOnly
    setToken(token);
  };

  const logout = () => {
    Cookies.remove('token');
    setToken(null);
  };

  return (
    <AuthContext.Provider value={{ token, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

4。在组件中使用身份验证上下文

import React from 'react';
import { useAuth } from './AuthProvider';

const Dashboard: React.FC = () => {
  const { token, logout } = useAuth();

  if (!token) {
    return <p>You are not logged in.</p>;
  }

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Your token is: {token}</p>
      <button onClick={logout}>Logout</button>
    </div>
  );
};

export default Dashboard;

5。处理 HttpOnly Cookie

由于客户端代码无法直接访问 HttpOnly cookie,因此服务器必须处理这些 cookie。在现实场景中:

登录:用户登录时,服务器设置HttpOnly cookie,客户端不直接管理。
API 请求:所有需要身份验证的请求都应包含凭据:“include”选项以发送 HttpOnly cookie。

6。服务器端实现

确保您的服务器端 API 将令牌设置为 HttpOnly cookie。例如,在 Express.js 服务器中:

res.cookie('token', token, { httpOnly: true, secure: true, sameSite: 'Strict' });

7。保护您的应用程序

  • 在生产中始终使用 https,以确保 cookie 安全传输。

  • 考虑在 cookie 中设置 secure: true 以确保它们仅通过 HTTPS 发送。

  • 使用 SameSite=Strict 或 Lax 来防止 CSRF 攻击。

感谢您的阅读!如果您觉得这篇文章有帮助,请点赞。如果您对所讨论的任何主题有任何疑问或需要进一步澄清,请随时与我联系。我是来帮忙的,很想听听您的意见!您可以在 Twitter 或 LinkedIn 上找到我期待与您联系!.

以上是网络安全:用于存储令牌的 localStorage 与 cookie的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn