Search code examples
resthttpauthenticationpostput

Should I use POST or PUT for login request, and why?


I know the difference between them generally but for the login form, I'm not sure why the POST method is recommended.


Solution

  • Broadly: because PUT has more specific semantics in HTTP, and those semantics don't match the typical login form case very well.

    POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.” -- Fielding 2009

    POST /foo HTTP/1.1
    Content-Type: text/plain
    
    username=foo&password=this_is_a_secret
    

    That request can mean almost anything; it might or might not be idmpotent, it might or might not be "effectively read only". It's very non-committal. From RFC 7321:

    The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics.

    In contrast, PUT means something much more specific

    A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response.

    Thus

    PUT /foo HTTP/1.1
    Content-Type: text/plain
    
    username=foo&password=this_is_a_secret
    

    Suggests that when someone later does

    GET /foo HTTP/1.1
    

    You expect a response like

    HTTP/1.1 200 OK
    Content-Type: text/plain
    
    username=foo&password=this_is_a_secret
    

    In other words, the semantics of PUT are very close to those of "save" or "upsert". "Make your copy of this resource look like the payload of this request."

    Remember, general purpose HTTP components don't necessarily know that these message are about "login"; they only see messages with semantics of the transfer of documents over a network domain. That's means that when they see your "login" PUT request, they are going to assume that the semantics are exactly the same as a PUT to any other resource on the web, and act accordingly.