[Vuejs]-What response should I return when a users tries to log in with wrong credentials and how to indicate that the credentials are wrong on the front-end?

3πŸ‘

βœ…

  1. From this answer:

The correct HTTP code would actually be 401. From the RFC:

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The user agent MAY repeat the request with a new or replaced Authorization header field (Section 4.2).

  1. By checking the response code on the client-side from the axios, for example:
axios.post('/login', userInfo)
            .then(response => {
                if (response.code === 401) {
                    // Incorrect credential
                    showErrorMessage(); // implement this
                } else {
                    // Correct credential
                    commit('authUser', {
                        token: response.data.token,
                        userId: response.data.userId,
                        username: response.data.username
                    })
                    router.replace('/')
                }
            }).catch((error) => console.log(error));

Keep in mind that by default, Axios will throw an error if the response code isn’t status >= 200 && status < 300, if you want to prevent this, you need to change axios default:

axios.defaults.validateStatus = function() {
  return true; // this wont throw error whatever the response code is
  // the default is `return status >= 200 && status < 300;`
};
πŸ‘€Owl

Leave a comment