当前位置: 首页>后端>正文

前后端分离实现验证码的校验、登录

在前后端不分离的情况下,一般使用的是session 存储验证码文字,前端页面传过来的值与 session 存储的值做对比。但在前后端分离后,就不能用session 了

前后端分离的时候,我们又要如何实现?

思路:

1.用户进入页面,前端请求后端生成一张带验证码图片
2.后端生成验证码图片时,将验证码文本存到 Redis中,key 用 uuid 生成,value 为验证码文本,有效时间5分钟,把 生成的 uuid 也传给前端
3.前端显示后端传来的验证码图片,用户输入请求时,将用户的输入的验证码和 uuid传给后端
4.后端接受用户的输入的验证码和 uuid,根据 key = uuid,查出 value,获取到正确的验证码,与用户的验证码比对,返回结果。

功能实现

生成图片验证码

svg-captcha是一个可以生成图形验证码的模块

安装 svg-captcha

npm i svg-captcha

生成图片验证码,并导出

const code = require("svg-captcha");
function createCode() {
    return code.create({
        size: 4,
        ignoreChars: "0o1iIl",
        noise: 3,
        color: true,
        background: "#fff",
        fontSize: 60
    });
}
module.exports = createCode;

生成唯一key

uuid 是一个可以生成唯一的模块

安装 uuid

npm i uuid

生成唯一id,并导出

const { v4: uuidv4 } = require('uuid');
function createUuid(){
    return uuidv4()
}
module.exports = createUuid

redis 存储验证码

安装 redis

npm i redis

引入redis,并配置

const client = redis.createClient({
    host: "127.0.0.1",  //  redis地址
    port: 6379  // 端口号
})
// 监听连接事件
client.on("connect", error => {
    if(!error) {
        console.log("connect to redis")
    }
})
// 监听错误事件
client.on("error", error => {
    throw new Error(error)
})

封装 set、get 方法,并导出

function setString(key, value, expire) {
    return new Promise((resolve, reject) => {
        client.set(key, value, (error, replay) => {
            if(error) {
                reject("设置失败")
            }
            if(expire) {
                client.expire(key, expire);
            }
            resolve("设置成功")
        });
    })
}

function getString(key) {
    return new Promise((resolve, reject) => {
        if(key) {
            client.get(key, (error, replay) => {
                if(error) {
                    reject(`获取${key}失败`)
                }
                resolve(replay);
            })
        }
    })
}

module.exports = {
    setString,
    getString
}

后端接口生成图片验证码

express 中生成图片验证码

router.get('/captcha', (req, res) => {
  let captcha = createCode()
  let uuid = createUuid()
  setString(uuid,captcha.text.toLowerCase(),300)
  res.type('svg');
  res.status(200).send(captcha.data);
});

前端功能实现

<template>
  <div>
    <input type="text" v-model="username" placeholder="Username" />
    <input type="password" v-model="password" placeholder="Password" />
    <input type="text" v-model="captcha" placeholder="Captcha" />
    <a v-html="captchaImg" alt="" @click="getCaptcha" href="javascript:;"></a>
    <button @click="login">Login</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      captcha: '',
      uuid:'',
      captchaImg:""
    }
  },
  created(){
    this.init()
  },
  methods: {
     init(){
       this.getCaptcha()
     },
     getCaptcha(){
       axios.get("/captcha").then(res=>{
           this.uuid = res.headers.uuid
           this.captchaImg = res.data
       })
    },
    login() {
      // 前端验证
      if (!this.username || !this.password || !this.captcha || !this.uuid) {
        alert('Please enter all fields!');
        return;
      }
      // 后端验证
      axios.post('/login', {
        username: this.username,
        password: this.password,
        captcha: this.captcha,
        uuid:this.uuid
      }).then(res => {
        if (res.data.success) {
          // 登录成功
        } else {
          alert('Login failed!');
        }
      });
    }
  }
}
</script>

由于我们要用到图片验证码的uuid,就使用axios 方式请求

后端实现登录功能

router.post('/login', (req, res) => {
  const { username, password, captcha,uuid } = req.body;
   //  校验输入的内容 不能为空
  if(!username || !password || !captcha || !uuid){
    return res.json({ success: false, message: 'data empty!' });
  }
  // 校验验证码
  if (captcha.toLowerCase() !== getString(uuid)) {
    return res.json({ success: false, message: 'Incorrect captcha!' });
  }
   // 根据用户名和密码查询数据库 密码使用md5加密存储
  User.findOne({ username,password:md5(password) }, (err, user) => {
    if (err) {
      return res.json({ success: false, message: 'Server error!' });
    }
    if (!user) {
      return res.json({ success: false, message: 'Incorrect username or password!'});
    }
   
   // 登录成功逻辑
   return res.json({ success: true });
  });
});

https://www.xamrdz.com/backend/39b1941295.html

相关文章: