前后端分离情况下的图形验证码

图形验证码包含两部分:图片和文字验证码。在JSP时代,图形验证码生成和验证是通过Session机制来实现的:后端生成图片和文字验证码,并将文字验证码放在session中,前端填写验证码后提交到后台,通过与session中的验证码比较来实现验证。
在前后端分离的项目中,登录使用的是Token验证,而不是Session。后台必须保证当前用户输入的验证码是用户开始请求页面时候的验证码,必须保证验证码的唯一性。
那么怎样来实现呢,思路就是:
为每个验证码code分配一个主键codeId。前端请求验证码code时,将codeId在前端生成并发送给后端;后端生成code及图形验证码后,并与codeId关联保存;前端填写好code后,将code和codeId一并提交到后端,后端对code和codeId进行比较,完成验证。

下面贴上代码。

1、前端请求验证码

//生成图片验证码 function getVerifiCode() { var r = Math.random();//codeId,随机数 $("#r").val(r); $("#captchaPic").prop('src',commonObj.hostUrl + '/imgCode?r=' + r); }

在页面放了一个隐藏input用来保存codeId,请求时将codeId带上

2、后端生成验证码


    //生成验证码
    @GetMapping("/imgCode")
    public void creaeCode(HttpServletRequest request, HttpServletResponse response){
        ImageCode imagecode=new ImageCode();//图形验证码工具类
        BufferedImage img=imagecode.getImage();
        try {
            String codeId = request.getParameter("r");//从前端传codeId
            String code = imagecode.getValidateCode();//验证码
            service.saveImgCode(codeId, code);//后端保存验证码code和codeId
            response.setContentType("image/jpeg");
            imagecode.saveImage(img, response.getOutputStream());
        } catch (IOException e) {
            logger.error("生成图片验证码异常", e);
        }
    }

附上图形验证码生成类


public class ImageCode {
    int w=79;//宽度
    int h=30;//高度

    private String validateCode = "";//验证码

    Random r=new Random();

    public  BufferedImage CreateImage(){//生成图片的方法
        BufferedImage img=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);//内存中创建一张图片
        Graphics gps=img.getGraphics();//获取当前图片的画笔

        gps.setColor(new Color(240,240,240));//设置画笔

        gps.fillRect(0, 0, w, h);//填充一个与图片一样大小的矩形(其实就是为了设置背景颜色)
        return img;


    }
    public  BufferedImage getImage(){//得到图片的方法
        BufferedImage img=CreateImage();
        Graphics gps=img.getGraphics();//获取当前图片的画笔
        StringBuilder sb = new StringBuilder();
        //开始画东西
        for(int i=0;i<4;i++){
            String ch=this.getContent();
            sb.append(ch);
            gps.setColor(this.getColor());
            gps.setFont(this.getFont());
            gps.drawString(ch, w/4*i, h-5);//宽度让其不满图片
        }
        drawLine(img);
        validateCode = sb.toString();
        return img;

    }
    public  void saveImage(BufferedImage img,OutputStream out) throws  IOException {
        //这里为了测试将生成的图片放入f盘,在实际的项目开发中是需要将生成的图片写入客户端的:
        ImageIO.write(img, "JPEG", out);//response.getOutputStream()

        //ImageIO.write(img, "JPEG", new FileOutputStream("F:\\a.jpg"));//保存到硬盘

    }
    //在图片中插入字母和十个数字
    String str="abcdefghijklmnupqrstuvwxyzABCDEFGHIJKLMNUPQRSTUVWZYZ1234567890";
    public   String getContent(){
        int index=r.nextInt(str.length());
        return str.charAt(index)+"";
    }
    String[] font={"宋体","华文楷体","华文隶书","黑体","华文新魏"};//字体
    int[] fontSize={24,25,26,27,28};//字号大小
    int[] fontStyle={0,1,2,3};//字体样式
    public   Font getFont(){
        int index1=r.nextInt(font.length);
        String name=font[index1];
        int style=r.nextInt(4);
        int index2=r.nextInt(fontSize.length);
        int size=fontSize[index2];
        return new Font(name,style,size);
    }
    public   Color getColor(){//得到不同的颜色
        int R=r.nextInt(256);//取值范围是0-255
        int G=r.nextInt(256);
        int B=r.nextInt(256);
        return new Color(R,G,B);
    }
    public void drawLine(BufferedImage img){//画干扰线
        Graphics2D gs=(Graphics2D) img.getGraphics();
        gs.setColor(Color.BLACK);
        gs.setStroke(new BasicStroke(1.0F));//设置线的宽度
        for(int i=0;i<5;i++){//横坐标不能超过宽度,纵坐标不能超过高度
            int x1=r.nextInt(w);
            int y1=r.nextInt(h);
            int x2=r.nextInt(w);
            int y2=r.nextInt(h);
            gs.drawLine(x1, y1, x2, y2);

        }
    }

    public String getValidateCode(){
        return this.validateCode;
    }
}

3、登陆时提交验证码
登录界面:

image.png

提交登录代码:

            //执行登录
            var regData = {
                accName:data.username,
                accPwd:hex_md5(data.password),
                code:data.captcha,
                codeId:$("#r").val()
            };
            //提交数据到后台
            commonObj.ajaxData("/api/account/login", "post", JSON.stringify(regData), function     (res) {
                //登录成功
                var data = res.data;
                window.location.href='index.html';
            });

4、后台校验验证码

public Object doLogin(Map data) throws Exception {

        String accName = (String) data.get("accName");
        String accPwd = (String) data.get("accPwd");
        String code = (String) data.get("code");//验证码
        String codeId = (String) data.get("codeId");//验证码id

        Assert.hasText(accName, "账户名不能为空");
        Assert.hasText(accPwd, "密码不能为空");

        //验证码验证
        Assert.hasText(codeId, "验证码错误");
        PhoneCode phoneCode = codeService.validImgCode(codeId, code);
        ...
        //执行登录过程
        //todo
}

你可能感兴趣的:(前后端分离情况下的图形验证码)