处理 api 时进行两因素注册的正确方法是什么?
1)在前端有一个表单 - 电子邮件和电话 - 将数据发送到 api 方法
2) 我有一个 API,可以通过电子邮件和电话注册用户、生成代码并通过手机短信发送
问题 - 检查前面短信代码的正确方法是什么? (发送代码作为注册的响应,看起来不太安全)
最佳答案
我认为流程应该是(或多或少):
client:
- user fills out form and hits submit
- sends form data to backend
- show field for 2FA code entry
server:
- handles form data, generates a 2FA code, and sends that code to the client via email and/or SMS
- store that code in a DB (relational or not, doesn't really matter); you could even just store it whatever session manager you're using
- map that code to the current session, or supply that code to the client to correlate the 2FA code to the client
用户收到代码
client:
- user enters the code and hits submit
- sends entered code to the server
server:
- using the session or the DB, validates the code
- then, and only then, you auth the user
你是对的 - 永远不要在前端验证身份验证。
您的基本代码在前端应如下所示:
class TwoFactorAuth extends React.Component {
state = { stage: 1 };
onSubmitStageOne = (data) => {
// goes to /
submit(data).then(() => {
this.setState({ stage: 2 });
});
}
onSubmitStageTwo = (data) => {
// goes to /auth
authenticate(data).then(() => {
// success
}).catch(() => {
// wrong code, try again
});
}
renderStageOne() {
return (
<form onSubmit={this.onSubmitStageOne}>
<input name="email" />
<input name="phone" />
</form>
)
}
renderStageTwo() {
return (
<form onSubmit={this.onSubmitStageTwo}>
<input name="code" />
</form>
)
}
render() {
return this.state.stage === 1 ?
this.renderStageOne() :
this.renderStageTwo();
}
}
需要注意的是,我使用的是 ES6 类和 ES7 类属性初始值设定项 - 如果您想复制/粘贴上面的代码,您将需要 babel。
您的后端路由类似于:
router.post("/", (req, res) => {
const code = utils.generate2FACode();
request.session["code"] = code;
utils.emailOrSMSUser(code);
res.sendStatus(200);
});
router.post("/auth", (req, res) => {
const code = req.session["code"];
if (code === req.body.code) {
req.session["signedIn"] = true; // simplified for demonstration
res.sendStatus(200);
} else {
res.sendStatus(401);
}
});
这里我使用express
和express-session
。我会让您编写 generate2FACode
和 emailOrSMSUser
。
编辑:哎呀,你在标题中提到了 PHP API - 类似的逻辑,只是用 PHP 而不是 Node/Express。
关于api - 使用 React 和 php api 进行两因素注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43810298/