asp.net core配合vue实现后端验证码逻辑
程序员文章站
2022-08-12 08:43:55
概述网上的前端验证码逻辑总感觉不安全,验证码建议还是使用后端配合验证。如果产品确定可以上网的话,就可以使用腾讯,百度等第三方验证,对接方便。但是产品可能内网部署,就必须自己写了。本文章就是基于这一点来...
概述
网上的前端验证码逻辑总感觉不安全,验证码建议还是使用后端配合验证。
如果产品确定可以上网的话,就可以使用腾讯,百度等第三方验证,对接方便。但是产品可能内网部署,就必须自己写了。
本文章就是基于这一点来实现的。
前端验证码显示一个图片,后端生成图片。
部分原理
1.前端调用生端获取图片时,传入一个roomid,后端生成一个4位验征码,放入redis中。然后生成一个图片返回。
2.前端显示图片,登录时将roomid和填写的验证码,一并提交,登录接口根据roomid从redis中取出验证码判断是否正确。
这样就相当于后端验证了。
大家觉得有问题什么,可以进行评论。谢谢。
源码
前端部分代码
<template> <div class="login-container"> <vue-particles color="#ffffff" :particleopacity="0.7" :particlesnumber="50" shapetype="circle" :particlesize="4" linescolor="#dedede" :lineswidth="1" :linelinked="true" :lineopacity="0.4" :linesdistance="150" :movespeed="2" :hovereffect="true" hovermode="grab" :clickeffect="true" clickmode="push" ></vue-particles> <el-form ref="loginform" :model="loginform" :rules="loginrules" class="login-form" autocomplete="on" label-position="left"> <div class="title-container"> <h3 class="title">智能综合管理系统</h3> </div> <el-form-item prop="username"> <span class="svg-container"> <svg-icon icon-class="user" /> </span> <el-input ref="username" v-model="loginform.username" placeholder="用户名" name="username" type="text" tabindex="1" autocomplete="on" /> </el-form-item> <el-tooltip v-model="capstooltip" content="caps lock is on" placement="right" manual> <el-form-item prop="password"> <span class="svg-container"> <svg-icon icon-class="password" /> </span> <el-input :key="passwordtype" ref="password" v-model="loginform.password" :type="passwordtype" placeholder="密码" name="password" tabindex="2" autocomplete="on" @keyup.native="checkcapslock" @blur="capstooltip = false" @keyup.enter.native="handlelogin" /> <span class="show-pwd" @click="showpwd"> <svg-icon :icon-class="passwordtype === 'password' ? 'eye' : 'eye-open'" /> </span> </el-form-item> </el-tooltip> <el-form-item prop="yzm"> <span class="svg-container"> <svg-icon icon-class="password" /> </span> <el-input type="text" v-model="loginform.verifycode" maxlength="4" placeholder="验证码" /> <div class="identifycode" @click="refreshcode"> <el-image :src="verifyimageurl"></el-image> </div> </el-form-item> <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 30px" @click.native.prevent="handlelogin">登录</el-button> </el-form> </div> </template> <script> import { validusername } from '@/utils/validate' import identify from './components/identify' import { uuid } from 'vue-uuid'; // uuid object is also exported to things // outside vue instance. export default { name: 'login', components: { identify }, data() { const validateusername = (rule, value, callback) => { if (!validusername(value)) { callback(new error('请输入正确的用户名')) } else { callback() } } const validatepassword = (rule, value, callback) => { if (value.length < 6) { callback(new error('密码最少6位')) } else { callback() } } return { loginform: { username: 'admin', password: '111111', roomid: '', verifycode: '' }, loginrules: { username: [{ required: true, trigger: 'blur', validator: validateusername }], password: [{ required: true, trigger: 'blur', validator: validatepassword }] }, passwordtype: 'password', capstooltip: false, loading: false, showdialog: false, redirect: undefined, otherquery: {}, identifycodes: '1234567890', identifycode: '', // verifyimageroomid: '', verifyimageurl: '', } }, watch: { $route: { handler: function (route) { const query = route.query if (query) { this.redirect = query.redirect this.otherquery = this.getotherquery(query) } }, immediate: true } }, created() { // window.addeventlistener('storage', this.afterqrscan) // this.identifycode = '' // this.makecode(this.identifycodes, 4) this.refreshcode() }, mounted() { if (this.loginform.username === '') { this.$refs.username.focus() } else if (this.loginform.password === '') { this.$refs.password.focus() } }, destroyed() { // window.removeeventlistener('storage', this.afterqrscan) }, methods: { checkcapslock(e) { const { key } = e this.capstooltip = key && key.length === 1 && (key >= 'a' && key <= 'z') }, showpwd() { if (this.passwordtype === 'password') { this.passwordtype = '' } else { this.passwordtype = 'password' } this.$nexttick(() => { this.$refs.password.focus() }) }, createuuid() { let uuidv4 = uuid.v4().replace('-', '').replace('-', '').replace('-', '').replace('-', '') this.verifyimageroomid = uuidv4 this.verifyimageurl = '/api/operator/getcaptchaimage/120/40/' + this.verifyimageroomid console.log(uuidv4) }, handlelogin() { this.$refs.loginform.validate(valid => { if (valid) { this.loading = true this.$store.dispatch('user/login', this.loginform) .then(() => { this.$router.push({ path: this.redirect || '/', query: this.otherquery }) this.loading = false }) .catch(() => { this.loading = false }) } else { console.log('error submit!!') return false } }) }, getotherquery(query) { return object.keys(query).reduce((acc, cur) => { if (cur !== 'redirect') { acc[cur] = query[cur] } return acc }, {}) }, // 生成随机数 randomnum(min, max) { return math.floor(math.random() * (max - min) + min) }, // 切换验证码 refreshcode() { let uuidv4 = uuid.v4().replace('-', '').replace('-', '').replace('-', '').replace('-', '') this.loginform.roomid = uuidv4 this.verifyimageurl = '/api/operator/getcaptchaimage/120/40/' + this.loginform.roomid console.log(uuidv4) }, // 生成四位随机验证码 makecode(o, l) { for (let i = 0; i < l; i++) { this.identifycode += this.identifycodes[ this.randomnum(0, this.identifycodes.length) ] } console.log(this.identifycode) } } } </script> <style lang="scss"> /* 修复input 背景不协调 和光标变色 */ /* detail see https://github.com/panjiachen/vue-element-admin/pull/927 */ $bg: #283443; $light_gray: #fff; $cursor: #fff; @supports (-webkit-mask: none) and (not (cater-color: $cursor)) { .login-container .el-input input { color: $cursor; } } /* reset element-ui css */ .login-container { background: url("~@/assets/background.jpg") no-repeat; min-height: 100vh; .el-input { display: inline-block; height: 47px; width: 85%; input { background: transparent; border: 0px; -webkit-appearance: none; border-radius: 0px; padding: 12px 5px 12px 15px; color: $light_gray; height: 47px; caret-color: $cursor; &:-webkit-autofill { box-shadow: 0 0 0px 1000px $bg inset !important; -webkit-text-fill-color: $cursor !important; } } } .el-form-item { border: 1px solid rgba(255, 255, 255, 0.1); background: rgba(0, 0, 0, 0.1); border-radius: 5px; color: #454545; .el-form-item__error { color: rgb(223, 223, 176); } } } </style> <style lang="scss" scoped> $bg: #2d3a4b; $dark_gray: #889aa4; $light_gray: #eee; .login-container { min-height: 100%; width: 100%; background-color: $bg; overflow: hidden; .login-form { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; width: 520px; max-width: 100%; padding: 160px 35px 0; margin: 0 auto; overflow: hidden; } .tips { font-size: 14px; color: #fff; margin-bottom: 10px; span { &:first-of-type { margin-right: 16px; } } } .svg-container { padding: 6px 5px 6px 15px; color: $dark_gray; vertical-align: middle; width: 30px; display: inline-block; } .title-container { position: relative; .title { font-size: 42px; color: $light_gray; margin: 0px auto 40px auto; text-align: center; font-weight: bold; } } .show-pwd { position: absolute; right: 10px; top: 7px; font-size: 16px; color: $dark_gray; cursor: pointer; user-select: none; } .identifycode { position: absolute; right: 10px; top: 5px; } .thirdparty-button { position: absolute; right: 0; bottom: 6px; } @media only screen and (max-width: 470px) { .thirdparty-button { display: none; } } } </style>
后端接口
/// <summary> /// 获取验证码 /// </summary> /// <returns></returns> [httpget("getcaptchaimage/{width:int}/{height:int}/{roomid}")] public iactionresult getcaptchaimage(int width, int height, string roomid) { console.writeline(roomid); //int width = 100; //int height = 36; var captchacode = captcha.generatecaptchacode(); var result = captcha.generatecaptchaimage(width, height, captchacode); string rediskey = "verifycode_" + roomid; startup.redisdb.stringset(rediskey, captchacode, new timespan(0, 5, 0)); stream s = new memorystream(result.captchabytedata); return new filestreamresult(s, "image/png"); } /// <summary> /// 登录 /// </summary> /// <returns></returns> [httppost("login")] public apiresponsedata login(logindto logininfo) { if (string.isnullorwhitespace(logininfo.username)) return apiresponse.error("用户名不能为空"); if (string.isnullorwhitespace(logininfo.password)) return apiresponse.error("密码不能为空"); entity.baseoperator operinfo = db .select<baseoperator>() .where(a => a.operatorcode == logininfo.username && a.password == logininfo.password.tolower() && a.status == 1 && a.isdel == false).toone(); if (operinfo == null) return apiresponse.error("用户名或者密码不正确"); bool verifyresult = captcha.validatecaptchacode(logininfo.roomid, logininfo.verifycode); if(verifyresult == false) return apiresponse.error("验证码不正确"); //登录时重新生成token,一个用户只能在一个地方登录 string token = system.guid.newguid().tostring().replace("-", ""); db.update<baseoperator>(operinfo.operatorid) .set(a => a.token, token) .executeaffrows(); dynamic outjson = new expandoobject();//初始化一个不包含任何成员的expandoobject outjson.token = token; //存入redis string rediskey = "userinfo_" + token; startup.redisdb.stringset(rediskey, operinfo.operatorid, new timespan(24, 0, 0)); return apiresponse.succ(outjson); }
到此这篇关于asp.net core配合vue实现后端验证码逻辑的文章就介绍到这了,更多相关asp.net core验证码 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!