Troubleshooting: Resolving Devise Issue in an API-only Application

💡 原文中文,约1700字,阅读约需4分钟。
📝

内容提要

本文介绍了在 API-only Rails 应用中使用 Devise 遇到的问题,解决方法包括使用 token-based authentication 或 http authentication,或者切换回 regular Rails mode。同时还需要处理跨域问题和配置 rack-cors,允许 credentials。作者还分享了自己被坑的经历。

🎯

关键要点

  • 在 API-only Rails 应用中使用 Devise 时,current_user 在 sign_in 后仍然为 nil 的问题。
  • 原因是 session-based authentication 在 API 模式下无法使用。
  • 解决方案包括使用 token-based authentication(如 devise-jwt)或 http authentication,或切换回 regular Rails 模式。
  • 在现有程序中引入 middleware,如 ActionDispatch::Cookies 和 ActionDispatch::Session::CookieStore。
  • 方法1需要重新编写代码,成本较高,因此放弃。
  • 方法3引入 middleware 后仍然无效,需检查 middleware 和 cookie 设置。
  • 发现跨域问题,需在前端请求中使用 credentials 处理跨域请求。
  • 需要配置 rack-cors,允许 credentials,以便 cookie 能正常发送。
  • 作者分享了自己在未使用 devise 时的错误代码导致的困惑。
➡️

继续阅读