I'm implementing a REST api with Play... and I know a REST api should be stateless. Well, my api is an hybrid, in the sense that when an user authenticates, I send back a token to be used to sign any subsequent request. This token expires after an amount of time the user no longer sends requests to the server – on the server side, I use a MongoDB collection to handle active tokens.
Now my question is: how should I deal with this token? Should the request contain the token in the body? Or should I provide the token in the request headers?
Considering I'm using Play, is it still correct to use RequestHeader.cookies
to send the token even if I don't really use cookies?
Any suggestion on how to implement a decent authentication mechanism for my REST api would be really appreciated.
TLDR: You should use cookies.
Storing the token in a user's cookies is generally the best way to go. The cookies get passed to the server on every request via headers, therefore creating your own implementation of keeping state via some mechanism that keeps using a token in the headers would be a lot of redundant work (and increases the chance that something will break). Just because you're keeping state on the client-side doesn't mean this is bad... the whole idea of stateless programming is when you're load balanced on N machines is that you are not worried about a given user's requests getting routed.
You might take a look at this example app I wrote: https://github.com/kaeawc/play-encryption
And if you want to read more about the subject I'd suggest this as a very good guide: The definitive guide to form based website authentication