web front-end entry to combat: realized CAPTCHA

What is CAPTCHA

CAPTCHA is a verification code. Verification code (CAPTCHA) is "Completely Automated Public Turing test to tell Computers and Humans Apart" (automatic distinction between computer abbreviations and human Turing Test is a distinction between the user's public computer or automatic procedures can be prevented : malicious crack the code, brush tickets, forum irrigation, prevent a *** for a particular registered user with a specific program brute force approach to constantly landing attempt, with a verification code is actually a lot of sites now prevailing way.

Since CAPTCHA is to distinguish between the operation of machines and people, then we can draw only one can answer a question on the graph. More common is to generate word verification code in the picture, and then the user to enter text on the picture is consistent verified.

While this authentication method has gradually been other, more advanced methods are eliminated (the text on the picture can still be read program identification), and the front end to generate verification codes compared to the back-end security is not high, but we the sole purpose of loading x, enhance the security of the program only incidental effects.

Login form

First, we need to add additional code for FormItem enter in on the login form, and provides a canvas container to the graphic code. Sometimes generated code do not understand, it is necessary to add a click event code to switch the verification code:

web前端开发学习Q-q-u-n: ⑦⑧④-⑦⑧③-零①②,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法(详细的前端项目实战教学视频)
<Form ref="loginForm" :model="form" :rules="rules">
    <FormItem prop="userName">
        <Input v-model="form.userName" placeholder="请输入用户名">
            <span slot="prepend">
                <Icon :size="16" type="person"></Icon>
            </span>
        </Input>
    </FormItem>
    <FormItem prop="password">
        <Input type="password" v-model="form.password" placeholder="请输入密码">
            <span slot="prepend">
                <Icon :size="14" type="locked"></Icon>
            </span>
        </Input>
    </FormItem>
    <FormItem prop="valiCode" v-show="this.count">
        <Input v-model="form.valiCode" placeholder="请输入验证码">
            <span slot="prepend">
                <Icon :size="14" type="ios-analytics"></Icon>
            </span>
        </Input>
        <div class="canvas" @click="getImgYanzheng">
            <canvas id="canvas"></canvas>
        </div>
    </FormItem>
    <FormItem>
        <Button @click="handleSubmit" type="primary" long>登录</Button>
    </FormItem>
</Form>

You need to use the property

ValiCode forms need to add additional codes for recording user input. Here we define when a user login fails again you will need to enter additional graphics code, so adding the count property, when the failure of the landing count ++, of course, this approach is not very strict, and the user refreshes the page count will be cleared. You can add more restrictions, such as remote login, etc. Here, as in this case did not involve back-end programs, so simply to count the basis for judging.

data() {
    return {
      form: {
        userName: "",// 用户名
        password: "",// 密码
        valiCode: ""// 验证码
      },
      count: 0, // 登录次数
      show_num: [],// 图形上的文字
    }
}

Production CAPTCHA

The method of the page is the canvas container that is bound to draw getImgYanzheng CAPTCHA

. Need to define a set of content your PIN codes when drawing the graphics, used herein are: A, B, C, E, F, G, H, J, K, M, N, P, Q, R , S, T, W, X, Y, Z, 1,2,3,4,5,6,7,8,9,0, good, medicine, health. Alphabet letters excluded and easily misrecognized characters can join (and therefore also the graphic codes made four randomly generated text asking the user, or allow the user to generate idioms fill in the blank in various forms, etc.). And ignore user-sensitive, so you need to use toLowerCase method.

Then there is the canvas drawing up some tips.

canvas drawing

The canvas element itself is not drawing power. All drawing work must be completed within JavaScript:

var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");

In JavaScript id to find the canvas element, and then create a context object, getContext ( "2d") object is a built-in HTML5 object has several methods for drawing paths, boxes, circles, characters, as well as ways to add images. We can imagine the canvas view and context is rendered scenery canvas.

Since the drawing process codes from left to right in the drawing, and therefore has to schedule the use of the canvas, plus additionally the verification elements when some random code so that codes are not drawn easily recognized procedures.

web前端开发学习Q-q-u-n: 731771211,分享学习的方法和需要注意的小细节,不停更新最新的教程和学习方法(详细的前端项目实战教学视频)
getImgYanzheng() {
      var show_num = [];
      var canvas_width = 150; //document.getElementById("canvas").style.width;
      var canvas_height = 30; //document.getElementById("canvas").style.height;
      var canvas = document.getElementById("canvas"); //获取到canvas的对象,景色
      var context = canvas.getContext("2d"); //获取到canvas画图的环境,景色呈现的画布
      canvas.width = canvas_width;
      canvas.height = canvas_height;
      var sCode =
        "A,B,C,E,F,G,H,J,K,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0,好,医,生";
      var aCode = sCode.split(",");
      var aLength = aCode.length; //获取到数组的长度

      for (var i = 0; i <= 3; i++) {
        var j = Math.floor(Math.random() * aLength); //获取到随机的索引值
        var deg = (Math.random() * 30 * Math.PI) / 180; //产生0~30之间的随机弧度
        var txt = aCode[j]; //得到随机的一个内容
        show_num[i] = txt.toLowerCase();
        var x = 10 + i * 20; //文字在canvas上的x坐标
        var y = 20 + Math.random() * 8; //文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";

        context.translate(x, y);
        context.rotate(deg);

        context.fillStyle = this.randomColor();
        context.fillText(txt, 0, 0);

        context.rotate(-deg);
        context.translate(-x, -y);
      }
      for (var i = 0; i <= 5; i++) {
        //验证码上显示线条
        context.strokeStyle = this.randomColor();
        context.beginPath();
        context.moveTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.lineTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.stroke();
      }
      for (var i = 0; i <= 30; i++) {
        //验证码上显示小点
        context.strokeStyle = this.randomColor();
        context.beginPath();
        var x = Math.random() * canvas_width;
        var y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }
      this.show_num = show_num;
    },

Lines of code and requires some random color:

randomColor() {
      //得到随机的颜色值
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    }

With these two methods, graphical verification code has been generated is completed, the next step is to use the problem.

Use CAPTCHA

Analyzing logins count, if the number is greater than 0 log need to enter codes:

const self = this;
if (this.count) {
        if (this.form.valiCode) {
            if (this.show_num.join("") != this.form.valiCode.toLowerCase()) {
                self.$Notice.warning({
                    title: "验证码错误"
                });
                return;
            }
        } else {
            self.$Notice.warning({
                title: "请输入验证码"
            });
            return;
        }
    }

When the login fails and you need to perform refresh count ++ code:

self.count++;
self.getImgYanzheng();
self.$Notice.warning({
title: "登陆失败",
desc: rs.data.msg
});

At this time the work is completed to add a CAPTCHA, the students get up quick.

web front-end entry to combat: realized CAPTCHA

Guess you like

Origin blog.51cto.com/14592820/2464782