简体   繁体   English

如何实现REST API的身份验证?

[英]How to implement authentication for REST API?

I'm creating a web based service that I want to expose as a REST API so that developers are able to create apps using it. 我正在创建一个基于Web的服务,我希望将其作为REST API公开,以便开发人员能够使用它创建应用程序。 I want developers to be able to create/manage user accounts and authenticate through API. 我希望开发人员能够创建/管理用户帐户并通过API进行身份验证。 How to handle this? 怎么办呢? OAuth or something else? OAuth还是其他什么?

I'm using python,flask,mongodb for this. 我正在使用python,flask,mongodb。

We have settled on the following, using OAuth 2 (which is much preferable to OAuth 1). 我们使用OAuth 2 (比OAuth 1更优选)解决了以下问题。 In particular we are using the resource owner password credentials flow. 特别是我们使用资源所有者密码凭证流。 As to how to integrate it into our RESTful service, here is the idea: 至于如何将它集成到我们的RESTful服务中,这是一个想法:

  • The initial resource, when hit by an unauthorized user, returns a 401. The body of the 401 contains a single link, with rel=oauth2-token . 初始资源在被未授权用户命中时返回401.401的主体包含单个链接,其中rel=oauth2-token (How you signal links depends on your media type; we're using HAL , but you could use even just the Link header.) (如何通过链接发送信号取决于您的媒体类型;我们使用的是HAL ,但您甚至可以使用Link头。)
  • After the user authenticates, he returns to the initial resource, sending in his Authorization header the bearer token returned from the OAuth 2 process. 在用户进行身份验证后,他返回到初始资源,在其Authorization标头中发送从OAuth 2进程返回的承载令牌。 At this point, we return a 200, with all the normal links available. 此时,我们返回200,所有正常链接都可用。

We don't expose account creation, but if you wanted to do that, I would do so with another link available to unauthorized users in the initial resource. 我们不公开帐户创建,但如果您想这样做,我会使用初始资源中未授权用户可用的其他链接。 That link would have a custom rel since it is specific to your application, eg rel=http://rels.myapi.com/users 该链接将具有自定义rel因为它特定于您的应用程序,例如rel=http://rels.myapi.com/users

Good RESTful design would indicate that the link with this rel points to eg http://myapi.com/users , and that consumers of the API do a POST to that endpoint, which returns to them the new user resource with a Location header pointing to the newly-created user resource at eg http://myapi.com/users/username . 良好的RESTful设计表明与此rel的链接指向例如http://myapi.com/users ,并且API的消费者对该端点执行POST ,该端点返回具有Location头指向的新用户资源到新创建的用户资源,例如http://myapi.com/users/username (User resources themselves would of course be another rel , distinguishing between the singular user resource and the plural users collection resource.) (用户资源本身当然是另一个rel ,区分单个用户资源和多个用户集合资源。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM