[英]What is the best way to send firebase user token from front to back in API Authorization header ? (NextJs Application)
I need to send firebase user token in API authorization header in each API request in my next.js app.我需要在next.js应用程序的每个 API 请求中的 API 授权标头中发送 firebase 用户令牌。
Current Implementation:当前实施:
API.interceptors.request.use(
async (config) => {
const token = await firebase.auth().currentUser?.getIdToken(true);
if (token) {
config.headers["Authorization"] = "Bearer " + token;
}
return config;
},
(error) => {
return Promise.reject(error);
}
)
But the issue with this implementation is to User Token from firebase is fetched before each request which is effecting the performance of the applications.但是这个实现的问题是在每个影响应用程序性能的请求之前从 firebase 获取用户令牌。
Is there a better way to implement it ?有没有更好的方法来实现它? I am thinking to store the token in local storage and get token from localStorage instead of firebase.
我正在考虑将令牌存储在本地存储中并从 localStorage 而不是 firebase 获取令牌。
firebase.auth().onAuthStateChanged(async (user) => {
try {
if (user) {
const token = await user.getIdToken(true);
await localStorage.setItem("app_session", token);
}
} catch (err) =>{
// Handle error
}
}
And use it like this并像这样使用它
API.interceptors.request.use(
async (config) => {
const token = localStorage.getItem("app_session");
if (token) {
config.headers["Authorization"] = "Bearer " + token;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
There is a lot written on the subject of how best to store authentication tokens in frontend applications.有很多关于如何最好地在前端应用程序中存储身份验证令牌的主题。 There are several solutions and each has its pros and cons.
有几种解决方案,每种都有其优点和缺点。 This previous answer might give you some ideas.
这个以前的答案可能会给你一些想法。
This article gives a nice overview and explains why storing in memory might be the best option. 本文提供了一个很好的概述并解释了为什么存储在内存中可能是最好的选择。 Here is another article with a similar conclusion
这是另一篇有类似结论的文章
In your case, you might store the token in memory.在您的情况下,您可以将令牌存储在内存中。 When required, check for its existence, and if it is not in memory (think browser refresh) make the call to Firebase to retrieve the token and store it in memory again.
需要时,检查它是否存在,如果它不在内存中(想想浏览器刷新),则调用 Firebase 以检索令牌并将其再次存储在内存中。
Of course, you should look at your specific context and needs and decide if any of the other solutions, such as localStorage, might work for you and your security requirements.当然,您应该查看您的特定上下文和需求,并决定是否有任何其他解决方案(例如 localStorage)可能适合您和您的安全要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.