Commit cd112ea9 authored by wujipeng's avatar wujipeng
Browse files

init

parents
Pipeline #346 canceled with stages
package com.platform.gateway.filter;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.platform.constants.SecurityConstants;
import com.platform.utils.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author zhuxiang
* 密码解密工具类
*/
@Slf4j
@Component
public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {
private static final String PASSWORD = "password";
private static final String KEY_ALGORITHM = "AES";
@Value("${security.encode.key:1234567812345678}")
private String encodeKey;
@SneakyThrows
private static String decryptAES(String data, String pass) {
AES aes = new AES(Mode.CBC,Padding.NoPadding,
new SecretKeySpec(pass.getBytes(), KEY_ALGORITHM),
new IvParameterSpec(pass.getBytes()));
byte[] result = aes.decrypt(Base64.decode(data.getBytes(StandardCharsets.UTF_8)));
return new String(result, StandardCharsets.UTF_8);
}
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
// 不是登录请求,直接向下执行
if (!CharSequenceUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstants.OAUTH_TOKEN_URL)) {
return chain.filter(exchange);
}
URI uri = exchange.getRequest().getURI();
String queryParam = uri.getRawQuery();
Map<String, String> paramMap = HttpUtil.decodeParamMap(queryParam, StandardCharsets.UTF_8);
String password = paramMap.get(PASSWORD);
if (StringUtils.isNotEmpty(password)) {
try {
password = decryptAES(password, encodeKey);
} catch (Exception e) {
log.error("密码解密失败:{}", password);
return Mono.error(e);
}
paramMap.put(PASSWORD, password.trim());
}
URI newUri = UriComponentsBuilder.fromUri(uri)
.replaceQuery(HttpUtil.toParams(paramMap))
.build(true)
.toUri();
ServerHttpRequest newRequest = exchange.getRequest().mutate().uri(newUri).build();
return chain.filter(exchange.mutate().request(newRequest).build());
};
}
}
package com.platform.gateway.filter;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.cache.constant.CacheConstants;
import com.platform.constants.SecurityConstants;
import com.platform.gateway.exception.ValidateCodeException;
import com.platform.model.resp.Result;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
/**
* 验证码处理
*
* @author zhuxiang
*/
@Slf4j
@Component
@AllArgsConstructor
public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
private final ObjectMapper objectMapper;
private final RedisTemplate redisTemplate;
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
// 不是登录请求,直接向下执行
if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath()
, SecurityConstants.OAUTH_TOKEN_URL, SecurityConstants.PHONE_SMS_TOKEN_URL)) {
return chain.filter(exchange);
}
// 刷新token,直接向下执行
String grantType = request.getQueryParams().getFirst("grant_type");
if (StrUtil.equals(SecurityConstants.REFRESH_TOKEN, grantType)) {
return chain.filter(exchange);
}
try {
//校验验证码
checkCode(request);
} catch (Exception e) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
try {
return response.writeWith(Mono.just(response.bufferFactory()
.wrap(objectMapper.writeValueAsBytes(
Result.fail(e.getMessage())))));
} catch (JsonProcessingException e1) {
log.error("对象输出异常", e1);
}
}
return chain.filter(exchange);
};
}
/**
* 检查code
*
* @param request request
*/
@SneakyThrows
private void checkCode(ServerHttpRequest request) {
String code = request.getQueryParams().getFirst("code");
if (StrUtil.isBlank(code)) {
throw new ValidateCodeException("验证码不能为空");
}
String randomStr = request.getQueryParams().getFirst("randomStr");
String grantType = request.getQueryParams().getFirst("grant_type");
if (StrUtil.equals(SecurityConstants.SMS_LOGIN, grantType)) {
randomStr = SecurityConstants.SMS_LOGIN + ":" + request.getQueryParams().getFirst("phone");
}
String key = CacheConstants.VER_CODE_DEFAULT + randomStr;
redisTemplate.setKeySerializer(new StringRedisSerializer());
if (!redisTemplate.hasKey(key)) {
throw new ValidateCodeException("验证码不合法");
}
Object codeObj = redisTemplate.opsForValue().get(key);
if (codeObj == null) {
throw new ValidateCodeException("验证码不合法");
}
String saveCode = codeObj.toString();
if (StrUtil.isBlank(saveCode)) {
redisTemplate.delete(key);
throw new ValidateCodeException("验证码不合法");
}
if (!StrUtil.equals(saveCode, code)) {
throw new ValidateCodeException("验证码不合法");
}
redisTemplate.delete(key);
}
}
package com.platform.gateway.handler;
import cn.hutool.json.JSONUtil;
import com.platform.model.resp.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import java.util.Optional;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR;
/**
* @author zhuxiang
* Hystrix 降级处理
*/
@Slf4j
@Component
public class HystrixFallbackHandler implements HandlerFunction<ServerResponse> {
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
Optional<Object> originalUris = serverRequest.attribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
originalUris.ifPresent(originalUri -> log.error("网关执行请求:{}失败,hystrix服务降级处理", originalUri));
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR.value()).contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(JSONUtil.toJsonStr(Result.fail("服务已被降级熔断"))));
}
}
package com.platform.gateway.init;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.platform.constants.Constants;
import com.platform.gateway.entity.GatewayRouteList;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.annotation.Configuration;
import org.yaml.snakeyaml.Yaml;
import reactor.core.publisher.Mono;
import javax.annotation.PostConstruct;
import java.util.Properties;
import java.util.concurrent.Executor;
/**
* @author <zhuxiang
* 初始化网关路由
*/
@Slf4j
@Configuration
@AllArgsConstructor
public class DynamicRouteInit {
private RouteDefinitionWriter routeDefinitionWriter;
private NacosConfigProperties nacosProperties;
@PostConstruct
public void initRoute() {
try {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, nacosProperties.getServerAddr());
properties.put(PropertyKeyConst.USERNAME, nacosProperties.getUsername());
properties.put(PropertyKeyConst.PASSWORD, nacosProperties.getPassword());
properties.put(PropertyKeyConst.NAMESPACE, nacosProperties.getNamespace());
ConfigService configService = NacosFactory.createConfigService(properties);
String content = configService.getConfig(Constants.CONFIG_DATA_ID, Constants.CONFIG_GROUP, Constants.CONFIG_TIMEOUT_MS);
log.info("初始化网关路由开始");
updateRoute(content);
log.info("初始化网关路由完成");
//开户监听,实现动态
configService.addListener(Constants.CONFIG_DATA_ID, Constants.CONFIG_GROUP, new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
log.info("更新网关路由开始");
updateRoute(configInfo);
log.info("更新网关路由完成");
}
@Override
public Executor getExecutor() {
return null;
}
});
} catch (NacosException e) {
log.error("加载路由出错:{}", e.getErrMsg());
}
}
public void updateRoute(String content) {
Yaml yaml = new Yaml();
GatewayRouteList gatewayRouteList = yaml.loadAs(content, GatewayRouteList.class);
gatewayRouteList.getRoutes().forEach(route -> {
log.info("加载路由:{},{}", route.getId(), route);
routeDefinitionWriter.save(Mono.just(route)).subscribe();
});
}
}
spring:
application:
name: practical-train-gateway
# 配置中心
cloud:
nacos:
discovery:
server-addr: ${NACOS-HOST:192.168.10.3}:${NACOS-PORT:6001}
namespace: 272b9958-7a2d-41f8-ba0b-fdcb7ee8ead0
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
file-extension: yml
namespace: 272b9958-7a2d-41f8-ba0b-fdcb7ee8ead0
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
spring:
application:
name: practical-train-gateway
# 配置中心
cloud:
nacos:
discovery:
server-addr: ${NACOS-HOST:47.111.94.26}:${NACOS-PORT:8848}
namespace: 272b9958-7a2d-41f8-ba0b-fdcb7ee8ead0
config:
server-addr: ${spring.cloud.nacos.discovery.server-addr}
file-extension: yml
namespace: 272b9958-7a2d-41f8-ba0b-fdcb7ee8ead0
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment