What status code should a REST API return for login requests performed with wrong credentials?
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.
My question is specifically about the
POST
request to a login endpoint, which asks for username and password for example and the scenario where incorrect ones are provided.
It depends on how the credentials are sent:
If you are using HTTP Authentication (sending credentials in the
Authorization
header), you can return401
to indicate that the credentials are invalid.If you send credentials in the request body (for example a JSON with username and password),
401
doesn't seem to be the most suitable status code (once it's not a real HTTP Authentication). In this situation, consider403
instead with a descriptive response payload.
The 403
status code also can be used to indicate authorization problems, that is, to indicate that a user is not allowed to perform an action.