推荐并发量不高的项目,没有用到redis,不需要提前提前准备图片
package com.tongtech.utils;
import com.auth.model.model.Captcha;
import org.apache.commons.lang3.RandomUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Objects;
import java.util.Random;
public class CaptchaUtils {
/**
* 入参校验设置默认值
**/
public static void checkCaptcha(Captcha captcha) {
//设置画布宽度默认值
if (captcha.getCanvasWidth() == null) {
captcha.setCanvasWidth(320);
}
//设置画布高度默认值
if (captcha.getCanvasHeight() == null) {
captcha.setCanvasHeight(155);
}
//设置阻塞块宽度默认值
if (captcha.getBlockWidth() == null) {
captcha.setBlockWidth(65);
}
//设置阻塞块高度默认值
if (captcha.getBlockHeight() == null) {
captcha.setBlockHeight(55);
}
//设置阻塞块凹凸半径默认值
if (captcha.getBlockRadius() == null) {
captcha.setBlockRadius(9);
}
}
/**
* 获取指定范围内的随机数
**/
public static int getNonceByRange(int start, int end) {
Random random = new Random();
return random.nextInt(end - start + 1) + start;
}
/**
* 获取验证码资源图
**/
public static BufferedImage getBufferedImage(Integer canvasWidth, Integer canvasHeight) {
try {
//获取资源图片
BufferedImage image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, canvasWidth, canvasHeight);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
//定义字体形式
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int i_x = random.nextInt(canvasWidth);
int i_y = random.nextInt(canvasHeight);
int i_xl = random.nextInt(12);
int i_yl = random.nextInt(12);
g.drawLine(i_x, i_y, i_x + i_xl, i_y + i_yl);
}
return image;
} catch (Exception e) {
System.out.println("获取拼图资源失败");
//异常处理
return null;
}
}
/**
* 生成图片方法
*/
private static Color getRandColor(int cc, int bb) {
Random random = new Random();
if (cc > 255) {
cc = 255;
}
if (bb > 255) {
bb = 255;
}
int r = cc + random.nextInt(bb - cc);
int g = cc + random.nextInt(bb - cc);
int b = cc + random.nextInt(bb - cc);
return new Color(r, g, b);
}
/**
* 调整图片大小
**/
public static BufferedImage imageResize(BufferedImage bufferedImage, int width, int height) {
Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resultImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = resultImage.createGraphics();
graphics2D.drawImage(image, 0, 0, null);
graphics2D.dispose();
return resultImage;
}
/**
* 抠图,并生成阻塞块
**/
public static void cutByTemplate(BufferedImage canvasImage, BufferedImage blockImage, int blockWidth, int blockHeight, int blockRadius, int blockX, int blockY) {
BufferedImage waterImage = new BufferedImage(blockWidth, blockHeight, BufferedImage.TYPE_4BYTE_ABGR);
//阻塞块的轮廓图
int[][] blockData = getBlockData(blockWidth, blockHeight, blockRadius);
//创建阻塞块具体形状
for (int i = 0; i < blockWidth; i++) {
for (int j = 0; j < blockHeight; j++) {
try {
//原图中对应位置变色处理
if (blockData[i][j] == 1) {
//背景设置为黑色
waterImage.setRGB(i, j, Color.BLACK.getRGB());
blockImage.setRGB(i, j, canvasImage.getRGB(blockX + i, blockY + j));
//轮廓设置为白色,取带像素和无像素的界点,判断该点是不是临界轮廓点
if (blockData[i + 1][j] == 0 || blockData[i][j + 1] == 0 || blockData[i - 1][j] == 0 || blockData[i][j - 1] == 0) {
blockImage.setRGB(i, j, Color.WHITE.getRGB());
waterImage.setRGB(i, j, Color.WHITE.getRGB());
}
}
//这里把背景设为透明
else {
blockImage.setRGB(i, j, Color.TRANSLUCENT);
waterImage.setRGB(i, j, Color.TRANSLUCENT);
}
} catch (ArrayIndexOutOfBoundsException e) {
//防止数组下标越界异常
}
}
}
//在画布上添加阻塞块水印
addBlockWatermark(canvasImage, waterImage, blockX, blockY);
}
/**
* 构建拼图轮廓轨迹
**/
private static int[][] getBlockData(int blockWidth, int blockHeight, int blockRadius) {
int[][] data = new int[blockWidth][blockHeight];
double po = Math.pow(blockRadius, 2);
//随机生成两个圆的坐标,在4个方向上 随机找到2个方向添加凸/凹
//凸/凹1
int face1 = RandomUtils.nextInt(0, 4);
//凸/凹2
int face2;
//保证两个凸/凹不在同一位置
do {
face2 = RandomUtils.nextInt(0, 4);
} while (face1 == face2);
//获取凸/凹起位置坐标
int[] circle1 = getCircleCoords(face1, blockWidth, blockHeight, blockRadius);
int[] circle2 = getCircleCoords(face2, blockWidth, blockHeight, blockRadius);
//随机凸/凹类型
int shape = getNonceByRange(0, 1);
//圆的标准方程 (x-a)²+(y-b)²=r²,标识圆心(a,b),半径为r的圆
//计算需要的小图轮廓,用二维数组来表示,二维数组有两张值,0和1,其中0表示没有颜色,1有颜色
for (int i = 0; i < blockWidth; i++) {
for (int j = 0; j < blockHeight; j++) {
data[i][j] = 0;
//创建中间的方形区域
if ((i >= blockRadius && i <= blockWidth - blockRadius && j >= blockRadius && j <= blockHeight - blockRadius)) {
data[i][j] = 1;
}
double d1 = Math.pow(i - Objects.requireNonNull(circle1)[0], 2) + Math.pow(j - circle1[1], 2);
double d2 = Math.pow(i - Objects.requireNonNull(circle2)[0], 2) + Math.pow(j - circle2[1], 2);
//创建两个凸/凹
if (d1 <= po || d2 <= po) {
data[i][j] = shape;
}
}
}
return data;
}
/**
* 根据朝向获取圆心坐标
*/
private static int[] getCircleCoords(int face, int blockWidth, int blockHeight, int blockRadius) {
//上
if (0 == face) {
return new int[]{blockWidth / 2 - 1, blockRadius};
}
//左
else if (1 == face) {
return new int[]{blockRadius, blockHeight / 2 - 1};
}
//下
else if (2 == face) {
return new int[]{blockWidth / 2 - 1, blockHeight - blockRadius - 1};
}
//右
else if (3 == face) {
return new int[]{blockWidth - blockRadius - 1, blockHeight / 2 - 1};
}
return null;
}
/**
* 在画布上添加阻塞块水印
*/
private static void addBlockWatermark(BufferedImage canvasImage, BufferedImage blockImage, int x, int y) {
Graphics2D graphics2D = canvasImage.createGraphics();
graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.8f));
graphics2D.drawImage(blockImage, x, y, null);
graphics2D.dispose();
}
/**
* BufferedImage转BASE64
*/
public static String toBase64(BufferedImage bufferedImage, String type) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, type, byteArrayOutputStream);
String base64 = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
return String.format("data:image/%s;base64,%s", type, base64);
} catch (IOException e) {
System.out.println("图片资源转换BASE64失败");
//异常处理
return null;
}
}
}
package com.tongtech.auth.service;
import com.auth.component.CodeCache;
import com.auth.model.model.Captcha;
import com.tfw.backend.core.helper.ObjectHelper;
import com.utils.CaptchaUtils;
import org.springframework.stereotype.Service;
import java.awt.image.BufferedImage;
@Service
public class CaptchaService {
/**
* 校验验证码
*
* @param imageKey
* @param imageCode
* @return boolean
**/
public boolean checkImageCode(Long imageKey, Integer imageCode) {
Integer xvalue = CodeCache.coordinateMap.get(imageKey);
if (ObjectHelper.isEmpty(xvalue)) {
// "验证码已失效";
return false;
}
// 根据移动距离判断验证是否成功
if (Math.abs(imageCode - xvalue) > CodeCache.ALLOW_DEVIATION) {
// "验证失败,请控制拼图对齐缺口";
CodeCache.coordinateMap.remove(imageKey);
return false;
}
return true;
}
/**
* 缓存验证码,有效期2分钟
*
* @param key
* @param code
**/
public void saveImageCode(Long key, Integer code) {
CodeCache.coordinateMap.put(key, code);
}
/**
* 获取验证码拼图(生成的抠图和带抠图阴影的大图及抠图坐标)
**/
public Captcha getCaptcha() {
//可以设置图片高度和各种参数
Captcha captcha = new Captcha();
//参数校验
CaptchaUtils.checkCaptcha(captcha);
//获取画布的宽高
int canvasWidth = captcha.getCanvasWidth();
int canvasHeight = captcha.getCanvasHeight();
//获取阻塞块的宽高/半径
int blockWidth = captcha.getBlockWidth();
int blockHeight = captcha.getBlockHeight();
int blockRadius = captcha.getBlockRadius();
//获取资源图
BufferedImage canvasImage = CaptchaUtils.getBufferedImage(captcha.getCanvasWidth(), captcha.getCanvasHeight());
//调整原图到指定大小
canvasImage = CaptchaUtils.imageResize(canvasImage, canvasWidth, canvasHeight);
//随机生成阻塞块坐标
int blockX = CaptchaUtils.getNonceByRange(blockWidth, canvasWidth - blockWidth - 10);
int blockY = CaptchaUtils.getNonceByRange(10, canvasHeight - blockHeight + 1);
//阻塞块
BufferedImage blockImage = new BufferedImage(blockWidth, blockHeight, BufferedImage.TYPE_4BYTE_ABGR);
//新建的图像根据轮廓图颜色赋值,源图生成遮罩
CaptchaUtils.cutByTemplate(canvasImage, blockImage, blockWidth, blockHeight, blockRadius, blockX, blockY);
// 移动横坐标
Long nonceStr = System.currentTimeMillis();
// 缓存
saveImageCode(nonceStr, blockX);
//设置返回参数
captcha.setNonceStr(nonceStr);
captcha.setBlockY(blockY);
captcha.setBlockSrc(CaptchaUtils.toBase64(blockImage, "PNG"));
captcha.setCanvasSrc(CaptchaUtils.toBase64(canvasImage, "PNG"));
return captcha;
}
}
package com.auth.model.param;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
@Data
@ApiOperation(value = "登录请求参数")
public class AuthLoginParam {
@ApiModelProperty(value = "用户名")
private String loginname;
@ApiModelProperty(value = "密码")
private String password;
@ApiModelProperty(value = "验证码key")
private Long nonceStr;
@ApiModelProperty(value = "滑块验证码的x轴")
private Integer xvalue;
}
package com.auth.model.model;
import lombok.Data;
@Data
public class Captcha {
/**
* 时间戳
**/
private Long nonceStr;
/**
* 验证值
**/
private String value;
/**
* 生成的画布的base64
**/
private String canvasSrc;
/**
* 画布宽度
**/
private Integer canvasWidth;
/**
* 画布高度
**/
private Integer canvasHeight;
/**
* 生成的阻塞块的base64
**/
private String blockSrc;
/**
* 阻塞块宽度
**/
private Integer blockWidth;
/**
* 阻塞块高度
**/
private Integer blockHeight;
/**
* 阻塞块凸凹半径
**/
private Integer blockRadius;
/**
* 阻塞块的横轴坐标
**/
private Integer blockX;
/**
* 阻塞块的纵轴坐标
**/
private Integer blockY;
}
package com.tongtech.auth.controller;
import com.auth.model.param.AuthLoginParam;
import com.auth.service.CaptchaService;
import com.tfw.backend.admin.apis.biz.auth.model.TokenResponse;
import com.tfw.backend.admin.apis.biz.auth.service.AuthService;
import com.tfw.backend.admin.apis.biz.sys.user.UserHelper;
import com.tfw.backend.admin.apis.biz.sys.user.model.domain.SysUser;
import com.tfw.backend.admin.apis.biz.sys.user.service.SysUserService;
import com.tfw.backend.common.biz.models.BaseResponse;
import com.tfw.backend.common.models.supers.SuperController;
import com.tfw.backend.common.request.RequestUtil;
import com.tfw.backend.core.helper.ObjectHelper;
import com.tfw.backend.core.helper.StringHelper;
import com.utils.ResultData;
import com.utils.TokenUtil;
import com.utils.enums.ResultType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.HashMap;
@RestController
@Api(value = "用户", tags = "Auth")
@RequestMapping("/dsp/auth")
public class AuthUserController extends SuperController {
@Autowired
private CaptchaService captchaService;
@Autowired
private AuthService authService;
@Autowired
private SysUserService sysUserService;
/**
* 生成滑块验证码图片
*
* @auth guolz
*/
@ApiOperation(value = "生成验证码拼图")
@PostMapping("getrandcode")
public BaseResponse getCaptcha() {
BaseResponse response = new BaseResponse();
response.setData(captchaService.getCaptcha());
return response;
}
@ApiOperation(value = "用户登录", notes = "Auth Login 用户登录")
@PostMapping({"/login"})
public BaseResponse<ResultData> login(@RequestBody AuthLoginParam loginParam) {
BaseResponse<ResultData> baseResponse = new BaseResponse<>();
ResultData resultData = new ResultData(ResultType.ERROR_RESPONSE, null);
if (StringHelper.isEmpty(loginParam.getLoginname())
|| StringHelper.isEmpty(loginParam.getPassword())
|| ObjectHelper.isEmpty(loginParam.getNonceStr())
|| ObjectHelper.isEmpty(loginParam.getXvalue())) {
resultData.setResultType(ResultType.ERROR_RESPONSE_MISS_PARAM);
return baseResponse;
}
//校验验证码的坐标
if (!captchaService.checkImageCode(loginParam.getNonceStr(),loginParam.getXvalue())){
resultData.setResultType(ResultType.LOGIN_CODE_ERROR);
baseResponse.setData(resultData);
return baseResponse;
}
}
}
package com.auth.component;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@Data
@EnableScheduling // 开启定时任务
public class CodeCache {
public static Map<Long, Integer> coordinateMap = new ConcurrentHashMap<Long, Integer>();
@Value("${code.loginerrorlockedfrequency}")
private Integer errorLockedFrequency;
@Value("${code.deviation}")
private Integer deviation;
/**
* 登录次数限制
*/
public static Integer LOGIN_ERROR_LOCKED_FREQUENCY = 5;
/**
* 滑块验证码允许偏差
**/
public static Integer ALLOW_DEVIATION = 6;
@PostConstruct
public void init() {
//系统启动中。。。
LOGIN_ERROR_LOCKED_FREQUENCY = this.errorLockedFrequency;
ALLOW_DEVIATION = this.deviation;
}
public void clearcoordinateMap() {
//获取当前时间
long now = System.currentTimeMillis();
//过期时间两分钟
for (Long key : coordinateMap.keySet()) {
if (Math.abs(now - key) >= 60 * 1000) {
coordinateMap.remove(key);
}
}
}
@PreDestroy
public void destroy() {
//系统运行结束
coordinateMap.clear();
}
@Scheduled(cron = "0 */1 * * * ?")
public void clear() {
//每2分钟执行一次清理滑块验证码坐标
clearcoordinateMap();
}
}