js登录验证码实现
验证码生成与显示
使用HTML5 Canvas生成图形验证码,通过随机生成字符和干扰元素增强安全性。以下为基本实现代码:
function generateCaptcha() {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 生成随机4位验证码
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
let captchaText = '';
for (let i = 0; i < 4; i++) {
captchaText += chars.charAt(Math.floor(Math.random() * chars.length));
}
// 绘制验证码文本
ctx.font = '30px Arial';
ctx.fillStyle = '#333';
ctx.fillText(captchaText, 10, 30);
// 添加干扰线
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() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.stroke();
}
return captchaText;
}
验证码刷新功能
为验证码添加点击刷新功能,提升用户体验:
document.getElementById('captchaCanvas').addEventListener('click', function() {
currentCaptcha = generateCaptcha();
});
let currentCaptcha = generateCaptcha();
表单验证逻辑
在表单提交时验证用户输入的验证码:
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault();
const userInput = document.getElementById('captchaInput').value.trim();
if (userInput.toUpperCase() !== currentCaptcha.toUpperCase()) {
alert('验证码错误,请重新输入');
currentCaptcha = generateCaptcha();
return false;
}
// 验证通过后继续登录流程
this.submit();
});
服务端验证增强
虽然前端验证可提升用户体验,但必须结合服务端验证:
// Node.js示例(使用Express框架)
app.post('/login', (req, res) => {
const { username, password, captcha } = req.body;
const sessionCaptcha = req.session.captcha;
if (!captcha || captcha.toUpperCase() !== sessionCaptcha.toUpperCase()) {
return res.status(400).json({ error: '验证码错误' });
}
// 清除已使用的验证码
delete req.session.captcha;
// 继续验证用户名密码...
});
安全性优化措施
采取以下措施提升验证码安全性:
- 设置验证码有效期(如5分钟)
- 限制单位时间内验证尝试次数
- 使用更复杂的变形验证码(扭曲、旋转字符)
- 考虑使用第三方验证码服务如reCAPTCHA
移动端适配方案
针对移动设备优化验证码体验:
// 响应式调整验证码大小
function adjustCaptchaSize() {
const canvas = document.getElementById('captchaCanvas');
if (window.innerWidth < 768) {
canvas.width = 120;
canvas.height = 40;
} else {
canvas.width = 150;
canvas.height = 50;
}
generateCaptcha();
}
window.addEventListener('resize', adjustCaptchaSize);
adjustCaptchaSize();
无障碍访问支持
为视障用户提供语音验证码选项:
function speakCaptcha() {
const utterance = new SpeechSynthesisUtterance(currentCaptcha.split('').join(' '));
window.speechSynthesis.speak(utterance);
}
以上实现方案可根据实际需求进行调整,建议在重要场景结合短信验证码或生物识别等多因素认证方式。







