RESTful authentication API design

霸气de小男生 提交于 2019-12-24 14:23:38

问题


I have a question regarding RESTful API design. Following the guidelines of REST, all endpoints should be nouns and in plural, and should never be verbs. However, it is customary to have authentication routes be:

/login
/logout

which are both verbs. If you should be true to the guidelines these routes should look more like this instead:

/users?action=login
/users?action=logout

but I've never used any API that has this particular authentication implementation, everyone uses the first one, me included. But I wonder if this is because many people don't follow the guidelines fully and it has just become a habit or is there another reason?


回答1:


If you want to be compliant with the rest guidelines, your api should expose a security token resource as follows for instance :

/security/token

And that's it... You can then GET security tokens (login), use them, then DELETE them (logout)




回答2:


According to the stateless constraint of REST maintaining client sessions on server side is not allowed. So your question does not make any sense. These are the simplest auth solutions by REST:

  • By trusted clients you have to send the username and password with every request for example in a HTTP (basic) auth header. You have to use encrypted connection.

  • By 3rd party (non trusted) clients, you have to add a unique API key to the client by registration. After that when a customer first tries to use the client you show her a dialog in where she can register a unique access token for the client. So this way she allows access to her account. After that the 3rd party client sends the API key and the access token with every request related to the customers account.

To answer your question related to the URIs. According the uniform interface constraint:

  • You map the URIs to resources and not to operations. That's why they should not contain verbs. You use the verbs to choose the proper HTTP method. You can reduce almost every operation name to a few HTTP methods and nice URIs.

  • URIs does not have a meaning to the clients, because clients follow hyperlinks annotated with semantics (e.g. link relation, or a term from an RDF vocab).

  • Nice URIs are good for checking if you really mapped them to resources (if not, then they contain verbs).

  • Nice URIs are good when you write the routing logic on the server side manually, or when you debug requests.




回答3:


Use JWT(Json Web Token). It's very lightweight.



来源:https://stackoverflow.com/questions/25952842/restful-authentication-api-design

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!