[英]How do you pass authentication from an RTK Query to firebase functions to access realtime database?
In the frontend, everything is authenticated properly using the firebase signin api, and a listener for auth changes to get the token and User info to pass to the backend.在前端,一切都使用 firebase 登录 api 进行正确验证,并且 auth 更改的侦听器获取令牌和用户信息以传递到后端。
this is the general fields used in RTK Query:这是 RTK 查询中使用的一般字段:
reducerPath: "api",
baseQuery: fetchBaseQuery({
baseUrl: "https://us-central1.cloudfunctions.net/api",
mode: "cors",
prepareHeaders: (headers) => {
headers.set("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
headers.set("Access-Control-Allow-Origin", "*");
headers.set("Access-Control-Allow-Headers", "Content-Type");
const authToken = localStorage.getItem("AuthToken");
if (authToken) headers.set("authorization", authToken);
return headers;
},
}),
endpoints: (builder) => ({
getWorkouts: builder.query<GetWorkoutList, string>({
query: (userId) => ({
url: `/workouts/${userId}`,
}),
}),
---rest of endpoints---
and this it is checking for successful frontend authentication changes:这是检查成功的前端身份验证更改:
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, async (userInfo) => {
setUser(userInfo);
if (userInfo === null) {
localStorage.clear();
} else {
const token = await userInfo.getIdToken(true);
localStorage.setItem("AuthToken", `Bearer ${token}`);
}
});
return unsubscribe;
}, [user]);
In firebase functions, it is using admin levels to verify the token from the frontend and the rest of the backend is using regular user permissions.在 firebase 功能中,它使用管理员级别从前端验证令牌,而后端的 rest 使用普通用户权限。
const decodedIdToken = await adminApp.auth().verifyIdToken(idToken);
The problem is that using the admin level bypasses the security rules and doesn't actually provide the authentication for a user to reach the database.问题是使用管理员级别绕过了安全规则,实际上并没有为用户访问数据库提供身份验证。
What is the actual step that is missing to give the request to the realtime database the authentication object for firebase rules to be successfully passed.向实时数据库请求身份验证 object 以成功通过 firebase 规则的实际步骤是什么?
"users":{
"$userId":{
".write": "$userId == auth.uid",
".read": "$userId == auth.uid",
},
},
(auth == null) (身份验证 == 空)
Requests from the Admin SDK are normally fully trusted and bypass the security rules.来自管理员 SDK 的请求通常是完全可信的并且绕过安全规则。
For the Realtime Database though you can pass a databaseAuthVariableOverride
when initializing the Admin SDK, and pass your own UID as shown in the documentation on authenticating with limited privileges .对于实时数据库,虽然您可以在初始化 Admin SDK 时传递databaseAuthVariableOverride
,并传递您自己的 UID,如有关使用有限权限进行身份验证的文档中所示。 Although I've never tested this myself, I think you might be able to pass other claims too - as the information you pass just becomes the auth
variable in the rules.虽然我自己从未对此进行过测试,但我认为您也可以传递其他声明 - 因为您传递的信息只是成为规则中的auth
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.