js实现登录验证码
实现登录验证码的步骤
生成验证码
使用Canvas绘制随机验证码,包含数字、字母或混合字符。以下是一个生成4位随机验证码的示例:
function generateCaptcha() {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let captcha = '';
for (let i = 0; i < 4; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = '30px Arial';
ctx.fillStyle = '#000';
ctx.fillText(captcha, 10, 30);
return captcha;
}
存储验证码
将生成的验证码存储在变量或sessionStorage中,用于后续验证:
let currentCaptcha = generateCaptcha();
// 或者使用sessionStorage
sessionStorage.setItem('captcha', currentCaptcha);
验证用户输入
在提交表单时比较用户输入的验证码和存储的验证码:
function validateCaptcha() {
const userInput = document.getElementById('captchaInput').value;
const storedCaptcha = sessionStorage.getItem('captcha');
if (userInput.toUpperCase() !== storedCaptcha) {
alert('验证码错误');
currentCaptcha = generateCaptcha();
return false;
}
return true;
}
刷新验证码
提供刷新验证码的功能:
document.getElementById('refreshCaptcha').addEventListener('click', function() {
currentCaptcha = generateCaptcha();
});
HTML结构示例
<canvas id="captchaCanvas" width="120" height="40"></canvas>
<input type="text" id="captchaInput" placeholder="输入验证码">
<button id="refreshCaptcha">刷新验证码</button>
增强安全性措施
- 添加干扰线和噪点
- 限制验证码尝试次数
- 设置验证码有效期
// 添加干扰线
function addNoise(ctx) {
for (let i = 0; i < 5; i++) {
ctx.strokeStyle = `rgb(${Math.random()*255}, ${Math.random()*255}, ${Math.random()*255})`;
ctx.beginPath();
ctx.moveTo(Math.random()*120, Math.random()*40);
ctx.lineTo(Math.random()*120, Math.random()*40);
ctx.stroke();
}
}
服务器端验证
虽然前端验证可以提高用户体验,但必须配合服务器端验证:
// 伪代码示例
app.post('/login', (req, res) => {
if (req.body.captcha !== req.session.captcha) {
return res.status(400).send('验证码错误');
}
// 继续登录流程
});






