Search code examples
restauthenticationhttpresponse

What status code should a REST API return for login requests performed with wrong credentials?


I have found a lot of answers and explanations for the meanings of HTTP status codes. My question is specifically about the POST request to a login endpoint, which asks for username and password and an invalid combination is provided.

Some thoughts:

400 Bad Response I think this code is not appropriate, because it says the request was syntactically incorrect and not understood by the server, which is not the case here. The login data is just semantically not correct.

401 Unauthorized Here is the tricky part for me. If 401 can only occur on requests requiring an authentication header then this is not correct. But if 401 can occur on all requests, which require authentication (either as header or in the body) then 401 is a candidate.

403 Forbidden Usually, 403 is returned if the user already is authenticated and known to the system but requested a resource he/she is not allowed to access. The user definitely is not authenticated before the login. I don't know if there is a semantic for 403 for unauthenticated users.

I'm happy to be told the answer or hear your thoughts.


Solution

  • If a user is attempting to authenticate, but provides invalid credentials, the response should have a status of 401, regardless of if you are using Basic Authorization or not. 401 indicates that authentication failed, but the user can alter their request and attempt again.

    If a user is authenticated, but not authorized to access the requested resource, then the response should have a status of 403. 403 indicates that the user is forbidden from accessing the resource, and no matter how they alter the request, they will not be permitted access.

    In the scenario that your endpoint requires the credentials to be in the body of the request, you should return a 400 if the request body does not meet your specifications.