As a part of my learning project, I am developing a WebAPI and striving to implement best practices. The initial focus is on creating an authentication API that accepts an authentication object in JSON format:
{
username: myusername,
password: mypassword
}
The API endpoint for authentication is /api/authenticate, which is accessed via a POST request with the object as input.
Within my .Net code, I conduct necessary verification checks. If the username/password combination is valid, a jwt token is generated along with associated roles. The response from the API includes a 200 status code where the token is returned in the body (as displayed by "ey....." in Chrome developer tools indicating the jwt).
In case of invalid credentials, a 401 status code is returned.
I am contemplating if this approach is adequate. Would it be advisable to return a 200 status code with additional payload in the body upon successful login? For example, should the successful login response consist of JSON like:
{
success: true,
error: null,
token: "ey.....",
}
Conversely, a failed login could return:
{
success: false,
error: null,
token: null,
}
Furthermore, an error scenario could be represented as:
{
success: false,
error: 500,
token: null,
}
At the client-side, such responses could guide the decision-making process. This exercise aims at understanding the best practices for handling scenarios within a WebAPI environment.