且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

跨应用程序/服务器的 Rails 身份验证

更新时间:2023-12-01 14:17:10

是的,使用 OAuth 的 SSO 是一种可行的解决方案,但它不是最简单的解决方案.在构建任何新事物时,OAuth 2.0 是***选择.OAuth 标准涵盖了很多方面.

Yes, SSO using OAuth is a viable solution, but it's not the simplest one. When building anything new, OAuth 2.0 is the way to go. The OAuth standards cover a lot of ground.

OAuth 的主要优势在于它允许用户授予 3rd 方应用访问其帐户的权限,而无需将其密码透露给 3rd 方.如果您没有认真地提供这种互操作性,那么 OAuth 可能有点过头了.

The primary advantage of OAuth is that it allows users to give 3rd party apps access to their account without disclosing their password to the 3rd party. If you are not seriously providing such interoperability, then OAuth is probably overkill.

考虑到复杂性,我提供了一对不同的解决方案:

Given the complexity, I offer a different pair of solutions:

单点登录

诀窍是在您域内的主机之间共享会话 ID cookie &使用共享会话存储(如 ActiveRecordStore 或基于缓存的存储.)

The trick is to share the session ID cookie between hosts within your domain & to use a shared session store (like ActiveRecordStore or a cache-based store.)

每个 Rails 应用程序都有一个用于签署 cookie 的秘密".在较新的 Rails 应用程序中,它位于 /config/initializers/secret_token.rb.在每个应用程序中设置相同的秘密令牌.

Every Rails app has a "secret" that is used to sign cookies. In newer Rails apps this is located in /config/initializers/secret_token.rb. Set the same secret token in each application.

然后,配置会话以允许来自所有子域的访问:

Then, configure the session to allow access from all subdomains:

AppName::Application.config.session_store :active_record_store, :key => '_app_name_session', :domain => :all

对于内部 API 调用

使用良好的共享密钥通过 HTTPS 连接进行身份验证.在授权"标头值中传递秘密.

Use a good shared secret to authenticate over HTTPS connections. Pass the secret in the "Authorization" header value.

您可以轻松地将共享密钥与其他架构(如 node.js)一起使用.请确保始终使用 HTTPS,否则共享机密可能会在网络上被嗅探.

You can use the shared secret easily with other architectures (like node.js). Just make sure you always use HTTPS, otherwise the shared secret could be sniffed on the network.