zoukankan      html  css  js  c++  java
  • SpringBoot整合Shiro完成验证码校验

    SpringBoot整合Shiro完成验证码校验

    上一篇:SpringBoot整合Shiro使用Redis作为缓存

    首先编写生成验证码的工具类

    package club.qy.datao.utils;
    
    import java.awt.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.util.Random;
    
    /**
     * 图形验证码生成
     */
    public class VerifyUtil {
        // 默认验证码字符集
        private static final char[] chars = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        // 默认字符数量
        private final Integer SIZE;
        // 默认干扰线数量
        private final int LINES;
        // 默认宽度
        private final int WIDTH;
        // 默认高度
        private final int HEIGHT;
        // 默认字体大小
        private final int FONT_SIZE;
        // 默认字体倾斜
        private final boolean TILT;
    
        private final Color BACKGROUND_COLOR;
    
        /**
         * 初始化基础参数
         *
         * @param builder
         */
        private VerifyUtil(Builder builder) {
            SIZE = builder.size;
            LINES = builder.lines;
            WIDTH = builder.width;
            HEIGHT = builder.height;
            FONT_SIZE = builder.fontSize;
            TILT = builder.tilt;
            BACKGROUND_COLOR = builder.backgroundColor;
        }
    
        /**
         * 实例化构造器对象
         *
         * @return
         */
        public static Builder newBuilder() {
            return new Builder();
        }
    
        /**
         * @return 生成随机验证码及图片
         * Object[0]:验证码字符串;
         * Object[1]:验证码图片。
         */
        public Object[] createImage() {
            StringBuffer sb = new StringBuffer();
            // 创建空白图片
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            // 获取图片画笔
            Graphics2D graphic = image.createGraphics();
            // 设置抗锯齿
            graphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // 设置画笔颜色
            graphic.setColor(BACKGROUND_COLOR);
            // 绘制矩形背景
            graphic.fillRect(0, 0, WIDTH, HEIGHT);
            // 画随机字符
            Random ran = new Random();
    
            //graphic.setBackground(Color.WHITE);
    
            // 计算每个字符占的宽度,这里预留一个字符的位置用于左右边距
            int codeWidth = WIDTH / (SIZE + 1);
            // 字符所处的y轴的坐标
            int y = HEIGHT * 3 / 4;
    
            for (int i = 0; i < SIZE; i++) {
                // 设置随机颜色
                graphic.setColor(getRandomColor());
                // 初始化字体
                Font font = new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE);
    
                if (TILT) {
                    // 随机一个倾斜的角度 -45到45度之间
                    int theta = ran.nextInt(45);
                    // 随机一个倾斜方向 左或者右
                    theta = (ran.nextBoolean() == true) ? theta : -theta;
                    AffineTransform affineTransform = new AffineTransform();
                    affineTransform.rotate(Math.toRadians(theta), 0, 0);
                    font = font.deriveFont(affineTransform);
                }
                // 设置字体大小
                graphic.setFont(font);
    
                // 计算当前字符绘制的X轴坐标
                int x = (i * codeWidth) + (codeWidth / 2);
    
                // 取随机字符索引
                int n = ran.nextInt(chars.length);
                // 得到字符文本
                String code = String.valueOf(chars[n]);
                // 画字符
                graphic.drawString(code, x, y);
    
                // 记录字符
                sb.append(code);
            }
            // 画干扰线
            for (int i = 0; i < LINES; i++) {
                // 设置随机颜色
                graphic.setColor(getRandomColor());
                // 随机画线
                graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
            }
            // 返回验证码和图片
            return new Object[]{sb.toString(), image};
        }
    
        /**
         * 随机取色
         */
        private Color getRandomColor() {
            Random ran = new Random();
            Color color = new Color(ran.nextInt(256), ran.nextInt(256), ran.nextInt(256));
            return color;
        }
    
        /**
         * 构造器对象
         */
        public static class Builder {
            // 默认字符数量
            private int size = 4;
            // 默认干扰线数量
            private int lines = 10;
            // 默认宽度
            private int width = 80;
            // 默认高度
            private int height = 35;
            // 默认字体大小
            private int fontSize = 25;
            // 默认字体倾斜
            private boolean tilt = true;
            //背景颜色
            private Color backgroundColor = Color.LIGHT_GRAY;
    
            public Builder setSize(int size) {
                this.size = size;
                return this;
            }
    
            public Builder setLines(int lines) {
                this.lines = lines;
                return this;
            }
    
            public Builder setWidth(int width) {
                this.width = width;
                return this;
            }
    
            public Builder setHeight(int height) {
                this.height = height;
                return this;
            }
    
            public Builder setFontSize(int fontSize) {
                this.fontSize = fontSize;
                return this;
            }
    
            public Builder setTilt(boolean tilt) {
                this.tilt = tilt;
                return this;
            }
    
            public Builder setBackgroundColor(Color backgroundColor) {
                this.backgroundColor = backgroundColor;
                return this;
            }
    
            public VerifyUtil build() {
                return new VerifyUtil(this);
            }
        }
    }
    
    

    开发控制器,加载页面时生成新的验证码

    @RequestMapping("/getVerifyCode")
        public void getVerifyCode(HttpSession session, HttpServletResponse response) throws IOException {
            // 生成默认的验证码图片
            Object[] obj = VerifyUtil.newBuilder().build().createImage();
            // obj[0]是验证码的字符串,放入session
            session.setAttribute("verifyCode", obj[0]);
            // obj[1]是验证码图片
            BufferedImage image = (BufferedImage) obj[1];
            OutputStream outputStream = response.getOutputStream();
            // 设置响应类型
            response.setContentType("image/png");
            // IO输出图片
            ImageIO.write(image, "png", outputStream);
    
        }
    

    注意在ShiroConfig配置类中药放行对应的验证码请求。

    image-20200818165357022

    在login页面上添加验证码。

    <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" %>
    
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
            <h1 class="">登录首页</h1>
            <form action="${pageContext.request.contextPath}/user/login" method="post">
                用户名:<input type="text" name="username"><br/>
                密码: <input type="password" name="password"><br/>
                验证码: <input type="text" name="verifyCode"><img src="${pageContext.request.contextPath}/user/getVerifyCode"><br/>
                 <input type="submit" value="登录">
            </form>
    
    </body>
    </html>
    

    效果如下…

    image-20200818165543123

    然后在控制层中修改登录的处理,首先验证输入的验证码是否正确,如果不正确就直接返回验证码错误,不进行后面的判断;如果正确,再验证用户名和密码。这里只是做抛出异常处理。

     @PostMapping("/login")
        public String login(String username, String password, String verifyCode, HttpSession session) {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken passwordToken = new UsernamePasswordToken(username, password);
            String code = (String) session.getAttribute("verifyCode");
            try {
                if (verifyCode.equalsIgnoreCase(code)) {
                    subject.login(passwordToken);
                    return "redirect:/index.jsp";
                } else{
                    throw new RuntimeException("验证码错误!");
                }
            }catch(UnknownAccountException e){
                System.out.println("用户名错误" + e.getMessage());
            } catch(IncorrectCredentialsException e){
                System.out.println("密码错误" + e.getMessage());
            }catch (RuntimeException e){
                System.out.println("验证码错误!"+e.getMessage());
                e.printStackTrace();
            }
    
            return "redirect:/login.jsp";
        }
    

    因为自定义Realm中使用了随机盐加密,需要对盐进行序列化和反序列化处理(保存到缓存),因此需要对ByteSource建一个无参构造并实现相对应的接口。

    package club.qy.datao.salt;
    
    import org.apache.shiro.codec.Base64;
    import org.apache.shiro.codec.CodecSupport;
    import org.apache.shiro.codec.Hex;
    import org.apache.shiro.util.ByteSource;
    import org.apache.shiro.util.SimpleByteSource;
    
    import java.io.File;
    import java.io.InputStream;
    import java.io.Serializable;
    import java.util.Arrays;
    
    public class MyByteSource implements ByteSource, Serializable {
    
        public MyByteSource(){
    
        }
    
        private  byte[] bytes;
        private String cachedHex;
        private String cachedBase64;
    
        public MyByteSource(byte[] bytes) {
            this.bytes = bytes;
        }
    
        public MyByteSource(char[] chars) {
            this.bytes = CodecSupport.toBytes(chars);
        }
    
        public MyByteSource(String string) {
            this.bytes = CodecSupport.toBytes(string);
        }
    
        public MyByteSource(ByteSource source) {
            this.bytes = source.getBytes();
        }
    
        public MyByteSource(File file) {
            this.bytes = (new MyByteSource.BytesHelper()).getBytes(file);
        }
    
        public MyByteSource(InputStream stream) {
            this.bytes = (new MyByteSource.BytesHelper()).getBytes(stream);
        }
    
        public static boolean isCompatible(Object o) {
            return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
        }
    
        @Override
        public byte[] getBytes() {
            return this.bytes;
        }
    
        @Override
        public boolean isEmpty() {
            return this.bytes == null || this.bytes.length == 0;
        }
    
        @Override
        public String toHex() {
            if (this.cachedHex == null) {
                this.cachedHex = Hex.encodeToString(this.getBytes());
            }
    
            return this.cachedHex;
        }
    
        @Override
        public String toBase64() {
            if (this.cachedBase64 == null) {
                this.cachedBase64 = Base64.encodeToString(this.getBytes());
            }
    
            return this.cachedBase64;
        }
    
        @Override
        public String toString() {
            return this.toBase64();
        }
    
        @Override
        public int hashCode() {
            return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
        }
    
        @Override
        public boolean equals(Object o) {
            if (o == this) {
                return true;
            } else if (o instanceof ByteSource) {
                ByteSource bs = (ByteSource)o;
                return Arrays.equals(this.getBytes(), bs.getBytes());
            } else {
                return false;
            }
        }
    
        private static final class BytesHelper extends CodecSupport {
            private BytesHelper() {
            }
    
            public byte[] getBytes(File file) {
                return this.toBytes(file);
            }
    
            public byte[] getBytes(InputStream stream) {
                return this.toBytes(stream);
            }
        }
    }
    

    自定义Realm

    public class CustomRelam extends AuthorizingRealm {
        @Autowired
        UserService userService;
    
        // 授权
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            String username = (String) principalCollection.getPrimaryPrincipal();
            User roleByUserName = userService.findRoleByUserName(username);
            if (!CollectionUtils.isEmpty(roleByUserName.getRoles())){
                SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
                roleByUserName.getRoles().forEach(role->{
                    simpleAuthorizationInfo.addRole(role.getName());
                    //查询该角色下的所有权限然后添加到该角色中
                    List<Permission> permissions = userService.findPermissionsByRoleId(role.getId());
                    if (!CollectionUtils.isEmpty(permissions)){
                        permissions.forEach(permission -> {
                            simpleAuthorizationInfo.addStringPermission(permission.getName());
                        });
                    }
                });
    
                return simpleAuthorizationInfo;
            }
            return null;
        }
    
        //认证
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            String principal = (String) authenticationToken.getPrincipal();
            // 实际开发中 先确认传来的token用户名是否存在,如果存在且唯一,然后根据有户名查询密码返回,进而判断密码是否正确
            User user = userService.findUserByUsername(principal);
            if (!ObjectUtils.isEmpty(user)){
                SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUsername(),
                        user.getPassword(), new MyByteSource(user.getSalt()),this.getName());
                // 用户名和密码都判断完成后可以返回
                return simpleAuthenticationInfo;
            }
    
            return null;
        }
    }
    

    当输入错误的验证码时,控制台会抛出异常,并重新刷新登录界面。
    在这里插入图片描述
    在这里插入图片描述
    所有信息都验证正确后才进入首页
    在这里插入图片描述

  • 相关阅读:
    dotNet程序保护方案
    网络数据包捕获函数库Libpcap安装与使用(非常强大)
    Objectivec 中 nil, Nil, NULL和NSNull的区别
    对象的相等和恒等
    IOS SDK介绍
    iOS内存管理编程指南
    http权威指南读书笔记(三)——http报文
    http权威指南学习笔记(二)
    http权威指南读书笔记(一)
    CentOS 设置环境变量
  • 原文地址:https://www.cnblogs.com/itjiangpo/p/14181339.html
Copyright © 2011-2022 走看看