我正在构建一个全栈移动应用程序,使用 Appwrite 进行身份验证和后端服务。前端与一个自定义 API 网关通信,该网关将请求代理到各个微服务。
目前,我正在使用 Appwrite 的 account.createJWT() 来验证用户身份,但 JWT 令牌每 15 分钟就会过期一次。频繁刷新令牌对于我的应用程序来说不可扩展,尤其是在用户群增长的情况下。因此,我正在尝试使用会话验证来代替 JWT。
我面临的问题是:如何使用 Appwrite 会话正确地验证对 API 网关的前端请求?
环境详情:
Backend API gateway is built with FastAPI
Appwrite version: cloud
Frontend framework: React Native
我的问题是:
What is the correct way to validate Appwrite user sessions from a backend service (API gateway) without using the frontend SDKs?
Is it possible to securely authenticate frontend requests to a custom backend using only Appwrite sessions (without using short-lived JWTs)?
If not, what would be the best scalable approach for authenticating requests in this setup?
任何建议、推荐流程或示例都将不胜感激!
以下是我尝试过的方法:
I retrieve the user session on the frontend (account.get() gives me session info).
I send the session ID (or the Appwrite cookie) along with API requests to my gateway.
On the backend (in the API gateway), I try to validate the session by using the Appwrite Server SDK (account.getSession(sessionId)).
However, sometimes I get errors like:
Unauthorized: User is missing "account" scope.
如何在不使用前端 SDK 的情况下从后端验证 appwrite 用户会话?
快完成了。使用服务器 SDK 进行调用
account.getSession(sessionId)
在技术上是正确的,但 AppWrite 要求会话 ID 与请求中的真实 Cookie(类似 的会话 Cookiea_session_<projectid>
)绑定。有时,在没有该 Cookie 的情况下进行服务器端调用
getSession(sessionId)
会让 AppWrite 感到不“自然”,然后它会报“未经授权”的错误。超级干净的方法是:
从你的前端,将会话 cookie 与你的 API 请求一起发送(就像浏览器行为一样)
在你的 fastapi 网关中,你从请求中挑选出那个 cookie
然后,您不需要这样做
getSession(sessionId)
,而是account.get()
在请求标头中发送 cookie 时执行此操作(这意味着您必须模拟真实的用户请求)问题是— appwrite server sdk 不允许手动发送原始 cookie,因为它是为“服务器端信任”调用而设计的,
因此解决方法是:
直接在网关内对 appwrite 的 HTTP API 进行 REST 调用,而不是使用 SDK
手动将会话 cookie 与请求标头一起发送
例如:
GET https://[appwrite-endpoint]/v1/account
使用X-Fallback-Cookies
标头调用或仅正确转发 cookie是否可以仅使用会话来安全地验证前端->自定义后端->appwrite?
是的,这是可能的。这实际上是理想的老式“基于会话的身份验证”方式。
流程将是:
前端使用 appwrite sdk 正常登录 → 获取会话
前端存储会话 cookie(如果您使用浏览器则自动存储 / 对于 React Native 则必须手动执行此操作)
前端将携带会话 cookie 的请求发送到您的 api 网关
您的网关提取会话 cookie,验证会话(就像我上面说的,直接将 REST 调用发送到 appwrite 的
/account
端点)如果 appwrite 说用户没有问题,就允许向微服务发出请求
这种方式永远不需要 jwt,除非你以后需要跨集群的可扩展性,或者移动 + web SSO 类型的功能
如果会话混乱,最好的可扩展方法是什么?
如果有一天这种会话方式让你感觉很烦人(比如移动端的 cookie 管理变得很痛苦),
那么你必须转向混合模型:
短期访问令牌(例如 15 分钟)
刷新令牌(长期有效,例如 1 个月)
后端问题
前端自动刷新访问令牌,用户甚至不知道
但是兄弟,说真的,除非你疯狂地扩展(比如数百万并发用户),否则
会话认证是干净、简单的,并且你可以根据需要使用粘性会话或 redis 会话存储来水平扩展它。
您可以立即尝试正确流程的快速版本
前端手动保存并发送会话 cookie
fastapi 获取 cookie,
https://cloud.appwrite.io/v1/account
在简单的requests.get()
(python 的请求库)中调用(带有 cookie 标头)如果 200 ok → 用户有效
将用户信息附加到请求上下文并将其转发给微服务
不需要 jwt,不需要刷新 session,没有戏剧性