首页 > 其他分享 >五、kaptcha实现图形验证码

五、kaptcha实现图形验证码

时间:2023-06-07 20:44:33浏览次数:58  
标签:return String -- kaptcha 验证码 new 图形 public

Kaptcha是谷歌开源的可高度配置的实用验证码生成工具。

一、验证码配置

加入依赖:

<dependency>
        <groupId>com.github.penggle</groupId>
        <artifactId>kaptcha</artifactId>
        <version>2.3.2</version>
    </dependency>

 

生成验证码配置:

@Configuration
public class KaptchaConfig {
 
    //DefaultKaptcha是Producer的实现类
    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

 

新增验证码controller:

@Controller
@Slf4j
public class KaptchaController {
    @Autowired
    private Producer producer;


    @GetMapping("/verify_code")
    public  Mono<Void>  createVerifyCode(ServerWebExchange webExchange) throws IOException {
        //生成验证码字符文本
        String verifyCode = producer.createText();
        log.info("生成的验证码:{}", verifyCode);
        /**
         * 将验证码保存到session中
         */
        webExchange.getSession().map(webSession -> {
            webSession.getAttributes().put("kaptchaVerifyCode",verifyCode);
            return Mono.empty();
        }).subscribe();

        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        BufferedImage image = producer.createImage(verifyCode);
        try {
            ImageIO.write(image, "jpeg", os);
        } catch (IOException e) {
            log.error("ImageIO write err", e);
            return Mono.empty();
        }

        webExchange.getResponse().getHeaders().add("Content-type","image/jpeg");
        /**
         * 将验证码图片转成DataBuffer并写入到客户端
         */
        Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read(new ByteArrayResource(os.toByteArray()), webExchange.getResponse().bufferFactory(), 1024 * 8);

        return webExchange.getResponse().writeAndFlushWith(t -> {
            t.onSubscribe(new Subscription() { // 这步是必须的,不然可能生成不了验证码
                @Override
                public void request(long l) {

                }

                @Override
                public void cancel() {

                }
            });
            t.onNext(dataBufferFlux);
            t.onComplete();
        });
    }
}

 

二、表单登录使用验证码

修改MyReactiveSecurityConfig配置类,将/verify_code放开权限校验:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
            .authorizeExchange(exchanges -> exchanges
                    .pathMatchers(LOGIN_PAGE).permitAll()
                    .pathMatchers("/verify_code").permitAll()
                    .anyExchange().authenticated()
            )
           // .httpBasic().disable()
         //   .formLogin().disable()
            .formLogin()
            .loginPage(LOGIN_PAGE)
            .and()
           // .loginPage(LOGIN_PAGE)
          //  .and()
            .csrf().disable();

    http.addFilterAt(authenticationManager(), SecurityWebFiltersOrder.FORM_LOGIN);
    return http.build();
}

 

自定义AuthenticationWebFilter:

@Bean
public ReactiveAuthenticationManager userDetailsRepositoryReactiveAuthenticationManager() {
    UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager(this.reactiveUserDetailsService);
    manager.setPasswordEncoder(passwordEncoder());
    manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
    return manager;
}

@Bean
public AuthenticationWebFilter authenticationManager() {
    AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(userDetailsRepositoryReactiveAuthenticationManager());
    authenticationFilter.setRequiresAuthenticationMatcher(ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, LOGIN_PAGE));
    authenticationFilter.setAuthenticationFailureHandler(new RedirectServerAuthenticationFailureHandler(LOGIN_PAGE + "?error"));
    authenticationFilter.setAuthenticationConverter(new KaptchServerAuthenticationConverter());
    authenticationFilter.setAuthenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/"));
    authenticationFilter.setSecurityContextRepository(new WebSessionServerSecurityContextRepository());
    return authenticationFilter;
}

 

增加验证码解析类:

@Slf4j
public class KaptchServerAuthenticationConverter extends ServerFormLoginAuthenticationConverter {

    private ObjectMapper objectMapper = new ObjectMapper();

    private String usernameParameter = "username";

    private String passwordParameter = "password";

    private String kaptchaParamter = "kaptchaVerifyCode";


    public KaptchServerAuthenticationConverter() {

    }

    public KaptchServerAuthenticationConverter(String usernameParameter, String passwordParameter,String kaptchaParamter) {
        this.usernameParameter = usernameParameter;
        this.passwordParameter = passwordParameter;
        this.kaptchaParamter = kaptchaParamter;
    }

    public Mono<Authentication> apply(ServerWebExchange exchange) {
        return exchange.getFormData().map(data -> {
          return   data.getFirst(kaptchaParamter);
        }).zipWith(exchange.getSession().map(webSession -> {
            return webSession.getAttribute(kaptchaParamter);
                })).map(t-> {
            String t1 = t.getT1();
            Object t2 = t.getT2();

            log.info("前端传来的验证码:{},session中的验证码:{}", t1, t2);
            if (!Objects.equals(t1, t2)) {
                throw new KaptchaAuthenticationException("验证码不正确");
            } else {
                return Mono.empty();
            }
        }).flatMap(t -> {
            return super.apply(exchange);
        });
    }
}

public class KaptchaAuthenticationException extends AuthenticationException {
    public KaptchaAuthenticationException(String msg, Throwable cause) {
        super(msg, cause);
    }

    public KaptchaAuthenticationException(String msg) {
        super(msg);
    }
}

调用父类super.apply解析用户名和密码,在解析用户名和密码之前对比前端传过来的验证码和WebSession中的验证码是否一致。不一致则抛出KaptchaAuthenticationException。

 

修改登录页doLogin.html:

<!DOCTYPE html>
<html lang="en">
<!-- https://codepen.io/danielkvist/pen/LYNVyPL -->
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        :root {
            /* COLORS */
            --white: #e9e9e9;
            --gray: #333;
            --blue: #0367a6;
            --lightblue: #008997;

            /* RADII */
            --button-radius: 0.7rem;

            /* SIZES */
            --max-width: 758px;
            --max-height: 420px;

            font-size: 16px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
            Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
        }

        body {
            align-items: center;
            background-color: var(--white);
            background: url("https://res.cloudinary.com/dbhnlktrv/image/upload/v1599997626/background_oeuhe7.jpg");
            /* 决定背景图像的位置是在视口内固定,或者随着包含它的区块滚动。 */
            /* https://developer.mozilla.org/zh-CN/docs/Web/CSS/background-attachment */
            background-attachment: fixed;
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
            display: grid;
            height: 100vh;
            place-items: center;
        }

        .form__title {
            font-weight: 300;
            margin: 0;
            margin-bottom: 1.25rem;
        }

        .link {
            color: var(--gray);
            font-size: 0.9rem;
            margin: 1.5rem 0;
            text-decoration: none;
        }

        .container {
            background-color: var(--white);
            border-radius: var(--button-radius);
            box-shadow: 0 0.9rem 1.7rem rgba(0, 0, 0, 0.25),
            0 0.7rem 0.7rem rgba(0, 0, 0, 0.22);
            height: var(--max-height);
            max-width: var(--max-width);
            overflow: hidden;
            position: relative;
            width: 100%;
        }

        .container__form {
            height: 100%;
            position: absolute;
            top: 0;
            transition: all 0.6s ease-in-out;
        }

        .container--signin {
            left: 0;
            width: 50%;
            z-index: 2;
        }

        .container.right-panel-active .container--signin {
            transform: translateX(100%);
        }

        .container--signup {
            left: 0;
            opacity: 0;
            width: 50%;
            z-index: 1;
        }

        .container.right-panel-active .container--signup {
            animation: show 0.6s;
            opacity: 1;
            transform: translateX(100%);
            z-index: 5;
        }

        .container__overlay {
            height: 100%;
            left: 50%;
            overflow: hidden;
            position: absolute;
            top: 0;
            transition: transform 0.6s ease-in-out;
            width: 50%;
            z-index: 100;
        }

        .container.right-panel-active .container__overlay {
            transform: translateX(-100%);
        }

        .overlay {
            background-color: var(--lightblue);
            background: url("https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547_1280.jpg");
            background-attachment: fixed;
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
            height: 100%;
            left: -100%;
            position: relative;
            transform: translateX(0);
            transition: transform 0.6s ease-in-out;
            width: 200%;
        }

        .container.right-panel-active .overlay {
            transform: translateX(50%);
        }

        .overlay__panel {
            align-items: center;
            display: flex;
            flex-direction: column;
            height: 100%;
            justify-content: center;
            position: absolute;
            text-align: center;
            top: 0;
            transform: translateX(0);
            transition: transform 0.6s ease-in-out;
            width: 50%;
        }

        .overlay--left {
            transform: translateX(-20%);
        }

        .container.right-panel-active .overlay--left {
            transform: translateX(0);
        }

        .overlay--right {
            right: 0;
            transform: translateX(0);
        }

        .container.right-panel-active .overlay--right {
            transform: translateX(20%);
        }

        .btn {
            background-color: var(--blue);
            background-image: linear-gradient(90deg, var(--blue) 0%, var(--lightblue) 74%);
            border-radius: 20px;
            border: 1px solid var(--blue);
            color: var(--white);
            cursor: pointer;
            font-size: 0.8rem;
            font-weight: bold;
            letter-spacing: 0.1rem;
            padding: 0.9rem 4rem;
            text-transform: uppercase;
            transition: transform 80ms ease-in;
        }

        .form>.btn {
            margin-top: 1.5rem;
        }

        .btn:active {
            transform: scale(0.95);
        }

        .btn:focus {
            outline: none;
        }

        .form {
            background-color: var(--white);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            padding: 0 3rem;
            height: 100%;
            text-align: center;
        }

        .input {
            background-color: #fff;
            border: none;
            padding: 0.9rem 0.9rem;
            margin: 0.5rem 0;
            width: 88%;
        }

        @keyframes show {

            0%,
            49.99% {
                opacity: 0;
                z-index: 1;
            }

            50%,
            100% {
                opacity: 1;
                z-index: 5;
            }
        }
    </style>
</head>

<body>
<div class="container right-panel-active">

    <!-- Sign In -->
    <div class="container__form container--signin">
        <form action="/doLogin" class="form" id="form2" method="post">
            <h2 class="form__title">Sign In</h2>
            <div style="width: 100%">
                <input type="text" placeholder="username" class="input" name="username"/>
            </div>

            <div style="width: 100%">
                <input type="password" placeholder="Password" class="input" name="password"/>
            </div>

            <div style="display: flex">
                <div style="width: 70%">
                    <input type="text" placeholder="验证码" class="input" name="kaptchaVerifyCode"/>
                </div>

                <div style="width: 30%">
                    <img src="/verify_code"
                    style="margin: 10% 0"
                         width="80%"
                         height="70%"
                         id="kapche_img"
                    onclick="refreshCode()"
                   />
                </div>
            </div>
            <a href="#" class="link">Forgot your password?</a>
            <button class="btn">Sign In</button>
        </form>
    </div>

    <!-- Overlay -->
    <div class="container__overlay">
        <div class="overlay">
            <div class="overlay__panel overlay--left">
                <button class="btn" id="signIn">Sign In</button>
            </div>
            <div class="overlay__panel overlay--right">
                <button class="btn" id="signUp">Sign Up</button>
            </div>
        </div>
    </div>
</div>

<script>
    const signInBtn = document.getElementById("signIn");
    const signUpBtn = document.getElementById("signUp");
    const fistForm = document.getElementById("form1");
    const secondForm = document.getElementById("form2");
    const container = document.querySelector(".container");

    signInBtn.addEventListener("click", () => {
      container.classList.remove("right-panel-active");
    });

    signUpBtn.addEventListener("click", () => {
      container.classList.add("right-panel-active");
    });

    fistForm.addEventListener("submit", (e) => e.preventDefault());
    secondForm.addEventListener("submit", (e) => e.preventDefault());


    function refreshCode(e) {
        document.getElementById("kapche_img").src = "/verify_code?date="+(new Date())
    }
  </script>
</body>

</html>

点击验证码图片可以刷新验证码。

三、JSON格式登录使用验证码

修改JsonServerAuthenticationConverter增加验证码判断:

@Slf4j
public class JsonServerAuthenticationConverter extends ServerFormLoginAuthenticationConverter {

    private ObjectMapper objectMapper = new ObjectMapper();

    private String usernameParameter = "username";

    private String passwordParameter = "password";

    private String kaptchaParamter = "kaptchaVerifyCode";


    public JsonServerAuthenticationConverter() {

    }

    public JsonServerAuthenticationConverter(String usernameParameter,String passwordParameter, String kaptchaParamter) {
        this.usernameParameter = usernameParameter;
        this.passwordParameter = passwordParameter;
        this.kaptchaParamter = kaptchaParamter;
    }

    public Mono<Authentication> apply(ServerWebExchange exchange) {

        return exchange.getRequest().getBody().map(t -> {
            String s = t.toString(StandardCharsets.UTF_8);
            log.info("参数:{}",s);
            Map<String , Object> map = null;
            try {
                map = objectMapper.readValue(s, Map.class);
            } catch (JsonProcessingException e) {
               log.info("解析JSON参数异常",e);
               map = null;
            }

            return map;
        }).zipWith(exchange.getSession().map(session -> {
          return  session.getAttribute(kaptchaParamter);
        })).map(tuple -> {
            Map<String, Object> map = tuple.getT1();
            Object t2 = tuple.getT2();

            if (map != null && !map.isEmpty()) {
                log.info("前端传来的验证码:{},session中的验证码:{}", map.get(kaptchaParamter), t2);
                if (!Objects.equals(map.get(kaptchaParamter),t2)) {
                    throw new KaptchaAuthenticationException("验证码不正确");
                } else {
                    String username = (String) map.get(usernameParameter);
                    String password = (String) map.get(passwordParameter);

                    Authentication unauthenticated = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
                    return unauthenticated;
                }
            }
            return null;
        }).next();
    }
}

 

修改配置MyReactiveSecurityConfig:

 @Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
            .authorizeExchange(exchanges -> exchanges
                    .pathMatchers(LOGIN_PAGE).permitAll()
                    .pathMatchers("/verify_code").permitAll()
                    .anyExchange().authenticated()
            )
            .httpBasic().disable()
            .formLogin().disable()
            .csrf().disable();

    http.addFilterAt(authenticationManager(), SecurityWebFiltersOrder.FORM_LOGIN);
    return http.build();
}


@Bean
public ReactiveAuthenticationManager userDetailsRepositoryReactiveAuthenticationManager() {
    UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager(this.reactiveUserDetailsService);
    manager.setPasswordEncoder(passwordEncoder());
    manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
    return manager;
}

@Bean
public AuthenticationWebFilter authenticationManager() {
    AuthenticationWebFilter authenticationFilter = new AuthenticationWebFilter(userDetailsRepositoryReactiveAuthenticationManager());
    authenticationFilter.setRequiresAuthenticationMatcher(ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, LOGIN_PAGE));
    authenticationFilter.setAuthenticationFailureHandler((webFilterExchange, exception) -> {
        log.info("认证异常",exception);
        ServerWebExchange exchange = webFilterExchange.getExchange();

        exchange.getResponse().getHeaders().add("Content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);

        Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read(new ByteArrayResource("认证失败".getBytes(StandardCharsets.UTF_8)), exchange.getResponse().bufferFactory(), 1024 * 8);

        return exchange.getResponse().writeAndFlushWith(t -> {
            t.onSubscribe(new Subscription() {
                @Override
                public void request(long l) {

                }

                @Override
                public void cancel() {

                }
            });
            t.onNext(dataBufferFlux);
            t.onComplete();
        });
    });
    authenticationFilter.setAuthenticationConverter(new JsonServerAuthenticationConverter());
    authenticationFilter.setAuthenticationSuccessHandler((webFilterExchange, authentication) -> {
        log.info("认证成功:{}",authentication);
        ServerWebExchange exchange = webFilterExchange.getExchange();

        exchange.getResponse().getHeaders().add("Content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);

        Flux<DataBuffer> dataBufferFlux = DataBufferUtils.read(new ByteArrayResource("认证成功".getBytes(StandardCharsets.UTF_8)), exchange.getResponse().bufferFactory(), 1024 * 8);

        return exchange.getResponse().writeAndFlushWith(t -> {
            t.onSubscribe(new Subscription() {
                @Override
                public void request(long l) {

                }

                @Override
                public void cancel() {

                }
            });
            t.onNext(dataBufferFlux);
            t.onComplete();
        });
    });
    authenticationFilter.setSecurityContextRepository(new WebSessionServerSecurityContextRepository());
    return authenticationFilter;
}

 

用Postman调用http://localhost:8080/verify_code获取验证码,在调用http://localhost:8080/doLogin进行登录。

 

 

 

参考:https://blog.csdn.net/weixin_44014864/article/details/128629697
参考:https://blog.csdn.net/m0_47119893/article/details/122397803
参考:https://blog.csdn.net/wstever/article/details/128698695

标签:return,String,--,kaptcha,验证码,new,图形,public
From: https://www.cnblogs.com/shigongp/p/17464433.html

相关文章

  • 简单的图形界面
    以下是一个更加复杂的C++代码,它的作用是实现一个简单的图形界面,通过鼠标点击和键盘输入来操作和控制图形界面:#include<iostream>#include<graphics.h>usingnamespacestd;intmain(){initgraph(640,480);//初始化图形界面setbkcolor(WHITE);//设置背景色为......
  • 图形数学:线性代数
    一.向量加法(X1)  (X2)   (X1+X2)(Y1)+(Y2)= (Y1+Y2)(Z1)  (Z2)   (Z1+Z2) 二.向量减法(X1)  (X2)   (X1-X2)(Y1)- (Y2)= (Y1-Y2)(Z1)  (Z2)   (Z1-Z2) 三.向量乘法注意:这里是shader的向量颜色乘......
  • Ubuntu开关图形界面
    systemctlset-defaultmulti-user.target#关闭图形界面systemctlset-defaultgraphical.target#打开图形界面关闭:在图形界面下终端输入sudoservicelightdmstop开启:在命令行输入:sudoservicelightdmstartubuntu20.04关闭图形界面关闭用户图形界面,使用tty登录......
  • java 图形学 点和闭合区域位置关系判断
    判断一个点是否在一个特定的区域内或外,通常需要你具备区域的数学表达(例如,方程、不等式等)以及要判断的点的坐标。例如,如果你有一个圆的方程(x-h)²+(y-k)²=r²,其中(h,k)是圆心,r是半径,你要判断点(a,b)是否在此圆内或外。你可以将点(a,b)的坐标带入这个方程:如果(a......
  • springboot 发送邮箱验证码
    0步骤总览开启邮箱的POP3/SMTP服务。新建springboot项目。导入依赖。配置配置文件。编写controller测试接口。postman中测试1开启邮箱的POP3/SMTP服务这里我用的网易邮箱,其它邮箱类似步骤,不清楚的可以百度。总之就是要打开pop3/smtp服务,如果按照我的方法......
  • 类GeometricShapeFactory-JTS几何图形绘制API
    org.locationtech.jts.util类GeometricShapeFactoryjava.lang.Objectorg.locationtech.jts.util.GeometricShapeFactory直接已知子类:正弦之星工厂公共类GeometricShapeFactory扩展Object计算各种常见的几何形状。提供各种方法来指定所生成形状的位置,范围和旋转,以及用于形成它们......
  • random模块生成六位随机数字+大小写验证码
    random模块生成六位随机数字+大小写验证码【一】代码importrandom'''生成六位随机(数字+大小写)验证码'''defget_verify_code(n):code=''foriinrange(n):random_int=str(random.randint(0,9))#0-9之间的整数random_upper......
  • 银河麒麟服务器V10 SP3 安装ZooKeeperZookeeper 图形化的客户端工具(ZooInspector)
    服务器zookeeper安装一、软件介绍1、ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。2、ZooKeeper的原理......
  • 案例补充:random模块模拟随机验证码登陆验证
    案例补充:random模块模拟随机验证码登陆验证***用到的知识点【一】random模块产生随机数字(1)产生0-9之间的随机整数importrandomrandom_int=str(random.randint(0,9))(2)产生A-Z之间的字母importrandomrandom_upper=chr(random.randint(65,90))(3)产生a-z之间的字......
  • 解决谷歌验证码问题
    浏览器右键F12,打开控制台,输入以下代码: !(function(){"usestrict";document.querySelectorAll("script").forEach(function(e){if(e.src.indexOf("googleapis.com")>=0||e.src.indexOf("themes.googleuserconten......