Do sessions really violate RESTfulness?

前端 未结 7 1390
小蘑菇
小蘑菇 2020-11-22 08:35

Is using sessions in a RESTful API really violating RESTfulness? I have seen many opinions going either direction, but I\'m not convinced that sessions are RESTless

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 08:58

    Cookies are not for authentication. Why reinvent a wheel? HTTP has well-designed authentication mechanisms. If we use cookies, we fall into using HTTP as a transport protocol only, thus we need to create our own signaling system, for example, to tell users that they supplied wrong authentication (using HTTP 401 would be incorrect as we probably wouldn't supply Www-Authenticate to a client, as HTTP specs require :) ). It should also be noted that Set-Cookie is only a recommendation for client. Its contents may be or may not be saved (for example, if cookies are disabled), while Authorization header is sent automatically on every request.

    Another point is that, to obtain an authorization cookie, you'll probably want to supply your credentials somewhere first? If so, then wouldn't it be RESTless? Simple example:

    • You try GET /a without cookie
    • You get an authorization request somehow
    • You go and authorize somehow like POST /auth
    • You get Set-Cookie
    • You try GET /a with cookie. But does GET /a behave idempotently in this case?

    To sum this up, I believe that if we access some resource and we need to authenticate, then we must authenticate on that same resource, not anywhere else.

提交回复
热议问题