简体   繁体   English

当用户尝试使用错误的凭据登录时我应该返回什么响应以及如何在前端指示凭据错误?

[英]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?

I have an application with decoupled front-end and back-end and I'm trying to figure out 2 things:我有一个前端和后端分离的应用程序,我试图弄清楚两件事:

  1. What response should I return when the user tries to log in with wrong credentials当用户尝试使用错误的凭据登录时,我应该返回什么响应
  2. After returning the response, how to indicate to the user that the credentials he has used are wrong返回响应后,如何向用户表明他使用的凭据是错误的

Right now I have the following function used for login a user.现在我有以下 function 用于登录用户。 If a user with that email does not exist, I send a 401 response.如果具有该 email 的用户不存在,我将发送 401 响应。 If a user exists, I check if his password is correct, and if it is I return a 200 response with all the data.如果用户存在,我会检查他的密码是否正确,如果正确,我会返回包含所有数据的 200 响应。 If the password is incorrect, I send 401 response.如果密码不正确,我会发送 401 响应。

module.exports.loginUser = async (req, res, next) => {
    let email = req.body.email
    let password = req.body.password

    let userExists = await User.findOne({
        where: {
            email: email
        }
    })

    if (userExists) {
        bcrypt.compare(password, userExists.password, (error, result) => {
            if (result) {
                let token = jwt.sign({ id: userExists.id, email: userExists.email }, 'secretkey')
                res.status(200).json({
                    message: 'Authentication succeeded',
                    username: userExists.username,
                    userId: userExists.id,
                    token: token
                })
            } else {
                res.status(401).json({
                    message: 'Authentication failed'
                })
            }
        })
    } else {
        res.status(401).json({
            message: 'Authentication failed'
        })
    }

}

On the front-end, I have a Login view with the following code:在前端,我有一个登录视图,其中包含以下代码:

<template lang="html">
    <div class="register">
        <div class="register-container">
            <p>Welcome back!</p>
            <form @submit.prevent="onSubmit" novalidate>
                <div class="margin-bottom-20">
                    <p>Email</p>
                    <input v-model='email' type='email'>
                </div>
                <div class="margin-bottom-20">
                    <p>Password</p>
                    <input v-model='password' type="password">
                </div>
                <button type="submit" name="button">Continue</button>
            </form>
        </div>
    </div>
</template>

<script>
import axios from 'axios'

export default {
    data(){
        return {
            email: '',
            password: '',
        }
    },
    methods: {
        onSubmit(){
            let userInfo = {
                password: this.password,
                email: this.email
            }
            this.$store.dispatch('login', userInfo)
        }
    }
}
</script>

And my store:还有我的商店:

const store = new Vuex.Store({
    state: {
        token: null,
        username: null,
        userId: null,
    },
    mutations: {
        authUser(state, userData){
            state.token = userData.token
            state.userId = userData.userId
            state.username = userData.username
            localStorage.setItem('token', userData.token);
            localStorage.setItem('userId', userData.userId);
            localStorage.setItem('username', userData.username);
        }
    },
    actions: {
        login({commit, dispatch}, userInfo){
            axios.post('/login', userInfo)
            .then(response => {
                commit('authUser', {
                    token: response.data.token,
                    userId: response.data.userId,
                    username: response.data.username
                })
                router.replace('/')
            }).catch((error) => console.log(error));
        },
    }
}

Now I'm not quite sure how to correctly and cleanly add functionality to the front-end that will render error if the user has added incorrect credentials.现在我不太确定如何正确和干净地向前端添加功能,如果用户添加了不正确的凭据,则会出现错误。 In order to render the error on the front-end, I'd have to send something in the response from the back-end to the front-end that will indicate that an error has occurred.为了在前端呈现错误,我必须在从后端到前端的响应中发送一些内容,表明发生了错误。 Sadly, I'm not sure what exactly should I send.可悲的是,我不确定我应该发送什么。

  1. From this answer :这个答案

The correct HTTP code would actually be 401. From the RFC:正确的 HTTP 代码实际上是 401。来自 RFC:

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. 401(未授权)状态码表示该请求尚未应用,因为它缺少目标资源的有效身份验证凭据。 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.生成 401 响应的服务器必须发送一个 WWW-Authenticate header 字段(第 4.1 节),其中包含至少一个适用于目标资源的质询。 If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials.如果请求包含身份验证凭据,则 401 响应表明这些凭据的授权已被拒绝。 The user agent MAY repeat the request with a new or replaced Authorization header field (Section 4.2).用户代理可以使用新的或替换的授权 header 字段(第 4.2 节)重复请求。

  1. By checking the response code on the client-side from the axios, for example:通过从 axios 检查客户端的响应代码,例如:
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:请记住,默认情况下,如果响应代码不是status >= 200 && status < 300 ,Axios 将抛出错误,如果要防止这种情况,则需要更改 axios 默认值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在纯前端应用程序上存储服务凭证的位置和方式 - Where and how to store service credentials on pure front-end application 前端从后端获取错误数据 - Front-end get wrong data from back-end 将Stripe API凭据存储在certificate.yml.enc中,这是什么错误? - What am I doing wrong storing my Stripe API credentials in credentials.yml.enc? 当我输入错误的凭据时,为什么我的后端会崩溃? - Why does my backend crashes when I enter wrong credentials? 在登录时输入错误的凭据时如何输入错误消息 - How to put an error message when putting the credentials wrong in a login 如何指示浏览器凭据应在不重新加载页面的情况下保存 - How to indicate to browser credentials should be saved without doing a page reload 如果我想通过在前端替换值来防止作弊,我应该怎么做? - What should I do if I want to prevent cheating by substituting values on front-end? Java Spring-如何上传文件,然后在html前端返回响应? - Java Spring - How to upload a file and then return the response in the html Front-end? 如何将SQL返回数组更改为值并返回到前端? - How to alter SQL return array to a value and return to the front-end? 如何在服务器控制台上打印前端日志消息? - How to print front-end log messages on the server console?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM