开发喵星球

若依微服务版集成aj-captcha(262)

需求提出

在若依微服务版中集成AJ-Captcha滑块验证码,以提高系统的安全性和用户体验。

相关介绍

AJ-Captcha是一种滑块验证码技术,通过用户拖动滑块完成图像拼图来验证用户身份。它可以有效防止恶意刷票、注册等行为,提升系统的安全性。

解决思路

  1. 在若依微服务版的ruoyi-modules下新建一个ruoyi-captcha模块。
  2. 配置该模块的依赖和配置文件。
  3. 编写验证码控制器和配置类。
  4. 修改前端代码以支持滑块验证码。

集成aj-captcha实现滑块验证码集成包
下载链接: https://pan.baidu.com/s/1b4yMF9UAqXxf5uLW9h-_9Q?pwd=meow
提取码: meow

所需技术

项目结构

ruoyi-modules
├── ruoyi-captcha
│   ├── src
│   │   ├── main
│   │   │   ├── java
│   │   │   │   ├── com
│   │   │   │   │   ├── ruoyi
│   │   │   │   │   │   ├── captcha
│   │   │   │   │   │   │   ├── config
│   │   │   │   │   │   │   │   ├── CaptchaConfig.java
│   │   │   │   │   │   │   ├── controller
│   │   │   │   │   │   │   │   ├── CaptchaController.java
│   │   │   │   │   │   │   ├── service
│   │   │   │   │   │   │   │   ├── CaptchaCacheServiceRedisImpl.java
│   │   │   │   │   │   ├── RuoyiCaptchaApplication.java
│   ├── pom.xml
├── ruoyi-gateway
│   ├── src
│   │   ├── main
│   │   │   ├── resources
│   │   │   │   ├── application.yml
├── ruoyi-ui
│   ├── src
│   │   ├── api
│   │   │   ├── login.js
│   │   ├── views
│   │   │   ├── login.vue

注意事项

完整代码

第一步:新建ruoyi-captcha模块并添加依赖

ruoyi-modules下新建ruoyi-captcha模块,并在pom.xml中添加以下依赖:

<!-- 滑块验证码  -->
<dependency>
    <groupId>com.github.anji-plus</groupId>
    <artifactId>captcha-spring-boot-starter</artifactId>
    <version>1.2.7</version>
</dependency>

第二步:配置Nacos和Gateway

gateway的配置文件application.yml中增加滑动验证码配置:

routes:
  - id: ruoyi-captcha
    uri: lb://ruoyi-captcha
    predicates:
      - Path=/captcha/**
    filters:
      - StripPrefix=1    

并将以下路径增加白名单:

- /captcha/get
- /captcha/check
- /captcha/verify

第三步:关闭原来的验证码校验

在相关配置文件中将原来的验证码校验设置为false

第四步:新增CaptchaController.java

package com.ruoyi.captcha.controller;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @PostMapping("/get")
    public ResponseModel get(@RequestBody CaptchaVO captchaVO) {
        return captchaService.get(captchaVO);
    }

    @PostMapping("/check")
    public ResponseModel check(@RequestBody CaptchaVO captchaVO) {
        return captchaService.check(captchaVO);
    }

    @PostMapping("/verify")
    public ResponseModel verify(@RequestBody CaptchaVO captchaVO) {
        return captchaService.verification(captchaVO);
    }
}

第五步:新增CaptchaConfig.java

package com.ruoyi.captcha.config;

import com.anji.captcha.model.common.Const;
import com.anji.captcha.service.CaptchaCacheService;
import com.anji.captcha.service.CaptchaService;
import com.anji.captcha.service.impl.CaptchaServiceFactory;
import com.anji.captcha.util.ImageUtils;
import com.anji.captcha.util.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class CaptchaConfig {

    @Bean(name = "AjCaptchaCacheService")
    public CaptchaCacheService captchaCacheService() {
        return CaptchaServiceFactory.getCache("local");
    }

    @Bean
    @DependsOn("AjCaptchaCacheService")
    public CaptchaService captchaService() {
        Properties config = new Properties();
        config.put(Const.CAPTCHA_CACHETYPE, "local");
        config.put(Const.CAPTCHA_WATER_MARK, "我的水印");
        config.put(Const.CAPTCHA_FONT_TYPE, "宋体");
        config.put(Const.CAPTCHA_TYPE, "default");
        config.put(Const.CAPTCHA_INTERFERENCE_OPTIONS, "0");
        config.put(Const.ORIGINAL_PATH_JIGSAW, "");
        config.put(Const.ORIGINAL_PATH_PIC_CLICK, "");
        config.put(Const.CAPTCHA_SLIP_OFFSET, "5");
        config.put(Const.CAPTCHA_AES_STATUS, "true");
        config.put(Const.CAPTCHA_WATER_FONT, "宋体");
        config.put(Const.CAPTCHA_CACAHE_MAX_NUMBER, "1000");
        config.put(Const.CAPTCHA_TIMING_CLEAR_SECOND, "180");
        if ((StringUtils.isNotBlank(config.getProperty(Const.ORIGINAL_PATH_JIGSAW))
                && config.getProperty(Const.ORIGINAL_PATH_JIGSAW).startsWith("classpath:"))
                || (StringUtils.isNotBlank(config.getProperty(Const.ORIGINAL_PATH_PIC_CLICK))
                && config.getProperty(Const.ORIGINAL_PATH_PIC_CLICK).startsWith("classpath:"))) {
            config.put(Const.CAPTCHA_INIT_ORIGINAL, "true");
            initializeBaseMap(config.getProperty(Const.ORIGINAL_PATH_JIGSAW),
                    config.getProperty(Const.ORIGINAL_PATH_PIC_CLICK));
        }
        CaptchaService s = CaptchaServiceFactory.getInstance(config);
        return s;
    }

    private static void initializeBaseMap(String jigsaw, String picClick) {
        ImageUtils.cacheBootImage(getResourcesImagesFile(jigsaw + "/original/*.png"),
                getResourcesImagesFile(jigsaw + "/slidingBlock/*.png"),
                getResourcesImagesFile(picClick + "/*.png"));
    }

    public static Map<String, String> getResourcesImagesFile(String path) {
        Map<String, String> imgMap = new HashMap<>();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = resolver.getResources(path);
            for (Resource resource : resources) {
                byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
                String string = Base64Utils.encodeToString(bytes);
                String filename = resource.getFilename();
                imgMap.put(filename, string);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imgMap;
    }
}

第六步:新增CaptchaCacheServiceRedisImpl

package com.ruoyi.captcha.service;

import com.anji.captcha.service.CaptchaCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class CaptchaCacheServiceRedisImpl implements CaptchaCacheService {

    @Override
    public String type() {
        return "redis";
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void set(String key, String value, long expiresInSeconds) {
        stringRedisTemplate.opsForValue().set(key, value, expiresInSeconds, TimeUnit.SECONDS);
    }

    @Override
    public boolean exists(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    @Override
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
}

第七步:修改RuoyiCaptchaApplication

package com.ruoyi.captcha;

import com.ruoyi.common.security.annotation.EnableCustomConfig;
import com.ruoyi.common.security.annotation.EnableRyFeignClients;
import com.ruoyi.common.swagger.annotation.EnableCustomSwagger2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableCustomConfig
@EnableCustomSwagger2
@EnableRyFeignClients
@SpringBootApplication
public class RuoyiCaptchaApplication {
    public static void main(String[] args) {
        SpringApplication.run(RuoyiCaptchaApplication.class, args);
        System.out.println("(♥◠‿◠)ノ゙  验证码模块启动成功   ლ(´ڡ`ლ)゙  \n" +
                " .-------.       ____     __        \n" +
                " |  _ _   \\      \\   \\   /  /    \n" +
                " | ( ' )  |       \\  _. /  '       \n" +
                " |(_ o _) /        _( )_ .'         \n" +
                " | (_,_).' __  ___(_ o _)'          \n" +
                " |  |\\ \\  |  ||   |(_,_)'         \n" +
                " |  | \\ `'   /|   `-'  /           \n" +
                " |  |  \\    /  \\      /           \n" +
                " ''-'   `'-'    `-..-'              ");
    }
}

第八步:前端代码修改

ruoyi-ui中安装依赖:

npm install crypto-js --save-dev

然后按照目录结构替换api/login.jsviews/login.vue,并复制静态资源和组件。

运行结果

集成完成后,启动ruoyi-captcha模块并访问相关接口,可以看到滑动验证码功能已经成功集成。前端在登录时会显示滑动验证码,用户需要完成滑动操作才能继续登录。

   
分类:Java/OOP 作者:无限繁荣, 吴蓉 发表于:2024-07-07 04:08:25 阅读量:87
<<   >>


powered by kaifamiao