前端JS通过Cookie实现记住密码

发布时间:2024年01月15日

目录

步骤1:掌握在cookie中存值

步骤2:掌握在cookie中通过name取值

步骤3:vue2集成ElementUI实现页面

步骤4:前端校验,通过axios连接后端

步骤5:后端代码(仅供参考)


步骤1:掌握在cookie中存值

    /**
     * [获取cookie]
     * @param {string} cookieName
     * @return {string} cookie
     */
    export function setCookie(cookieName, cookieValue, dayExpira) {
      //获取当前时间(中国标准时间))
      let time = new Date();
      //将天数转化为毫秒值+当前时间毫秒值=预计过期时间毫秒值
      time.setTime(time.getTime() + (dayExpira * 24 * 60 * 60 * 1000));
      //将预计过期时间毫秒值转化为预计过期时间字符串(格林威治时间)
      let expires = "expires=" + time.toUTCString();
      //cookie存储格式为name=value;expires
      document.cookie = cookieName + "=" + cookieValue + "; " + expires;
    }

注:参数dayExpira为设置多少天过期,默认为Session,即会话结束后过期

    // noinspection JSCheckFunctionSignatures
    setCookie("token", "123456");
    // 存储一个名为token,值为123456,结束时间为会话结束时间

步骤2:掌握在cookie中通过name取值

    //参数为cookie的name值
    export function getCookie(cookieName) {
      let name = cookieName + "=";
      //获取所有的cookie 例:a=123; b=123; c=123 split(去除符号';')
      let cookie = document.cookie.split(';');
      for (let i = 0; i < cookie.length; i++) {
        let cookieQuery = cookie[i];
        //如果查询到的cookie第一个值为空格,则从第二个字符串开始截取
        while (cookieQuery.charAt(0) === ' ') cookieQuery = cookieQuery.substring(1);
        //执行结束
        if (cookieQuery.indexOf(name) !== -1) {
          //返回查询到的cookie的value值
          return cookieQuery.substring(name.length, cookieQuery.length);
        }
      }
      return "";
    }

步骤3:vue2集成ElementUI实现页面

<template>
  <div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="手机号" prop="authPhone">
        <el-input v-model="ruleForm.authPhone" style="width: 420px"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="authPwd">
        <el-input v-model="ruleForm.authPwd" type="password" style="width: 420px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <el-checkbox v-model="checked">记住密码</el-checkbox>
      </el-form-item>
    </el-form>
  </div>
</template>

步骤4:前端校验,通过axios连接后端

<script>
export default {
  data() {
    return {
      ruleForm: {authPhone: '', authPwd: ''},
      rules: {
        authPhone: [
          {required: true, message: '请输入账号', trigger: 'blur'},
        ],
        authPwd: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ],
      },
      checked: false,
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post("http://localhost:8101/auth/loginByPwd", this.ruleForm).then(r => {
            // noinspection JSCheckFunctionSignatures
            setCookie("token", r.data.data);
            this.$router.push("list");
            this.setUserInfo();
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }, setUserInfo() {
      //判断用户是否勾选记住密码,如果勾选,向cookie中储存登录信息,如果没有勾选,储存的信息为空
      if (this.checked) {
        //将手机号存入cookie,过期时间为3天
        setCookie("authPhone", this.ruleForm.authPhone, 3);
        //base64加密密码
        let authPwd = window.atob(this.ruleForm.authPwd);
        //将加密后密码存入cookie,过期时间为3天
        setCookie("authPwd", authPwd, 3);
      } else {
        //清空key值为authPhone的token
        setCookie("authPhone", "", 0);
        //清空key值为authPwd的token
        setCookie("authPwd", "", 0);
      }
    }
  }, created() {
    //获取cookie存的手机号
    let authPhone = getCookie("authPhone");
    //获取解密后的密码
    let authPwd = window.btoa(getCookie("authPwd"));
    //如果密码不为空则页面为保存在cookie的账号和密码
    if (authPhone) {
      this.ruleForm.authPhone = authPhone;
      this.ruleForm.authPwd = authPwd;
      this.checked = true;
    }
  }
}
</script>

步骤5:后端代码(仅供参考)

    /**
     * 密码登录
     */
    @RequestMapping("loginByPwd")
    public R loginByPwd(@RequestBody Auth user) {
        QueryWrapper<Auth> wrapper = new QueryWrapper<>();
        wrapper.eq("auth_phone", user.getAuthPhone());
        Auth one = authService.getOne(wrapper);
        if (one == null) {
            return R.failed("未查询到该用户");
        }
        String password = DigestUtil.md5Hex(user.getAuthPwd() + one.getSalt());
        if (!StrUtil.equalsIgnoreCase(one.getAuthPwd(), password) || one.getAuthPwd() == null) {
            return R.failed("密码错误");
        }
        //加密签名
        byte[] key = one.getSalt().getBytes();
        //通过用户id获取Token
        String token = JWT.create().setPayload("id", user.getAuthId()).setKey(key).sign();
        return R.successed(token);
    }

文章来源:https://blog.csdn.net/Domain_2022/article/details/135533036
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。