From fd0a070abce625fcd2885a6f4b613fe9b4fa92fa Mon Sep 17 00:00:00 2001 From: huangweixiong Date: Mon, 9 May 2022 15:30:52 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E3=80=90=E8=83=BD=E5=8A=9B=E4=B8=8A?= =?UTF-8?q?=E6=9E=B6=E7=94=B3=E8=AF=B7=E3=80=91=E6=B7=BB=E5=8A=A0api?= =?UTF-8?q?=E7=BD=91=E5=85=B3=E9=9B=86=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../interceptor/YaweiSSOProperties.java | 2 +- .../entity/TAbilityApplicationEntity.java | 5 + .../listener/CorrectionListener.java | 38 ++++++++ .../service/ApiGatewayService.java | 96 ++++++++++++++++--- .../listener/ResourceOwnerListener.java | 10 +- .../src/main/resources/application-prod.yml | 6 +- .../src/main/resources/yaweisso.properties | 4 +- .../java/io/renren/ApiGatewayServiceTest.java | 11 ++- 8 files changed, 150 insertions(+), 22 deletions(-) diff --git a/renren-admin/src/main/java/io/renren/common/interceptor/YaweiSSOProperties.java b/renren-admin/src/main/java/io/renren/common/interceptor/YaweiSSOProperties.java index 5a7b4f17..d50e7542 100644 --- a/renren-admin/src/main/java/io/renren/common/interceptor/YaweiSSOProperties.java +++ b/renren-admin/src/main/java/io/renren/common/interceptor/YaweiSSOProperties.java @@ -7,7 +7,7 @@ import org.springframework.stereotype.Component; @Data @Component -@PropertySource("classpath:/yaweisso.properties") +@PropertySource("classpath:yaweisso.properties") @ConfigurationProperties(prefix = "sso") public class YaweiSSOProperties { private String domain; diff --git a/renren-admin/src/main/java/io/renren/modules/processForm/entity/TAbilityApplicationEntity.java b/renren-admin/src/main/java/io/renren/modules/processForm/entity/TAbilityApplicationEntity.java index 10bcaa8b..9a597057 100644 --- a/renren-admin/src/main/java/io/renren/modules/processForm/entity/TAbilityApplicationEntity.java +++ b/renren-admin/src/main/java/io/renren/modules/processForm/entity/TAbilityApplicationEntity.java @@ -66,4 +66,9 @@ public class TAbilityApplicationEntity { * 用户id */ private String userId; + + /** + * 流程通过后api网关注册的认证code,用于三方接口调用 + */ + private String gatewayCode; } \ No newline at end of file diff --git a/renren-admin/src/main/java/io/renren/modules/processForm/listener/CorrectionListener.java b/renren-admin/src/main/java/io/renren/modules/processForm/listener/CorrectionListener.java index ef2b3809..0c608559 100644 --- a/renren-admin/src/main/java/io/renren/modules/processForm/listener/CorrectionListener.java +++ b/renren-admin/src/main/java/io/renren/modules/processForm/listener/CorrectionListener.java @@ -1,9 +1,12 @@ package io.renren.modules.processForm.listener; +import cn.hutool.core.lang.UUID; import com.google.gson.Gson; import com.google.gson.JsonElement; import io.renren.modules.processForm.dto.TAbilityApplicationDTO; +import io.renren.modules.processForm.service.ApiGatewayService; import io.renren.modules.resource.dto.ResourceDTO; +import io.renren.modules.resource.entity.ResourceEntity; import io.renren.modules.resource.service.ResourceService; import io.renren.modules.sys.dto.SysDeptDTO; import io.renren.modules.sys.dto.SysRoleDTO; @@ -12,6 +15,8 @@ import io.renren.modules.sys.service.SysDeptService; import io.renren.modules.sys.service.SysRoleService; import io.renren.modules.sys.service.SysRoleUserService; import io.renren.modules.sys.service.SysUserService; +import org.activiti.engine.ProcessEngine; +import org.activiti.engine.ProcessEngines; import org.activiti.engine.TaskService; import org.activiti.engine.delegate.*; import org.activiti.engine.delegate.event.ActivitiEvent; @@ -47,6 +52,9 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti @Autowired private SysDeptService sysDeptService; + @Autowired + private ApiGatewayService apiGatewayService; + @Autowired private ResourceService resourceService; @@ -58,6 +66,9 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti case EVENTNAME_CREATE: create(delegateTask); break; + case EVENTNAME_COMPLETE: + complete(delegateTask); + break; default: } logger.error("-------------------------结束部门动态审批人流程-------------------------------"); @@ -138,4 +149,31 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti taskService.setAssignee(delegateTask.getId(), "1516728698224427010"); } } + + /** + * 审批通过,申请code + * @param delegateTask + */ + private void complete(DelegateTask delegateTask) { + Map kv = delegateTask.getVariables(); + Gson gson = new Gson(); + JsonElement jsonElement = gson.toJsonTree(kv); + TAbilityApplicationDTO abilityApplicationDTO = gson.fromJson(jsonElement, TAbilityApplicationDTO.class); + + ResourceEntity resourceEntity = resourceService.selectById(abilityApplicationDTO.getResourceId()); + + //没有groupid当做没有接口,直接跳过 + if (resourceEntity.getGroupId() == null) + return; + + String code = UUID.randomUUID().toString(); + apiGatewayService.subscribeCode(String.valueOf(abilityApplicationDTO.getId()), code); + + delegateTask.setVariable("gatewayCode", code); + + String apiPrefix = "/juapi/" + abilityApplicationDTO.getResourceId(); + TaskService taskService = ProcessEngines.getDefaultProcessEngine().getTaskService(); + String msg = String.format("您的能力申请已通过,接口认证code为:%s, 接口公共前缀为:%s",code, apiPrefix) ; + taskService.addComment(delegateTask.getId(), delegateTask.getProcessInstanceId(), msg); + } } diff --git a/renren-admin/src/main/java/io/renren/modules/processForm/service/ApiGatewayService.java b/renren-admin/src/main/java/io/renren/modules/processForm/service/ApiGatewayService.java index 156012ee..521e3181 100644 --- a/renren-admin/src/main/java/io/renren/modules/processForm/service/ApiGatewayService.java +++ b/renren-admin/src/main/java/io/renren/modules/processForm/service/ApiGatewayService.java @@ -1,9 +1,14 @@ package io.renren.modules.processForm.service; +import cn.hutool.core.lang.UUID; import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import io.renren.modules.processForm.dao.TAbilityApplicationDao; +import io.renren.modules.processForm.entity.TAbilityApplicationEntity; import io.renren.modules.resource.dao.ResourceDao; import io.renren.modules.resource.entity.ResourceEntity; import lombok.extern.slf4j.Slf4j; @@ -21,40 +26,60 @@ import java.util.regex.Pattern; @Service @Slf4j +/** + * 聚好看网关对接相关 + * + */ public class ApiGatewayService { @Autowired private ResourceDao resourceDao; + @Autowired + private TAbilityApplicationDao abilityApplicationDao; + @Autowired private RestTemplate restTemplate; - @Value("${hisense.gateway.url:http://devtest-security-app.hismarttv.com:8080}") + @Value("${hisense.gateway.url}") private String gatewayUrl; - /** + /** 将api注册到网关 + * 注册流程:创建group -> 创建路由(api)并关联到group下,未来可多个api关联 * @param resourceId 能力资源的id * @return */ public void registerApi2Gateway(String resourceId){ if (resourceId == null) { - log.warn("传入resourceId为空"); - return; + throw new IllegalArgumentException("传入resourceId为空"); } ResourceEntity resourceEntity = resourceDao.selectById(resourceId); + if (resourceEntity == null) { + throw new IllegalArgumentException(String.format("未找到对应的资源id:%s", resourceId)); + } String apiUrl = resourceEntity.getApiUrl(); + String methods = resourceEntity.getApiMethodType().toUpperCase(); - if (apiUrl == null || !apiUrl.startsWith("http")){ - log.warn("非法apiurl!! apiUrl:{} resourceId:{}",apiUrl, resourceId); + if (StringUtils.isBlank(apiUrl) || StringUtils.isBlank(methods)){ + String msg = String.format("注册api参数为空,跳过 apiUrl:%s, methods:%s, resourceId:%s", apiUrl, methods, resourceId); + //重要参数没有当成不需要注册 + log.info(msg); return; } //建group String domain = getIP(apiUrl); + String uris = apiUrl.substring(apiUrl.indexOf(domain) + domain.length()); + if (StringUtils.isBlank(uris)) { + uris = "/"; + } + String apiPrefix = "/juapi/" + resourceId; HashMap groupEntity = new HashMap(); + groupEntity.put("id", resourceId); groupEntity.put("name", resourceEntity.getName()); + groupEntity.put("stripPrefixPattern",String.format("^%s/(.*)", apiPrefix)); groupEntity.put("serviceName",domain ); String groupUrl = gatewayUrl + "/apiops/api/groups"; @@ -63,17 +88,17 @@ public class ApiGatewayService { HashMap body = responseEntity.getBody(); String id = (String) body.get("id"); if (StringUtils.isBlank(id)){ - log.error("创建group时id为空 {} body:{}", JSON.toJSONString(groupEntity), body); - return; + String error = String.format("创建group时id为空 request:%s body:%s", JSON.toJSONString(groupEntity), body); + throw new RuntimeException(error); } //建路由(接口url) - String routeUrl = gatewayUrl + "apiops/api/routers"; + String routeUrl = gatewayUrl + "/apiops/api/routers"; HashMap routeEntity = new HashMap(); routeEntity.put("name", "api:1:" + resourceEntity.getName()); routeEntity.put("group", id); - routeEntity.put("methods", resourceEntity.getApiMethodType().toUpperCase()); - routeEntity.put("uris", apiUrl.substring(apiUrl.indexOf(domain) + domain.length())); + routeEntity.put("methods", methods); + routeEntity.put("uris", apiPrefix + uris); ResponseEntity routeResEntity = restTemplate.postForEntity(routeUrl, routeEntity, HashMap.class); if (routeResEntity.getStatusCode() != HttpStatus.OK || !responseEntity.hasBody()){ //失败则删除group @@ -89,6 +114,55 @@ public class ApiGatewayService { } } + /** + * 将code关联到group,api这希望code由我们来生成 + * 关联流程:创建消费者 -> 订阅接口传入code关联消费者与group + * @param formId + * @param code + */ + public void subscribeCode( String formId, String code){ + + if ( StringUtils.isBlank(formId) || StringUtils.isBlank(code)) { + throw new IllegalArgumentException(String.format("关键参数不能为空 formId:%s code:%s", formId, code)); + } + + TAbilityApplicationEntity applicationEntity = abilityApplicationDao.selectById(formId); + ResourceEntity resourceEntity = resourceDao.selectById(applicationEntity.getResourceId()); + String groupId = resourceEntity.getGroupId(); + if (resourceEntity == null){ + throw new RuntimeException(String.format("找不到资源类 groupId:%s", groupId)); + } + + //注册消费者,一个表单关联一个消费者 + HashMap consumerEntity = new HashMap(); + consumerEntity.put("id", formId); + consumerEntity.put("name", resourceEntity.getName() + "-concumer"); + + String consumerUrl = gatewayUrl + "/apiops/api/consumers"; + HashMap consumerResponse = restTemplate.postForEntity(consumerUrl, consumerEntity, HashMap.class).getBody(); + if (consumerResponse == null || !formId.equals(consumerResponse.get("id"))){ + throw new RuntimeException(String.format("消费者创建失败 response: %s", consumerResponse)); + } + + //订阅 + HashMap subscribeEntity = new HashMap(); + subscribeEntity.put("consumerId", formId); + subscribeEntity.put("routerId", groupId); + subscribeEntity.put("routerType","group"); + subscribeEntity.put("code", code); + + String subscribeUrl = gatewayUrl + "/apiops/api/subscribers"; + HashMap body = restTemplate.postForEntity(subscribeUrl, subscribeEntity, HashMap.class).getBody(); + if (body == null || StringUtils.isBlank((String) body.get("consumerId"))){ + throw new RuntimeException(String.format("订阅失败 response: %s", body)); + } + + LambdaUpdateWrapper updateWrapper = new UpdateWrapper().lambda() + .eq(TAbilityApplicationEntity::getId, formId) + .set(TAbilityApplicationEntity::getGatewayCode, code); + abilityApplicationDao.update(null, updateWrapper); + } + private String getIP(String url) { String re = "((http|ftp|https)://)(([a-zA-Z0-9._-]+)|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(([a-zA-Z]{2,6})|(:[0-9]{1,4})?)"; String str = ""; diff --git a/renren-admin/src/main/java/io/renren/modules/resourceMountApply/listener/ResourceOwnerListener.java b/renren-admin/src/main/java/io/renren/modules/resourceMountApply/listener/ResourceOwnerListener.java index b5088653..a6f907c5 100644 --- a/renren-admin/src/main/java/io/renren/modules/resourceMountApply/listener/ResourceOwnerListener.java +++ b/renren-admin/src/main/java/io/renren/modules/resourceMountApply/listener/ResourceOwnerListener.java @@ -79,9 +79,9 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A case EVENTNAME_CREATE: // 创建当前审批节点事件 create(delegateTask, roleDTO); break; -// case EVENTNAME_COMPLETE: -// complete(delegateTask); -// break; + case EVENTNAME_COMPLETE: + complete(delegateTask); + break; default: logger.error("未处理该事件:" + eventName); } @@ -124,7 +124,7 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A } /** - * 流程结束,推送 + * 流程结束,接口推送api * * @param delegateTask */ @@ -134,7 +134,7 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A JsonElement jsonElement = gson.toJsonTree(kv); TResourceMountApplyDTO resourceMountApplyDTO = gson.fromJson(jsonElement, TResourceMountApplyDTO.class); Long resourceID = resourceMountApplyDTO.getResourceDTO().getId(); -// apiGatewayService.registerApi2Gateway(String.valueOf(resourceID)); + apiGatewayService.registerApi2Gateway(String.valueOf(resourceID)); ResourceDTO re = resourceMountApplyDTO.getResourceDTO(); if (re != null) { diff --git a/renren-admin/src/main/resources/application-prod.yml b/renren-admin/src/main/resources/application-prod.yml index f85e42f5..bbf13ad6 100644 --- a/renren-admin/src/main/resources/application-prod.yml +++ b/renren-admin/src/main/resources/application-prod.yml @@ -42,4 +42,8 @@ resource: # 大数据部门相关配置 big_date: name: 青岛市大数据发展管理局 - assignee_role_name: 部门审批人 \ No newline at end of file + assignee_role_name: 部门审批人 + +hisense: + gateway: + url: http://devtest-security-app.hismarttv.com:8080 \ No newline at end of file diff --git a/renren-admin/src/main/resources/yaweisso.properties b/renren-admin/src/main/resources/yaweisso.properties index bb802a06..9d5bcaeb 100644 --- a/renren-admin/src/main/resources/yaweisso.properties +++ b/renren-admin/src/main/resources/yaweisso.properties @@ -1,3 +1,3 @@ -sso.domain=yw.com.cn +sso.domain=127.0.0.1:8080 sso.ssoKey=SSOToken -sso.keeperUrl=http://127.0.0.1:9090/renren-admin/sys/user/123 \ No newline at end of file +sso.keeperUrl=http://jhoa.qd.gov.cn \ No newline at end of file diff --git a/renren-admin/src/test/java/io/renren/ApiGatewayServiceTest.java b/renren-admin/src/test/java/io/renren/ApiGatewayServiceTest.java index 71134cab..a783dd71 100644 --- a/renren-admin/src/test/java/io/renren/ApiGatewayServiceTest.java +++ b/renren-admin/src/test/java/io/renren/ApiGatewayServiceTest.java @@ -1,5 +1,6 @@ package io.renren; +import cn.hutool.core.lang.UUID; import io.renren.common.redis.RedisUtils; import io.renren.modules.processForm.service.ApiGatewayService; import io.renren.modules.sys.entity.SysUserEntity; @@ -17,8 +18,14 @@ public class ApiGatewayServiceTest { private ApiGatewayService apiGatewayService; @Test - public void contextLoads() { - apiGatewayService.registerApi2Gateway("1519505145602723841"); + public void registerApi2Gateway() { + apiGatewayService.registerApi2Gateway("1522550194523152385"); + } + + @Test + public void registerCode2Group() { + String code = UUID.randomUUID().toString(); + apiGatewayService.subscribeCode("1522550733273112577", code); } } \ No newline at end of file From 4815e9f3f51f28b10038ff0e8c81da13df3e9531 Mon Sep 17 00:00:00 2001 From: huangweixiong Date: Mon, 9 May 2022 15:31:24 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E3=80=90=E7=BB=9F=E4=B8=80=E5=8D=95?= =?UTF-8?q?=E7=82=B9=E3=80=91=E4=BF=AE=E6=94=B9=E7=99=BB=E5=BD=95=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../interceptor/IdentityInterceptor.java | 1 + .../modules/security/config/ShiroConfig.java | 9 +- .../modules/security/config/WebMvcConfig.java | 7 +- .../modules/security/oauth2/Oauth2Filter.java | 125 +++++++++++++++++- 4 files changed, 132 insertions(+), 10 deletions(-) diff --git a/renren-admin/src/main/java/io/renren/common/interceptor/IdentityInterceptor.java b/renren-admin/src/main/java/io/renren/common/interceptor/IdentityInterceptor.java index 5e4920f2..fbba7ca1 100644 --- a/renren-admin/src/main/java/io/renren/common/interceptor/IdentityInterceptor.java +++ b/renren-admin/src/main/java/io/renren/common/interceptor/IdentityInterceptor.java @@ -48,6 +48,7 @@ public class IdentityInterceptor implements HandlerInterceptor { String keeperUrl = yaweiSSOProperties.getKeeperUrl(); keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "=" + URLEncoder.encode(requeststr, "UTF-8"); + response.addHeader("REDIRECT", keeperUrl); response.sendRedirect(keeperUrl); return false; } diff --git a/renren-admin/src/main/java/io/renren/modules/security/config/ShiroConfig.java b/renren-admin/src/main/java/io/renren/modules/security/config/ShiroConfig.java index c07aa65d..94536f7c 100644 --- a/renren-admin/src/main/java/io/renren/modules/security/config/ShiroConfig.java +++ b/renren-admin/src/main/java/io/renren/modules/security/config/ShiroConfig.java @@ -9,8 +9,10 @@ import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSource import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; import javax.servlet.Filter; import java.util.HashMap; @@ -23,6 +25,9 @@ import java.util.Map; @Configuration public class ShiroConfig { +// @Autowired +// private Oauth2Filter oauth2Filter; + @Bean public DefaultWebSessionManager sessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); @@ -42,13 +47,13 @@ public class ShiroConfig { } @Bean("shiroFilter") - public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { + public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager, Oauth2Filter oauth2Filter) { ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); shiroFilter.setSecurityManager(securityManager); //oauth过滤 Map filters = new HashMap<>(); - filters.put("oauth2", new Oauth2Filter()); + filters.put("oauth2", oauth2Filter); shiroFilter.setFilters(filters); Map filterMap = new LinkedHashMap<>(); diff --git a/renren-admin/src/main/java/io/renren/modules/security/config/WebMvcConfig.java b/renren-admin/src/main/java/io/renren/modules/security/config/WebMvcConfig.java index df41a497..34de09e8 100644 --- a/renren-admin/src/main/java/io/renren/modules/security/config/WebMvcConfig.java +++ b/renren-admin/src/main/java/io/renren/modules/security/config/WebMvcConfig.java @@ -4,8 +4,10 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import io.renren.common.interceptor.IdentityInterceptor; import io.renren.common.utils.DateUtils; import io.renren.modules.pay.Interceptor.AliPayInterceptor; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.ByteArrayHttpMessageConverter; @@ -25,6 +27,9 @@ import java.util.TimeZone; @Configuration public class WebMvcConfig implements WebMvcConfigurer { + @Autowired + private IdentityInterceptor identityInterceptor; + @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") @@ -37,7 +42,7 @@ public class WebMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AliPayInterceptor()).addPathPatterns("/pay/alipay/**"); -// registry.addInterceptor(new IdentityInterceptor()); +// registry.addInterceptor(identityInterceptor); } @Override diff --git a/renren-admin/src/main/java/io/renren/modules/security/oauth2/Oauth2Filter.java b/renren-admin/src/main/java/io/renren/modules/security/oauth2/Oauth2Filter.java index 1e07ae14..b229ea06 100644 --- a/renren-admin/src/main/java/io/renren/modules/security/oauth2/Oauth2Filter.java +++ b/renren-admin/src/main/java/io/renren/modules/security/oauth2/Oauth2Filter.java @@ -1,8 +1,13 @@ package io.renren.modules.security.oauth2; import com.google.gson.Gson; +import com.yawei.pso.PSORequest; +import com.yawei.pso.SSOResponse; +import com.yawei.pso.TicketManager; import io.renren.common.constant.Constant; import io.renren.common.exception.ErrorCode; +import io.renren.common.interceptor.Validator; +import io.renren.common.interceptor.YaweiSSOProperties; import io.renren.common.utils.HttpContextUtils; import io.renren.common.utils.Result; import org.apache.commons.lang3.StringUtils; @@ -10,20 +15,38 @@ import org.apache.http.HttpStatus; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.web.filter.authc.AuthenticatingFilter; +import org.apache.shiro.web.servlet.ShiroHttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; +import java.lang.reflect.Field; +import java.net.URLEncoder; +import java.util.Iterator; +import java.util.Map; /** * oauth2过滤器 * */ +@Component() +@Scope("prototype") public class Oauth2Filter extends AuthenticatingFilter { + public final static String SEESION_USER = "seesion_user"; + + @Autowired + private YaweiSSOProperties yaweiSSOProperties; + @Override protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception { //获取请求token @@ -47,22 +70,28 @@ public class Oauth2Filter extends AuthenticatingFilter { @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { + + //获取请求token,如果token不存在,直接返回401 String token = getRequestToken((HttpServletRequest) request); if(StringUtils.isBlank(token)){ - HttpServletResponse httpResponse = (HttpServletResponse) response; - httpResponse.setContentType("application/json;charset=utf-8"); - httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); - httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); - String json = new Gson().toJson(new Result().error(ErrorCode.UNAUTHORIZED)); + yaweiHandle((HttpServletRequest)request, (HttpServletResponse)response); - httpResponse.getWriter().print(json); +// HttpServletResponse httpResponse = (HttpServletResponse) response; +// httpResponse.setContentType("application/json;charset=utf-8"); +// httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); +// httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); +// +// String json = new Gson().toJson(new Result().error(ErrorCode.UNAUTHORIZED)); +// +// httpResponse.getWriter().print(json); return false; } - return executeLogin(request, response); + boolean executeLogin = executeLogin(request, response); + return executeLogin; } @Override @@ -100,4 +129,86 @@ public class Oauth2Filter extends AuthenticatingFilter { return token; } + public boolean yaweiHandle(HttpServletRequest request, HttpServletResponse response) throws Exception { + // 获取当前请求的url + String requestUri = request.getHeader("REQUESTURI"); + if (requestUri == null){ + requestUri = request.getRequestURI(); + } + + Validator validator = Validator.getInstance(); + + String strResponse = request.getParameter(yaweiSSOProperties.getSsoKey()); + if (org.apache.commons.lang.StringUtils.isEmpty(strResponse)) { + TicketManager tm = new TicketManager(); + if (!tm.LoadTicket(request)) { + PSORequest psoRequest = new PSORequest(request); + //不建新类了,直接反射解决 + Field returnUrl = psoRequest.getClass().getDeclaredField("returnUrl"); + returnUrl.setAccessible(true); + returnUrl.set(psoRequest, requestUri); + String requeststr = psoRequest.CreateHash(); + + String keeperUrl = yaweiSSOProperties.getKeeperUrl(); + keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "=" + + URLEncoder.encode(requeststr, "UTF-8"); + response.addHeader("REDIRECT", keeperUrl); + response.setStatus(HttpStatus.SC_UNAUTHORIZED); + response.getWriter().write(HttpStatus.SC_UNAUTHORIZED); + return false; + } + } else { + // 如果服务器端通过认证后,会返回后执行改操作,然后写入cookie + SSOResponse ssoResp = new SSOResponse(strResponse); + TicketManager tm = ssoResp.CreatePSOTicket(); + if (tm == null) { + PSORequest psoRequest = new PSORequest(request); + String requeststr = psoRequest.CreateHash(); + + String keeperUrl = yaweiSSOProperties.getKeeperUrl(); + keeperUrl = keeperUrl + "?" + yaweiSSOProperties.getSsoKey() + "=" + + URLEncoder.encode(requeststr, "UTF-8"); + response.sendRedirect(keeperUrl); + } else { + String domainName = yaweiSSOProperties.getDomain(); + tm.SaveTicket(response, domainName); + + //同时添加自己的token +// Cookie cookie = new Cookie(Constant.TOKEN_HEADER, createToken(request, response).toString()); +// response.addCookie(cookie); + + Iterator> iterator = request + .getParameterMap().entrySet().iterator(); + StringBuffer param = new StringBuffer(); + int i = 0; + while (iterator.hasNext()) { + Map.Entry entry = (Map.Entry) iterator + .next(); + if (entry.getKey().equals(yaweiSSOProperties.getSsoKey())) + continue; + else { + i++; + if (i == 1) + param.append("?").append(entry.getKey()) + .append("="); + else + param.append("&").append(entry.getKey()) + .append("="); + + if (entry.getValue() instanceof String[]) { + param.append(((String[]) entry.getValue())[0]); + } else { + param.append(entry.getValue()); + } + } + } + response.sendRedirect(requestUri + param.toString()); + return false; + } + } + validator.SetUserTicket(request); + return true; + } + + } \ No newline at end of file From 06085b9eea03b97c16a8f4b2927ce25b56aa2edb Mon Sep 17 00:00:00 2001 From: huangweixiong Date: Wed, 11 May 2022 16:26:06 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E3=80=90=E7=BD=91=E5=85=B3=E5=AF=B9?= =?UTF-8?q?=E6=8E=A5=E3=80=91=E4=BF=AE=E6=94=B9=E7=94=B3=E8=AF=B7=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E4=BB=A5=E5=8F=8A=E6=B5=81=E7=A8=8B=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../activiti/service/ActTaskService.java | 11 ++++ .../entity/TAbilityApplicationEntity.java | 1 + .../listener/CorrectionListener.java | 43 +++++++++++--- .../listener/ResourceOwnerListener.java | 6 +- .../src/main/resources/application-hwx.yml | 58 +++++++++++++++++++ .../java/io/renren/ApiGatewayServiceTest.java | 2 +- 6 files changed, 110 insertions(+), 11 deletions(-) create mode 100644 renren-admin/src/main/resources/application-hwx.yml diff --git a/renren-admin/src/main/java/io/renren/modules/activiti/service/ActTaskService.java b/renren-admin/src/main/java/io/renren/modules/activiti/service/ActTaskService.java index 3b3137a2..d4f86be8 100644 --- a/renren-admin/src/main/java/io/renren/modules/activiti/service/ActTaskService.java +++ b/renren-admin/src/main/java/io/renren/modules/activiti/service/ActTaskService.java @@ -53,6 +53,13 @@ import java.util.*; */ @Service public class ActTaskService extends BaseServiceImpl { + + public static String Task_HANDLE_STATE = "handleState"; //任务节点处理状态key + public static String Task_HANDLE_STATE_AGREE = "agree"; //同意 + public static String Task_HANDLE_STATE_REJECTED = "rejected"; //驳回 + public static String Task_HANDLE_STATE_BACK = "back"; //回退 + public static String Task_HANDLE_STATE_STOP = "stop"; //终止 + @Autowired protected TaskService taskService; @Autowired @@ -210,6 +217,7 @@ public class ActTaskService extends BaseServiceImpl { if (StringUtils.isNotEmpty(comment)) { taskService.addComment(taskId, task.getProcessInstanceId(), comment); } + taskService.setVariable(taskId, Task_HANDLE_STATE, Task_HANDLE_STATE_AGREE); taskService.complete(taskId); } @@ -374,6 +382,7 @@ public class ActTaskService extends BaseServiceImpl { if (StringUtils.isNotEmpty(comment)) { commentMode += "[" + comment + "]"; } + taskService.setVariable(task.getId(), Task_HANDLE_STATE, Task_HANDLE_STATE_BACK); taskService.addComment(task.getId(), task.getProcessInstanceId(), commentMode); taskService.complete(task.getId(), variables); } @@ -461,6 +470,7 @@ public class ActTaskService extends BaseServiceImpl { String message = MessageUtils.getMessage(ErrorCode.END_PROCESS_MESSAGE); comment = message + "[" + comment + "]"; taskService.addComment(task.getId(), task.getProcessInstanceId(), comment); + taskService.setVariable(task.getId(), Task_HANDLE_STATE, Task_HANDLE_STATE_STOP); taskService.complete(taskId); pointActivity.getIncomingTransitions().remove(newTransition); List pvmTransitionListC = currActivity.getOutgoingTransitions(); @@ -590,6 +600,7 @@ public class ActTaskService extends BaseServiceImpl { this.setTaskVariable(taskDTO.getTaskId(), key, taskDTO.getParams().get(key)); } } + taskService.setVariable(taskDTO.getTaskId(), Task_HANDLE_STATE, Task_HANDLE_STATE_REJECTED); this.completeTask(taskDTO.getTaskId(), taskDTO.getComment()); } diff --git a/renren-admin/src/main/java/io/renren/modules/processForm/entity/TAbilityApplicationEntity.java b/renren-admin/src/main/java/io/renren/modules/processForm/entity/TAbilityApplicationEntity.java index 6ed5f847..d43307cd 100644 --- a/renren-admin/src/main/java/io/renren/modules/processForm/entity/TAbilityApplicationEntity.java +++ b/renren-admin/src/main/java/io/renren/modules/processForm/entity/TAbilityApplicationEntity.java @@ -37,6 +37,7 @@ public class TAbilityApplicationEntity { /** * 申请应用系统 */ + @TableField("`system`") private String system; /** * 申请场景 diff --git a/renren-admin/src/main/java/io/renren/modules/processForm/listener/CorrectionListener.java b/renren-admin/src/main/java/io/renren/modules/processForm/listener/CorrectionListener.java index 5b6de29d..df762354 100644 --- a/renren-admin/src/main/java/io/renren/modules/processForm/listener/CorrectionListener.java +++ b/renren-admin/src/main/java/io/renren/modules/processForm/listener/CorrectionListener.java @@ -2,6 +2,7 @@ package io.renren.modules.processForm.listener; import com.google.gson.Gson; import com.google.gson.JsonElement; +import io.renren.modules.activiti.service.ActTaskService; import io.renren.modules.processForm.dto.TAbilityApplicationDTO; import io.renren.modules.processForm.service.ApiGatewayService; import io.renren.modules.processForm.service.TAbilityApplicationService; @@ -15,19 +16,24 @@ import io.renren.modules.sys.service.SysDeptService; import io.renren.modules.sys.service.SysRoleService; import io.renren.modules.sys.service.SysRoleUserService; import io.renren.modules.sys.service.SysUserService; +import org.activiti.engine.HistoryService; import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngines; import org.activiti.engine.TaskService; import org.activiti.engine.delegate.*; import org.activiti.engine.delegate.event.ActivitiEvent; import org.activiti.engine.delegate.event.ActivitiEventListener; +import org.activiti.engine.history.HistoricTaskInstance; +import org.activiti.engine.task.Task; +import org.activiti.engine.task.TaskQuery; +import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import java.util.Map; +import java.util.*; /** * 部门动态审批人 @@ -46,6 +52,8 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti @Autowired private TaskService taskService; @Autowired + private HistoryService historyService; + @Autowired private SysUserService sysUserService; @Autowired private SysRoleUserService sysRoleUserService; @@ -68,6 +76,9 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti case EVENTNAME_CREATE: create(delegateTask); break; + case EVENTNAME_COMPLETE: + complete(delegateTask); + break; default: } logger.error("-------------------------结束部门动态审批人流程-------------------------------"); @@ -80,7 +91,7 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti final String eventName = delegateExecution.getEventName(); switch (eventName) { case EVENTNAME_END: - endTake(delegateExecution.getVariables()); + endTake(delegateExecution); break; } } @@ -105,9 +116,10 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti /** * 结束审批 * - * @param kv + * @param delegateExecution */ - private void endTake(Map kv) { // 进入最后结束节点 + private void endTake(DelegateExecution delegateExecution) { // 进入最后结束节点 + Map kv = delegateExecution.getVariables(); Gson gson = new Gson(); JsonElement jsonElement = gson.toJsonTree(kv); TAbilityApplicationDTO abilityApplicationDTO = gson.fromJson(jsonElement, TAbilityApplicationDTO.class); @@ -169,16 +181,27 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti } } - /** - * 审批通过,申请code - * @param delegateTask - */ private void complete(DelegateTask delegateTask) { Map kv = delegateTask.getVariables(); + + //如果有code说明已经注册过了,以及只有通过的流程申请 + if (kv.get("gatewayCode") != null || + !ActTaskService.Task_HANDLE_STATE_AGREE.equals(kv.get(ActTaskService.Task_HANDLE_STATE))) return; + Gson gson = new Gson(); JsonElement jsonElement = gson.toJsonTree(kv); TAbilityApplicationDTO abilityApplicationDTO = gson.fromJson(jsonElement, TAbilityApplicationDTO.class); + applyCode(delegateTask, abilityApplicationDTO); + } + /** + * 审批通过,申请code + * @param delegateTask + * @param abilityApplicationDTO + */ + private void applyCode(DelegateTask delegateTask, TAbilityApplicationDTO abilityApplicationDTO) { + + logger.info("-------能力申请code-------"); ResourceEntity resourceEntity = resourceService.selectById(abilityApplicationDTO.getResourceId()); //没有groupid当做没有接口,直接跳过 @@ -192,7 +215,9 @@ public class CorrectionListener implements TaskListener, ExecutionListener, Acti String apiPrefix = "/juapi/" + abilityApplicationDTO.getResourceId(); TaskService taskService = ProcessEngines.getDefaultProcessEngine().getTaskService(); - String msg = String.format("您的能力申请已通过,接口认证code为:%s, 接口公共前缀为:%s",code, apiPrefix) ; + String msg = String.format("您的能力申请已通过,接口认证code为:%s, 接口公共前缀为:%s",code, apiPrefix); taskService.addComment(delegateTask.getId(), delegateTask.getProcessInstanceId(), msg); + + } } diff --git a/renren-admin/src/main/java/io/renren/modules/resourceMountApply/listener/ResourceOwnerListener.java b/renren-admin/src/main/java/io/renren/modules/resourceMountApply/listener/ResourceOwnerListener.java index 6472dddf..b5b4dbd5 100644 --- a/renren-admin/src/main/java/io/renren/modules/resourceMountApply/listener/ResourceOwnerListener.java +++ b/renren-admin/src/main/java/io/renren/modules/resourceMountApply/listener/ResourceOwnerListener.java @@ -3,6 +3,7 @@ package io.renren.modules.resourceMountApply.listener; import com.alibaba.fastjson.JSONObject; import com.google.gson.Gson; import com.google.gson.JsonElement; +import io.renren.modules.activiti.service.ActTaskService; import io.renren.modules.processForm.service.ApiGatewayService; import io.renren.modules.resource.dto.ResourceDTO; import io.renren.modules.resource.service.ResourceService; @@ -137,7 +138,10 @@ public class ResourceOwnerListener implements TaskListener, ExecutionListener, A JsonElement jsonElement = gson.toJsonTree(kv); TResourceMountApplyDTO resourceMountApplyDTO = gson.fromJson(jsonElement, TResourceMountApplyDTO.class); Long resourceID = resourceMountApplyDTO.getResourceDTO().getId(); - apiGatewayService.registerApi2Gateway(String.valueOf(resourceID)); + + if (ActTaskService.Task_HANDLE_STATE_AGREE.equals(kv.get(ActTaskService.Task_HANDLE_STATE))) { + apiGatewayService.registerApi2Gateway(String.valueOf(resourceID)); + } ResourceDTO re = resourceMountApplyDTO.getResourceDTO(); if (re != null) { diff --git a/renren-admin/src/main/resources/application-hwx.yml b/renren-admin/src/main/resources/application-hwx.yml new file mode 100644 index 00000000..c6b8b9a3 --- /dev/null +++ b/renren-admin/src/main/resources/application-hwx.yml @@ -0,0 +1,58 @@ +server: + port: 8000 +spring: + datasource: + druid: + #MySQL + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://127.0.0.1:3306/share_platform?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true + username: root + password: 123456 + initial-size: 10 + max-active: 100 + min-idle: 10 + max-wait: 3000 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + time-between-eviction-runs-millis: 60000 + min-evictable-idle-time-millis: 300000 + #Oracle需要打开注释 + validation-query: SELECT 1 + test-while-idle: true + test-on-borrow: false + test-on-return: false + stat-view-servlet: + enabled: true + url-pattern: /druid/* + #login-username: admin + #login-password: admin + filter: + stat: + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: false + wall: + config: + multi-statement-allow: true +#上传的静态资源配置 +resource: + root_url: 15.2.21.238 + path: /data/services/nengli/files/ + devModelFilePath: /data/services/nengli/files/devModelFile +# 大数据部门相关配置 +big_date: + name: 青岛市大数据发展管理局 + assignee_role_name: 部门审批人 + +hisense: + gateway: +# url: http://15.72.184.7:8080 + url: http://devtest-security-app.hismarttv.com:8080 +logging: + level: + org: + activiti: + engine: + impl: + persistence: + entity: debug \ No newline at end of file diff --git a/renren-admin/src/test/java/io/renren/ApiGatewayServiceTest.java b/renren-admin/src/test/java/io/renren/ApiGatewayServiceTest.java index a783dd71..6bb4f9d7 100644 --- a/renren-admin/src/test/java/io/renren/ApiGatewayServiceTest.java +++ b/renren-admin/src/test/java/io/renren/ApiGatewayServiceTest.java @@ -25,7 +25,7 @@ public class ApiGatewayServiceTest { @Test public void registerCode2Group() { String code = UUID.randomUUID().toString(); - apiGatewayService.subscribeCode("1522550733273112577", code); + apiGatewayService.subscribeCode("1523913824099762177", code); } } \ No newline at end of file