♻️ 重构代码

This commit is contained in:
冷冷 committed 2018-10-12 13:13:03 +08:00
commit 4521d58db2
28 files changed
+465 -143

No files matched your search

+8 -22
View File
@@ -1,27 +1,13 @@
<p align="center">
<img src="https://img.shields.io/badge/Avue-1.5.4.RC1-green.svg" alt="Build Status">
<img src="https://img.shields.io/badge/Spring%20Cloud-Finchley.RELEASE-blue.svg" alt="Coverage Status">
<img src="https://img.shields.io/badge/Spring%20Boot-2.0.3.RELEASE-blue.svg" alt="Downloads">
</p>
<h2 align="center">Supporting Pig Developer Team</h2>
## 项目官网
https://pig4cloud.com
### 配套代码
<a href="https://gitee.wang/pig/pigx-ui" target="_blank">pigx-ui</a>
### pigx 和 pig 区别
- 基于最新的Spring Cloud Finchley.RELEASE 版本
- 完整的oAuth 流程,资源服务器控制权限
- 去除了部分对于开发不友好的中间件
### 使用说明
请参考VIP群共享 《从零开始部署pigx》
[>> 目录](doc/md/catalog.md)
请参考VIP群共享 《从零开始部署pigx》
[>> 文档](doc/md/catalog.md)
视频 | ppt
---|---
[>> 环境准备、运行pigx](https://www.bilibili.com/video/av33200189)| [PPT](https://slides.com/lengleng/pigx-springcloud-6/fullscreen#/)
[>> pigx定时任务、运维平台使用](https://www.bilibili.com/video/av33268288)| [PPT](https://slides.com/lengleng/pigx-springcloud-7/fullscreen#/)
[>> pigx 配置文件加解密原理和选择](https://www.bilibili.com/video/av33315412)| [PPT](https://slides.com/lengleng/pigx-springcloud-6-8/fullscreen#/)
## 协议和授权
+1 -1
View File
@@ -40,7 +40,7 @@ spring:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: lengleng
url: jdbc:mysql://127.0.0.1:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
url: jdbc:mysql://mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
```
+3 -3
View File
@@ -48,8 +48,8 @@ spring:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
password: 123456
url: jdbc:mysql://mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
elasticjob:
# 分布式任务协调依赖zookeeper
zookeeper:
@@ -71,4 +71,4 @@ spring:
最终效果如下:
![20189418110](http://p7sojn4oj.bkt.clouddn.com/20189418110.png)
![20189418110](http://p7sojn4oj.bkt.clouddn.com/20189418110.png)
@@ -21,6 +21,7 @@ package com.pig4cloud.pigx.auth.config;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.component.PigxWebResponseExceptionTranslator;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -52,6 +53,7 @@ import java.util.Map;
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private final DataSource dataSource;
private final PigxUserDetailsService pigxUserDetailsService;
private final AuthenticationManager authenticationManager;
private final RedisConnectionFactory redisConnectionFactory;
@@ -76,6 +78,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
.tokenStore(tokenStore())
.tokenEnhancer(tokenEnhancer())
.userDetailsService(pigxUserDetailsService)
.authenticationManager(authenticationManager)
.reuseRefreshTokens(false)
.exceptionTranslator(new PigxWebResponseExceptionTranslator());
@@ -20,8 +20,9 @@
package com.pig4cloud.pigx.auth.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.security.handler.MobileLoginSuccessHandler;
import com.pig4cloud.pigx.common.security.filter.TenantIdTtlFilter;
import com.pig4cloud.pigx.common.security.mobile.MobileLoginSuccessHandler;
import com.pig4cloud.pigx.common.security.handler.MobileLoginSuccessHandler;
import com.pig4cloud.pigx.common.security.mobile.MobileSecurityConfigurer;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
@@ -36,7 +37,6 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.auth.handler;
import com.pig4cloud.pigx.common.security.handler.AuthenticationFailureEvenHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
/**
* @author lengleng
* @date 2018/10/8
*/
@Slf4j
@Component
public class PigxAuthenticationFailureEvenHandler extends AuthenticationFailureEvenHandler {
/**
* 处理登录成功方法
* <p>
*
* @param authenticationException 登录的authentication 对象
* @param authentication 登录的authenticationException 对象
*/
@Override
public void handle(AuthenticationException authenticationException, Authentication authentication) {
log.info("用户:{} 登录失败,异常:{}", authentication.getPrincipal(), authenticationException.getLocalizedMessage());
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.auth.handler;
import com.pig4cloud.pigx.common.security.handler.AuthenticationSuccessEventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
/**
* @author lengleng
* @date 2018/10/8
*/
@Slf4j
@Component
public class PigxAuthenticationSuccessEventHandler extends AuthenticationSuccessEventHandler {
/**
* 处理登录成功方法
* <p>
* 获取到登录的authentication 对象
*
* @param authentication 登录对象
*/
@Override
public void handle(Authentication authentication) {
log.info("用户:{} 登录成功", authentication.getPrincipal());
}
}
@@ -47,6 +47,11 @@ public interface SecurityConstants {
*/
String FROM_IN = "Y";
/**
* 标志
*/
String FROM = "from";
/**
* {bcrypt} 加密的特征码
*/
@@ -2,15 +2,13 @@ package com.pig4cloud.pigx.common.security.component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration;
import org.springframework.cloud.security.oauth2.client.AccessTokenContextRelay;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.config.annotation.web.configuration.OAuth2ClientConfiguration;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration;
@@ -38,28 +36,6 @@ public class PigxResourceServerTokenRelayAutoConfiguration {
return new AccessTokenContextRelay(context);
}
@Configuration
public static class ResourceServerTokenRelayRegistrationAutoConfiguration implements WebMvcConfigurer {
@Autowired
AccessTokenContextRelay accessTokenContextRelay;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(
new HandlerInterceptorAdapter() {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
accessTokenContextRelay.copyToken();
return true;
}
}
);
}
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@@ -21,7 +21,9 @@ package com.pig4cloud.pigx.common.security.feign;
import feign.RequestInterceptor;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.security.oauth2.client.AccessTokenContextRelay;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
@@ -37,10 +39,10 @@ import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResour
@AllArgsConstructor
@ConditionalOnProperty("security.oauth2.client.client-id")
public class PigxFeignClientConfiguration {
@Bean
public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource) {
return new PigxFeignClientInterceptor(oAuth2ClientContext, resource);
OAuth2ProtectedResourceDetails resource,
AccessTokenContextRelay accessTokenContextRelay) {
return new PigxFeignClientInterceptor(oAuth2ClientContext, resource,accessTokenContextRelay);
}
}
@@ -17,12 +17,17 @@
package com.pig4cloud.pigx.common.security.feign;
import cn.hutool.core.collection.CollUtil;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.security.oauth2.client.AccessTokenContextRelay;
import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import java.util.Collection;
/**
* @author lengleng
* @date 2018/8/13
@@ -31,32 +36,39 @@ import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResour
@Slf4j
public class PigxFeignClientInterceptor extends OAuth2FeignRequestInterceptor {
private final OAuth2ClientContext oAuth2ClientContext;
private final AccessTokenContextRelay accessTokenContextRelay;
/**
* Default constructor which uses the provided OAuth2ClientContext and Bearer tokens
* within Authorization header
*
* @param oAuth2ClientContext provided context
* @param resource type of resource to be accessed
* @param oAuth2ClientContext provided context
* @param resource type of resource to be accessed
* @param accessTokenContextRelay
*/
public PigxFeignClientInterceptor(OAuth2ClientContext oAuth2ClientContext
, OAuth2ProtectedResourceDetails resource) {
, OAuth2ProtectedResourceDetails resource, AccessTokenContextRelay accessTokenContextRelay) {
super(oAuth2ClientContext, resource);
this.oAuth2ClientContext = oAuth2ClientContext;
this.accessTokenContextRelay = accessTokenContextRelay;
}
/**
* Create a template with the header of provided name and extracted extract
* 1. 如果使用 非web 请求,header 区别
* 2. 根据authentication 还原请求token
*
* @param template
*/
@Override
public void apply(RequestTemplate template) {
if (template.headers().isEmpty()) {
Collection<String> fromHeader = template.headers().get(SecurityConstants.FROM);
if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(SecurityConstants.FROM_IN)) {
return;
}
accessTokenContextRelay.copyToken();
if (oAuth2ClientContext != null
&& oAuth2ClientContext.getAccessToken() != null) {
super.apply(template);
@@ -0,0 +1,53 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.common.security.handler;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
/**
* @author lengleng
* @date 2018/10/8
* 认证失败事件处理器
*/
public abstract class AuthenticationFailureEvenHandler implements ApplicationListener<AbstractAuthenticationFailureEvent> {
/**
* Handle an application event.
*
* @param event the event to respond to
*/
@Override
public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
AuthenticationException authenticationException = event.getException();
Authentication authentication = (Authentication) event.getSource();
handle(authenticationException, authentication);
}
/**
* 处理登录成功方法
* <p>
*
* @param authenticationException 登录的authentication 对象
* @param authentication 登录的authenticationException 对象
*/
public abstract void handle(AuthenticationException authenticationException, Authentication authentication);
}
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.common.security.handler;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
/**
* @author lengleng
* @date 2018/10/8
* 认证成功事件处理器
*/
public abstract class AuthenticationSuccessEventHandler implements ApplicationListener<AuthenticationSuccessEvent> {
/**
* Handle an application event.
*
* @param event the event to respond to
*/
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
Authentication authentication = (Authentication) event.getSource();
handle(authentication);
}
/**
* 处理登录成功方法
* <p>
* 获取到登录的authentication 对象
*
* @param authentication 登录对象
*/
public abstract void handle(Authentication authentication);
}
@@ -14,7 +14,7 @@
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.common.security.mobile;
package com.pig4cloud.pigx.common.security.handler;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
@@ -72,6 +72,7 @@ public class PigxUser extends User {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.id = id;
this.deptId = deptId;
this.deptId = deptId;
this.tenantId = tenantId;
}
}
@@ -6,7 +6,7 @@ jasypt:
spring:
redis:
password:
host: localhost
host: redis
# 暴露监控端点
management:
endpoints:
@@ -4,5 +4,5 @@ spring:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/pigxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
password: 123456
url: jdbc:mysql://mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
@@ -12,8 +12,8 @@ spring:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/pigxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
password: 123456
url: jdbc:mysql://mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
@@ -13,12 +13,12 @@ spring:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/pigxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
password: 123456
url: jdbc:mysql://mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
elasticjob:
# 分布式任务协调依赖zookeeper
zookeeper:
server-lists: 114.116.45.246:13181
server-lists: zookeeper:2181
namespace: pigx-daemon
# 普通任务
simples:
@@ -14,26 +14,18 @@ spring:
- ImageCodeGatewayFilter
# 前端密码解密
- PasswordDecoderFilter
- StripPrefix=1
#UPMS 模块
- id: pigx-upms
uri: lb://pigx-upms
predicates:
- Path=/admin/**
filters:
# Swagger请求头处理
- SwaggerHeaderFilter
# 请求头清理避免不合法请求头
- name: RemoveRequestHeader
args:
name: from
# 限流配置
- name: RequestRateLimiter
args:
key-resolver: '#{@remoteAddrKeyResolver}'
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
- StripPrefix=1
# 降级配置
- name: Hystrix
args:
@@ -44,29 +36,21 @@ spring:
uri: lb://pigx-codegen
predicates:
- Path=/gen/**
filters:
- StripPrefix=1
# 定时任务模块
- id: pigx-daemon
uri: lb://pigx-daemon
predicates:
- Path=/daemon/**
filters:
- StripPrefix=1
# 分布式事务管理模块
- id: pigx-tx-manager
uri: lb://pigx-tx-manager
predicates:
- Path=/tx/**
filters:
- StripPrefix=1
# 工作流管理模块
- id: pigx-activiti
uri: lb://pigx-activiti
predicates:
- Path=/act/**
filters:
- StripPrefix=1
security:
encode:
# 前端密码密钥,必须16位
@@ -0,0 +1,6 @@
spring:
# 安全配置
security:
user:
name: ENC(rZHA4LW5hHmhLAAzJoFNag==)
password: ENC(bjeyh+Aeii3kHXkoo00ZUw==)
@@ -12,8 +12,8 @@ spring:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/pigxx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
password: 123456
url: jdbc:mysql://mysql:3306/pigx?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
# swagger相关配置,覆盖全局配置
swagger:
@@ -0,0 +1,92 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.filter;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.gateway.config.SwaggerProvider;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;
/**
* @author lengleng
* @date 2018/10/8
* <p>
* 全局拦截器,作用所有的微服务
* <p>
* 1. 对请求头中参数进行处理 from 参数进行清洗
* 2. 重写StripPrefix = 1,支持全局
* 3. 支持swagger添加X-Forwarded-Prefix header
*/
@Component
public class PigxRequestGlobalFilter implements GlobalFilter, Ordered {
private static final String HEADER_NAME = "X-Forwarded-Prefix";
/**
* Process the Web request and (optionally) delegate to the next
* {@code WebFilter} through the given {@link GatewayFilterChain}.
*
* @param exchange the current server exchange
* @param chain provides a way to delegate to the next filter
* @return {@code Mono<Void>} to indicate when request processing is complete
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. 清洗请求头中from 参数
ServerHttpRequest request = exchange.getRequest().mutate()
.headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM_IN))
.build();
// 2. 重写StripPrefix
addOriginalRequestUrl(exchange, request.getURI());
String rawPath = request.getURI().getRawPath();
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
.skip(1L).collect(Collectors.joining("/"));
ServerHttpRequest newRequest = request.mutate()
.path(newPath)
.build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
// 3. 支持swagger添加X-Forwarded-Prefix header
String path = request.getURI().getPath();
if (!StringUtils.endsWithIgnoreCase(path, SwaggerProvider.API_URI)) {
return chain.filter(exchange.mutate().request(newRequest).build());
}
String basePath = path.substring(0, path.lastIndexOf(SwaggerProvider.API_URI));
return chain.filter(exchange.mutate()
.request(newRequest.mutate()
.header(HEADER_NAME, basePath)
.build()).build());
}
@Override
public int getOrder() {
return -1000;
}
}
@@ -1,53 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.filter;
import com.pig4cloud.pigx.gateway.config.SwaggerProvider;
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.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
/**
* @author Sywd
* 添加X-Forwarded-Prefix header
*/
@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {
private static final String HEADER_NAME = "X-Forwarded-Prefix";
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
if (!StringUtils.endsWithIgnoreCase(path, SwaggerProvider.API_URI)) {
return chain.filter(exchange);
}
String basePath = path.substring(0, path.lastIndexOf(SwaggerProvider.API_URI));
ServerHttpRequest newRequest = request.mutate().header(HEADER_NAME, basePath).build();
ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
return chain.filter(newExchange);
};
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.admin;
import com.ulisesbocchio.jasyptspringboot.encryptor.DefaultLazyEncryptor;
import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
/**
* @author lengleng
* @date 2018/10/7
* <p>
* 加解密单元测试
*/
public class PigxAdminApplicationTest {
@Test
public void testJasypt() {
// 对应application-dev.yml 中配置的根密码
System.setProperty("jasypt.encryptor.password", "pigx");
StringEncryptor stringEncryptor = new DefaultLazyEncryptor(new StandardEnvironment());
//加密方法
System.out.println(stringEncryptor.encrypt("pigx"));
//解密方法
System.out.println(stringEncryptor.decrypt("ltJPpR50wT0oIY9kfOe1Iw==="));
}
}
+5
View File
@@ -61,6 +61,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!--security-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,66 @@
/*
*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*
*/
package com.pig4cloud.pigx.monitor.config;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
/**
* WebSecurityConfigurer
*
* @author: lishangbu
* @date: 2018/10/8
*/
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
private final String adminContextPath;
public WebSecurityConfigurer(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(adminContextPath + "/");
http.authorizeRequests()
.antMatchers(adminContextPath + "/assets/**").permitAll()
.antMatchers(adminContextPath + "/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
.logout().logoutUrl(adminContextPath + "/logout").and()
.httpBasic().and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers(
adminContextPath + "/instances",
adminContextPath + "/actuator/**"
);
// @formatter:on
}
}
+4 -2
View File
@@ -30,14 +30,14 @@
<url>https://www.pig4cloud.com</url>
<properties>
<pigx.version>1.6.2</pigx.version>
<pigx.version>1.6.3</pigx.version>
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
<spring-cloud.version>Finchley.SR1</spring-cloud.version>
<spring-platform.version>Cairo-SR3</spring-platform.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<monitor.version>2.0.2</monitor.version>
<monitor.version>2.0.3</monitor.version>
<hutool.version>4.1.13</hutool.version>
<mbp.boot.version>2.3</mbp.boot.version>
<kaptcha.version>0.0.9</kaptcha.version>
@@ -182,6 +182,7 @@
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<target>${maven.compiler.target}</target>
<source>${maven.compiler.source}</source>
@@ -191,6 +192,7 @@
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
<version>2.2.5</version>
</plugin>
</plugins>
</build>