授予 API 访问 Rails 应用程序的最佳身份验证方法

问题描述:

我想为我的网络应用程序提供经过身份验证的 API 访问.这种服务的消费者通常是其他网站/服务.

I would like to offer authenticated API access to my web app. The consumers of such a service are typically other web sites/services.

验证这些用户的最佳方法是什么?OAuth、openID、http 认证?

What would be the best method of authenticating these users? OAuth, openID, http authentication?

与我们的工作一样,哪个最好?"是视情况而定".:)

As so much in our line of work, the answer to "which is best?" is "it depends." :)

  • HTTP 身份验证 - 如果您已经让客户端通过 ID 和密码登录到您的服务,您可能只需要做很少的工作就可以很好地发挥作用使用您的 API.如果您的 API 基本上是单一用途的并且不需要详细的权限,那么您可以在此处快速运行.

  • HTTP Authentication - If you're already letting clients log in to your service via an ID and password, you'll probably only have to do minimal work to get this to play nicely with your API. If your API is basically mono-purpose and doesn't require detailed permissions, you can get something working fairly quickly here.

API 令牌 - 如果您希望客户能够在不提供密码的情况下轻松进行身份验证(想想那些构建与您的 API 交互的服务的公司;也许 IT 部门不这样做)不希望开发团队知道密码;等等),然后将随机 API 令牌 à la GitHub 附加到用户帐户可能是最快的方法.作为奖励,您可以提供一种无需更改帐户密码即可重新生成 API 令牌的方法.

API Token - If you want clients to be able to authenticate easily without providing a password (think companies that build a service that interacts with your API; maybe the IT dept. doesn't want the dev. team knowing the passwords; etc.), then attaching a random API token à la GitHub to the user account is probably the quickest way to go. As a bonus, you can supply a method for regenerating the API token without having to change the account password.

OAuth - 如果您有多个权限或想要更精细地控制客户端访问您的 API 的方式和时间,OAuth 是一个不错的选择(OAuth2 更容易工作与,IMO,并支持 多种获取方式访问令牌).此外,许多语言都有库、gem 等,可以让它们简化 OAuth 工作流程.

OAuth - If you have multiple permissions or want finer-grained control over how and when a client can access your API, OAuth is a pretty good bet (OAuth2 is much easier to work with, IMO, and supports multiple methods of obtaining an access token). Furthermore, many languages have libraries, gems, etc. that will allow them to simplify the OAuth workflow.