REST API Authentication
I'm building an application which will be hosted on a server. I want to build an API for the application to facilitate interaction with from any platform (Web App, Mobile App). What I'm not understanding is that when using the REST API, how do we authenticate the user.
For example, when a user has logged in and then wants to create a forum topic. How will I know that the user is already logged in?
You can use HTTP Basic or Digest Authentication. You can securely authenticate users using SSL on the top of it, however, it slows down the API a little bit.
OAuth is the best it can get. The advantages oAuth gives is a revokable or expirable token. Refer following on how to implement: Working Link from comments: https://www.ida.liu.se/~TDP024/labs/hmacarticle.pdf
For eg when a user has login.Now lets say the user want to create a forum topic, How will I know that the user is already logged in?
Think about it - there must be some handshake that tells your "Create Forum" API that this current request is from an authenticated user. Since REST APIs are typically stateless, the state must be persisted somewhere. Your client consuming the REST APIs is responsible for maintaining that state. Usually, it is in the form of some token that gets passed around since the time the user was logged in. If the token is good, your request is good.
Check how Amazon AWS does authentications. That's a perfect example of "passing the buck" around from one API to another.
*I thought of adding some practical response to my previous answer. Try Apache Shiro (or any authentication/authorization library). Bottom line, try and avoid custom coding. Once you have integrated your favorite library (I use Apache Shiro, btw) you can then do the following:
/api/v1/login
and api/v1/logout
JSESSIONID
) that is sent back to the client (web, mobile, whatever) /api/v1/findUser
That's all. Hope this helps.
Use HTTP Basic Auth to authenticate clients, but treat username/password only as temporary session token .
The session token is just a header attached to every HTTP request, eg: Authorization: Basic Ym9ic2Vzc2lvbjE6czNjcmV0
The string Ym9ic2Vzc2lvbjE6czNjcmV0 above is just the string "bobsession1:s3cret" (which is a username/password) encoded in Base64.
To obtain the temporary session token above, provide an API function (eg: http://mycompany.com/apiv1/login
) which takes master-username and master-password as an input, creates a temporary HTTP Basic Auth username / password on the server side, and returns the token (eg: Ym9ic2Vzc2lvbjE6czNjcmV0). This username / password should be temporary, it should expire after 20min or so.
For added security ensure your REST service are served over HTTPS so that information are not transferred plaintext
If you're on Java, Spring Security library provides good support to implement above method
链接地址: http://www.djcxy.com/p/71274.html上一篇: RESTful API身份验证
下一篇: REST API身份验证