需求概况
要求实现登录功能,包含记住密码
基本实现原理
传输给后端字段采用MD5加密,记住密码的状态存放在localStorage
中,密码采用encrypt
加密后存放在cookie
中,需要用时在cookie
获取密码解密后使用
准备工作
下载依赖包crypto-js
// 如果没有安装淘宝镜像先安装淘宝镜像
// npm install -g cnpm --registry=http://registry.npm.taobao.org/
cnpm install crypto-js --save-dev
上代码
1. 在
vuex
中先储存秘钥uid
export default new Vuex.Store({ state: { uid: 'xxxxx' } })
2. 封装加密解密及存储获取的
encryption.js
import CryptoJS from "crypto-js" import store from "@/store" export function setCookie(portId, psw, exdays) { // Encrypt,加密账号密码 let cipherPortId = CryptoJS.AES.encrypt(portId+'', store.state.uid).toString() let cipherPsw = CryptoJS.AES.encrypt(psw+'', store.state.uid).toString() // console.log(cipherPortId+'/'+cipherPsw)//打印一下看看有没有加密成功 let exdate = new Date() //获取时间 exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) //保存的天数 //字符串拼接cookie,为什么这里用了==,因为加密后的字符串也有个=号,影响下面getcookie的字符串切割,你也可以使用更炫酷的符号。 window.document.cookie = "username" + "==" + cipherPortId + ";path=/;expires=" + exdate.toGMTString() window.document.cookie = "password" + "==" + cipherPsw + ";path=/;expires=" + exdate.toGMTString() } //读取cookie export function getCookie () { let userInfo = { username: '', password: '' } if (document.cookie.length > 0) { let arr = document.cookie.split('; ') //这里显示的格式请根据自己的代码更改 for (let i = 0; i < arr.length; i++) { let arr2 = arr[i].split('==') //根据==切割 //判断查找相对应的值 if (arr2[0] == "username") { // Decrypt,将解密后的内容赋值给账号 let bytes = CryptoJS.AES.decrypt(arr2[1], store.state.uid) userInfo.username = bytes.toString(CryptoJS.enc.Utf8); } else if (arr2[0] == "password") { // Decrypt,将解密后的内容赋值给密码 let bytes = CryptoJS.AES.decrypt(arr2[1], store.state.uid) userInfo.password = bytes.toString(CryptoJS.enc.Utf8) } } } return userInfo } //清除cookie export function clearCookie () { setCookie('', '', -1) }
3.
login.vue
页面内使用封装好了的encryption.js
<script> // 先引入encryption.js和crypto-js import CryptoJS from "crypto-js" import { setCookie, getCookie, clearCookie } from '@/utils/encryption' export default { data() { return { userInfo: { username: '', password: '' }, isActive: false }; }, created(){ if (JSON.parse(localStorage.getItem('rememberPsw'))) { this.isActive = JSON.parse(localStorage.getItem('rememberPsw')) this.userInfo = getCookie() } else{ this.userInfo = { username: '', password: '' } this.isActive = false } } methods: { handlerSubmitBtn() { // 提交表单后给后台,密码进行MD5加密后传输进行验证是否正确 login(this.userInfo.username, CryptoJS.MD5(this.userInfo.password).toString(), this.isActive).then(res => { const resp = res.data; // 登录验证成功 if (resp.flag) { if (this.isActive) { localStorage.setItem('rememberPsw', JSON.stringify(this.isActive)) setCookie(this.userInfo.username, this.userInfo.password, 30) } else { localStorage.removeItem('rememberPsw') clearCookie() } this.$router.push({ path:"/home" }) } else { // 登陆验证失败 this.$message({ message: resp.message, type: "warning" }); } }) } } } </script>
结束语
crypto.js
中还有一些加密解密用法,如果有不懂的,可以参考一下 cryptojs官方api