电商系统开发实战-用户微服务注册模块之验证码开发
1、介绍微服务注册功能和流程介绍
-
功能需求
- 使用邮箱注册,已经注册的邮箱不能重复注册
- 密码不能使用简单的MD5加密
- 用户上传头像需要用文件存储
-
功能演示
- 手机号 18211102098
- 邮箱 18211102098@163.com
-
安全需求
- 高并发下邮箱唯一性
- 注册邮箱或者手机验证码不能被恶意调用
- 头像文件存储访问方便扩容和管理
1.2 图形验证码开发之谷歌kaptcha引入
1.2.1 谷歌开源kaptcha图形验证码开发
Kaptcha 框架介绍 谷歌开源的一个可高度配置的实用验证码生成工具
- 验证码的字体/大小/颜色
- 验证码内容的范围(数字,字母,中文汉字!)
- 验证码图片的大小,边框,边框粗细,边框颜色
- 验证码的干扰线
- 验证码的样式(鱼眼样式、3D、普通模糊)
1.2.2 聚合工程依赖添加 (使用国内baomidou二次封装的springboot整合starter)
<!--kaptcha依赖包-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
1.2.3 用户服务添加
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>kaptcha-spring-boot-starter</artifactId>
</dependency>
1.2.4 开发配置(任何框架和springboot整合基本都是)
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class CaptchaConfig {
/**
* 验证码配置
* Kaptcha配置类名
*
* @return
*/
@Bean
@Qualifier("captchaProducer")
public DefaultKaptcha kaptcha() {
DefaultKaptcha kaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// properties.setProperty(Constants.KAPTCHA_BORDER, "yes");
// properties.setProperty(Constants.KAPTCHA_BORDER_COLOR, "220,220,220");
// //properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, "38,29,12");
// properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, "147");
// properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, "34");
// properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, "25");
// //properties.setProperty(Constants.KAPTCHA_SESSION_KEY, "code");
//验证码个数
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
// properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Courier");
//字体间隔
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_SPACE,"8");
//干扰线颜色
// properties.setProperty(Constants.KAPTCHA_NOISE_COLOR, "white");
//干扰实现类
properties.setProperty(Constants.KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
//图片样式
properties.setProperty(Constants.KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.WaterRipple");
//文字来源
properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, "0123456789");
Config config = new Config(properties);
kaptcha.setConfig(config);
return kaptcha;
}
}
1.2.5 Controller类使用测试
@Api(tags = "通知模块")
@RestController
@RequestMapping("/api/notify/v1/")
@Slf4j
public class NotifyController {
@Resource
private Producer captchaProducer;
@ApiOperation("获取图形验证码")
@RequestMapping("captch")
public void getCaptch(HttpServletRequest request, HttpServletResponse response){
String captchText = captchaProducer.createText();
log.info(captchText);
BufferedImage bufferedImage = captchaProducer.createImage(captchText);
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
ImageIO.write(bufferedImage,
"jpg", outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
log.error("获取图形验证码异常:{}", e);
}
}
}
1.3 Linux服务器Docker安装和部署容器化Redis
1.3.1 安装docker
参考连接:https://www.sundablog.com/archives/docker-an-zhuang
1.3.2 docker部署redis 并配置密码
- 如果访问不了,记得看防火墙/网络安全组端口是否开放
- 源码安装redis的话默认不能远程访问
- docker安装redis可以远程访问
docker run -itd --name xdclass-redis -p 8000:6379 redis --requirepass 123456
Options | Mean |
---|---|
-i | 以交互模式运行容器,通常与 -t 同时使用; |
-t | 为容器重新分配一个伪输入终端,通常与 -i 同时使用; |
-d | 后台运行容器,并返回容器ID; |
1.4 用户微服务开发图形验证码加入缓存
1.4.1 用户微服务配置Redis
spring:
application:
name: sundablog-user-service
redis:
host: 192.168.1.100
password: 123456
port: 8000
1.4.2 common聚合工程依赖配置
<!--redis客户端-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
1.4.3 验证码接口开发
@Api(tags = "通知模块")
@RestController
@RequestMapping("/api/notify/v1/")
@Slf4j
public class NotifyController {
@Resource
private Producer captchaProducer;
@Resource
private StringRedisTemplate stringRedisTemplate;
private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;
@ApiOperation("获取图形验证码")
@RequestMapping("captch")
public void getCaptch(HttpServletRequest request, HttpServletResponse response){
String captchText = captchaProducer.createText();
log.info(captchText);
//存储
stringRedisTemplate.opsForValue().set(getCaptchaKey(request), captchText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
BufferedImage bufferedImage = captchaProducer.createImage(captchText);
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
ImageIO.write(bufferedImage,
"jpg", outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
log.error("获取图形验证码异常:{}", e);
}
}
}
1.4.4 CommonUtil工具类
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.Random;
public class CommonUtil {
/**
* 获取ip
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) {
// "***.***.***.***".length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress="";
}
return ipAddress;
}
/**
* MD5加密
* @param data
* @return
*/
public static String MD5(String data) {
try {
java.security.MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
} catch (Exception exception) {
}
return null;
}
}