在我的“REST API”中,我想使用一些基于令牌/ cookie的身份验证 . 这意味着,在消费者可以使用API之前,消费者需要通过使用用户名/密码调用一些身份验证URL来获取此令牌 .
是否可以返回Set-Cookie标头?
我认为它实际上打破了REST原则,但如果没有HTTP Basic Auth(这意味着在每个请求中发送用户名/密码),你会怎么做(或设计uris和动词)?
也许是这样的?
GET api/authentication/signin/?username=abc&pwd=123
GET api/authentication/signout
要么?
GET api/user/authtoken/?username=abc&pwd=123 (signin)
DELETE api/user/authtoken/ (signout)
GET api/user/ (returning details of the current user)
那么注册呢?
POST api/user/ (which would also return an authtoken)
要么?
GET api/user/abc/authtoken/?pwd=123 (signin of user abc)
DELETE api/user/abc/authtoken/ (signout)
GET api/user/abc/ (returning details of user abc)
2 回答
我会将会话视为一种资源:
创建会话并返回cookie .
删除cookie并注销 .
检查会话是否有效(例如Cookie未过期或以其他方式失效) .
但我认为你还应该实现Basic Auth或其他一些标准的方案,并要求你的自定义会话内容通过它进行身份验证,而API的其余部分也可以通过cookie使用会话数据 .
对于用户名/密码验证,我将使用HTTP基本身份验证
http://en.wikipedia.org/wiki/Basic_access_authentication
优点是大多数HTTP客户端库都支持它开箱即用 . 如果您需要更多高级方法(摘要,oauth等) . 我会尽量不发明自己,我会避免使用cookies .