前言
在网关 cloud-gateway 模块编写网关过滤器
0) (
public class GatewayRequestFilter implements GlobalFilter {
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
byte[] token = Base64Utils.encode((CloudConstant.GATEWAY_TOKEN_VALUE).getBytes());
String[] headerValues = {new String(token)};
ServerHttpRequest build = exchange.getRequest()
.mutate()
.header(CloudConstant.GATEWAY_TOKEN_HEADER, headerValues)
.build();
ServerWebExchange newExchange = exchange.mutate().request(build).build();
return chain.filter(newExchange);
}
}
建立公共 Starter 模块 cloud-component-security-starter
编写配置类,用于灵活控制服务是否允许绕过网关
public class CloudSecurityProperties {
/**
* 是否只能通过网关获取资源
* 默认为True
*/
private Boolean onlyFetchByGateway = Boolean.TRUE;
}
编写拦截器,用于校验请求是否经过网关
public class ServerProtectInterceptor implements HandlerInterceptor {
private CloudSecurityProperties properties;
public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler){
if (!properties.getOnlyFetchByGateway()) {
return true;
}
String token = request.getHeader(CloudConstant.GATEWAY_TOKEN_HEADER);
String gatewayToken = new String(Base64Utils.encode(CloudConstant.GATEWAY_TOKEN_VALUE.getBytes()));
if (StringUtils.equals(gatewayToken, token)) {
return true;
} else {
ResultData<String> resultData = new ResultData<>();
resultData.setSuccess(false);
resultData.setStatus(HttpServletResponse.SC_FORBIDDEN);
resultData.setMessage("请通过网关访问资源");
WebUtils.writeJson(response,resultData);
return false;
}
}
public void setProperties(CloudSecurityProperties properties) {
this.properties = properties;
}
}
配置拦截器
public class CloudSecurityInterceptorConfigure implements WebMvcConfigurer {
private CloudSecurityProperties properties;
public void setProperties(CloudSecurityProperties properties) {
this.properties = properties;
}
public HandlerInterceptor serverProtectInterceptor() {
ServerProtectInterceptor interceptor = new ServerProtectInterceptor();
interceptor.setProperties(properties);
return interceptor;
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(serverProtectInterceptor());
}
}
编写 starter 装载类
(CloudSecurityProperties.class)
public class CloudSecurityAutoConfigure{
public CloudSecurityInterceptorConfigure cloudSecurityInterceptorConfigure() {
return new CloudSecurityInterceptorConfigure();
}
}
建立资源文件 spring.factories,配置 Bean 的自动加载
\ =
com.javadaily.component.security.configure.CloudSecurityAutoConfigure
在后端服务配置文件中添加属性配置,默认只能通过网关访问
javadaily:
cloud:
onlyFetchByGateway: true
后端服务引用此公共 Starter 模块即可,以 account-service 为例
<dependency>
<groupId>com.jianzh5.cloud</groupId>
<artifactId>cloud-component-security-starter</artifactId>
</dependency>
{
"message": "请通过网关访问资源",
"status": 403,
"success": false,
"timestamp": 1611660015830
}
程序员如何避免陷入“内卷”、选择什么技术最有前景,中国开发者现状与技术趋势究竟是什么样?快来参与「2020 中国开发者大调查」,更有丰富奖品送不停!
☞小米澄清「手机不再支持GMS」;虾米音乐正式关停;《质量效应1》DLC 因源代码损坏而移除 | 极客头条