For e.g. 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:
- Create a Login/logout API like:
/api/v1/login
and api/v1/logout
- In these Login and Logout APIs, perform the authentication with your
user store
- The outcome is a token (usually,
JSESSIONID
) that is sent back to the client (web, mobile, whatever)
- From this point onwards, all subsequent calls made by your client
will include this token
- Let's say your next call is made to an API called
/api/v1/findUser
- The first thing this API code will do is to check for the token ("is
this user authenticated?")
- If the answer comes back as NO, then you throw a HTTP 401 Status
back at the client. Let them handle it.
- If the answer is YES, then proceed to return the requested User
That's all. Hope this helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…