[英]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:我有一个前端和后端分离的应用程序,我试图弄清楚两件事:
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.
可悲的是,我不确定我应该发送什么。
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 节)重复请求。
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.