Play, REST, and Authentication

末鹿安然 提交于 2020-01-05 09:28:50

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/22474268/play-rest-and-authentication

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