How to implement two level authentication in a RESTful API?

﹥>﹥吖頭↗ 提交于 2020-02-16 05:47:28

问题


I am writing a RESTful API for a fairly complex web application (further referred as api.mywebapp.com)

The requirements include that api.mywebapp.com should handle:

  • API level authentication (authorizing client application eg.: mobile app)
  • User level authentication (authorizing www.mywebapp.com registered users so they can access their protected resources)

Usage example:

  1. Mobile application connects to the https://api.mywebapp.com with a valid basic HTTP authorization header (Authorization: Basic [base64_encoded_username:password])

  2. api.mywebapp.com authenticates mobile app and on successful authentication it responds to the request with a generated token.

  3. Mobile app is now using the received token in all consecutive requests it makes. (api.mywebapp.com also limits the API operations that the authenticated mobile app can do eg.: it cannot use system admin level API controllers)

  4. Mobile app gets to a state where it needs to login a www.mywebapp.com user to access and show a protected resource.

This is where I am not sure how this should be done.

Should api.mywebapp.com challenge mobile app with basic HTTP authentication for the user login too? If so, how would that work out with the current authentication already in place for API level?

My reason for using a generated token is: www.mywebapp.com is very session driven and a token also functions as a "session" identifier (session is also replaced to some server-side storage)

So I am facing two separate issues (this question is really about the first one):

  • How to multi level authenticate with a REST API?

  • How to implement a truly RESTful API for a very session driven web application without major changes in the application itself? I found this issue important because in a RESTful API the client state must not be stored on the server.


回答1:


This is almost identical to OAuth2 "Resource Owner Password Credentials Grant": http://tools.ietf.org/html/rfc6749#section-4.3. Set client credentials in Authorization header and post user credentials as x-www-form-url-encoded body. The result can be a bearer/session token as you already use it.

And, yes, sessions are a slightly problematic since they require the server to store some sort of client state. You can instead return a bearer token that embeds username+password in it with some kind of digital signing such that the clients cannot change it. OAuth2 is very explicit about not saying anything about the format of bearer tokens.



来源:https://stackoverflow.com/questions/20127743/how-to-implement-two-level-authentication-in-a-restful-api

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