五、kaptcha实现图形验证码

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

posted @ 2023-06-07 20:32  shigp1  阅读(915)  评论(0编辑  收藏  举报