React集成Auth0时安全存储JWT令牌及钩子调用问题解决
React + Auth0 安全存储JWT令牌方案求助
我正在为基于React前端的分布式Web应用寻找使用Auth0安全存储JWT令牌的方案。当前使用localStorage存储,但该方式易受XSS和CSRF攻击;sessionStorage因关闭站点后需重新登录,无法作为备选。我考虑了两种方案:
1. 内存存储
这是Auth0推荐的最安全方案,但我无法在任意位置调用getAccessTokenSilently钩子。
当前API请求代码:
import axios from 'axios'; const token = localStorage.getItem('token') || null export default axios.create({ baseURL: `http://localhost:8080/`, headers: {Authorization: `Bearer ${token}`}, timeout: 2000 });
重构代码以使用getAccessTokenSilently实现内存存储时,出现以下错误:
Line 3:34: React Hook "useAuth0" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
重构后的代码:
import axios from 'axios'; import {useAuth0} from "@auth0/auth0-react"; const {getAccessTokenSilently} = useAuth0(); export default axios.create({ baseURL: `http://localhost:8080/`, headers: {Authorization: `Bearer ${getAccessTokenSilently}`}, timeout: 2000 });
请问有什么解决办法?我目前在GET请求中使用自定义钩子,但由于钩子必须在顶层调用,无法用于POST请求(比如添加商品)。
2. HTTP-only Cookie
虽然Auth0不推荐该方案,但如果可行的话可作为备选。
Auth0 SPA设置:

Auth0 API设置:

感谢您的建议。
内容的提问来源于stack exchange,提问作者Vercors
相关产品推荐
相关产品推荐

