登陸前端代碼
<template #append>
<div class="login-code">
<span
class="login-code-img"
@click="refreshCode"
v-if="code.type === 'text'"
>{{ code.value }}</span
>
<img
:src="code.src"
class="login-code-img"
@click="refreshCode"
v-else
/>
</div>
</template>
刷新驗證碼代碼
refreshCode() {
this.loginForm.code = "";
this.loginForm.randomStr = randomLenNum(this.code.len, true);
this.code.type === "text"
? (this.code.value = randomLenNum(this.code.len))
: (this.code.src = `${this.baseUrl}/code?randomStr=${this.loginForm.randomStr}`);
}
驗證碼配置開關
前端開關
位于website.js中配置validateCode屬性
validateCode: true,//是否開啟驗證碼校驗
后端開關
位于pig-gateway-dev.yml配置文件
# 不校驗驗證碼終端
gateway:
encode-key: 'thanks,pig4cloud'
ignore-clients:
- test
- client
生成驗證碼
pig-gate-way模塊pom.xml
<!--驗證碼 源碼: https://github.com/pig-mesh/easy-captcha -->
<dependency>
<groupId>com.pig4cloud.plugin</groupId>
<artifactId>captcha-spring-boot-starter</artifactId>
<version>${captcha.version}</version>
</dependency>
captcha-spring-boot-starter
中對驗證碼進行了配置区赵,這里不詳細展開說明传趾。
基于webflux生成驗證碼
@Slf4j
@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class RouterFunctionConfiguration {
private final ImageCodeHandler imageCodeHandler;
@Bean
public RouterFunction<ServerResponse> routerFunction() {
return RouterFunctions.route(
RequestPredicates.path("/code").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), imageCodeHandler);
}
}
RouterFunctionConfiguration
用來注冊一個路由和它的處理程序罩扇。
proxyBeanMethods配置類是用來指定@Bean注解標注的方法是否使用代理,默認是true使用代理竹习,直接從IOC容器之中取得對象;如果設置為false,也就是不使用注解帮坚,每次調用@Bean標注的方法獲取到的對象和IOC容器中的都不一樣踩身,是一個新的對象萤晴。
Spring 5.2.0+的版本吐句,建議你的配置類均采用Lite模式去做,即顯示設置proxyBeanMethods = false店读。Spring Boot在2.2.0版本(依賴于Spring 5.2.0)起就把它的所有的自動配置類的此屬性改為了false嗦枢,即@Configuration(proxyBeanMethods = false),提高Spring啟動速度屯断。
RouterFunction
為我們應用程序添加一個新的路由文虏,這個路由需要綁定一個HandlerFunction
,做為它的處理程序殖演,里面可以添加業(yè)務代碼氧秘。
ImageCodeHandler
@Slf4j
@RequiredArgsConstructor
public class ImageCodeHandler implements HandlerFunction<ServerResponse> {
private static final Integer DEFAULT_IMAGE_WIDTH = 100;
private static final Integer DEFAULT_IMAGE_HEIGHT = 40;
private final RedisTemplate<String, Object> redisTemplate;
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
ArithmeticCaptcha captcha = new ArithmeticCaptcha(DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
String result = captcha.text();
// 保存驗證碼信息
Optional<String> randomStr = serverRequest.queryParam("randomStr");
redisTemplate.setKeySerializer(new StringRedisSerializer());
randomStr.ifPresent(s -> redisTemplate.opsForValue().set(CacheConstants.DEFAULT_CODE_KEY + s, result,
SecurityConstants.CODE_TIME, TimeUnit.SECONDS));
// 轉換流信息寫出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
captcha.out(os);
return ServerResponse.status(HttpStatus.OK).contentType(MediaType.IMAGE_JPEG)
.body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
}
}
校驗驗證碼
網(wǎng)關配置
在pig-gateway-dev.yml
中配置ValidateCodeGatewayFilter
校驗驗證碼
public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
// 終端設置不校驗, 直接向下執(zhí)行
String[] clientInfos = WebUtils.getClientId(request);
if (filterIgnorePropertiesConfig.getClients().contains(clientInfos[0])) {
return chain.filter(exchange);
}
//校驗驗證碼
checkCode(request);
return chain.filter(exchange);
};
}
}
checkCode
方法
@SneakyThrows
private void checkCode(ServerHttpRequest request) {
String code = request.getQueryParams().getFirst("code");
if (CharSequenceUtil.isBlank(code)) {
throw new ValidateCodeException("驗證碼不能為空");
}
String randomStr = request.getQueryParams().getFirst("randomStr");
if (CharSequenceUtil.isBlank(randomStr)) {
randomStr = request.getQueryParams().getFirst(SecurityConstants.SMS_PARAMETER_NAME);
}
String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;
Object codeObj = redisTemplate.opsForValue().get(key);
if (ObjectUtil.isEmpty(codeObj) || !code.equals(codeObj)) {
throw new ValidateCodeException("驗證碼不合法");
}
redisTemplate.delete(key);
}