Browse Source

1.在请求header中加了customer,通过@LoginUser TokenDto获取

dev_shibei_match
wxz 5 years ago
parent
commit
ff56818878
  1. 5
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/constant/AppClientConstant.java
  2. 5
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/security/dto/TokenDto.java
  3. 9
      epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/security/resolver/LoginUserHandlerMethodArgumentResolver.java
  4. 117
      epmet-gateway/src/main/java/com/epmet/filter/CpAuthGatewayFilterFactory.java
  5. 168
      epmet-gateway/src/main/java/com/epmet/filter/FeignRequestFilter.java

5
epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/constant/AppClientConstant.java

@ -41,6 +41,11 @@ public interface AppClientConstant {
* */
String CLIENT = "client";
/**
* 客户ID
*/
String CUSTOMER_ID = "customerId";
/**
* 事务流水号每次请求串起来的多个服务拥有相同的流水号,便于日志追踪
*/

5
epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/security/dto/TokenDto.java

@ -40,6 +40,11 @@ public class TokenDto extends BaseTokenDto implements Serializable {
*/
private long updateTime;
/**
* 当前工作人员进入的客户id
*/
private String customerId;
@Override
public String toString() {
return JSON.toJSONString(this);

9
epmet-commons/epmet-commons-tools/src/main/java/com/epmet/commons/tools/security/resolver/LoginUserHandlerMethodArgumentResolver.java

@ -10,6 +10,7 @@ package com.epmet.commons.tools.security.resolver;
import com.alibaba.fastjson.JSON;
import com.epmet.commons.tools.annotation.LoginUser;
import com.epmet.commons.tools.constant.AppClientConstant;
import com.epmet.commons.tools.constant.Constant;
import com.epmet.commons.tools.exception.ErrorCode;
import com.epmet.commons.tools.exception.RenException;
@ -77,10 +78,12 @@ public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgu
// String client=keyArray[1];
// String userId=keyArray[2];
// TokenDto tokenDto = cpUserDetailRedis.get(app,client,userId);
TokenDto tokenDto = new TokenDto();
tokenDto.setUserId(request.getHeader("userId"));
tokenDto.setApp(request.getHeader("app"));
tokenDto.setClient(request.getHeader("client"));
tokenDto.setUserId(request.getHeader(AppClientConstant.USER_ID));
tokenDto.setApp(request.getHeader(AppClientConstant.APP));
tokenDto.setClient(request.getHeader(AppClientConstant.CLIENT));
tokenDto.setCustomerId(request.getHeader(AppClientConstant.CUSTOMER_ID));
logger.info("resolveArgument TokenDto:"+ JSON.toJSONString(tokenDto));
logger.info("CURRENT-REDIS-DATABASE---------!!!!!!:"+redisDb);
return tokenDto;

117
epmet-gateway/src/main/java/com/epmet/filter/CpAuthGatewayFilterFactory.java

@ -70,43 +70,41 @@ public class CpAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CpA
ServerHttpRequest request = exchange.getRequest();
String requestUri = request.getPath().pathWithinApplication().value();
//请求放行,无需验证权限
if (!pathMatcher(requestUri)) {
return chain.filter(exchange);
}
logger.info("CpAuthGatewayFilterFactory当前requestUri=[" + requestUri + "]CpAuthGatewayFilterFactory拦截成功");
HttpHeaders headers = request.getHeaders();
String token = headers.getFirst(Constant.AUTHORIZATION_HEADER);
if (StringUtils.isBlank(token)) {
token = headers.getFirst(Constant.TOKEN_HEADER);
logger.info("token=" + token);
} else {
logger.info("authorization=" + token);
}
if (StringUtils.isBlank(token)) {
token = request.getQueryParams().getFirst(Constant.AUTHORIZATION_HEADER);
logger.info("params token:" + token);
}
if (StringUtils.isBlank(token)) {
return response(exchange,new Result<>().error(EpmetErrorCode.ERR10005.getCode(),EpmetErrorCode.ERR10005.getMsg()));
}
try {
BaseTokenDto baseTokenDto = getBaseTokenDto(token, jwtTokenUtils);
if (AppClientConstant.APP_RESI.equals(baseTokenDto.getApp())) {
// 居民端
TokenDto resiTokenDto = getLoginUserInfoByToken(token, jwtTokenUtils, cpUserDetailRedis, TokenDto.class);
validateTokenDto(resiTokenDto, token);
} else if (AppClientConstant.APP_GOV.equals(baseTokenDto.getApp())) {
// 政府端
GovTokenDto govTokenDto = getLoginUserInfoByToken(token, jwtTokenUtils, cpUserDetailRedis, GovTokenDto.class);
validateTokenDto(govTokenDto, token);
} else if(AppClientConstant.APP_OPER.equals(baseTokenDto.getApp())){
//运营端
TokenDto resiTokenDto = getLoginUserInfoByToken(token, jwtTokenUtils, cpUserDetailRedis, TokenDto.class);
validateTokenDto(resiTokenDto, token);
String token = getTokenFromRequest(request);
BaseTokenDto baseTokenDto = StringUtils.isNotBlank(token) ? getBaseTokenDto(token, jwtTokenUtils) : null;
String customerId = "";
//需要认证
if (needAuth(requestUri)) {
if (StringUtils.isBlank(token)) {
return response(exchange,new Result<>().error(EpmetErrorCode.ERR10005.getCode(),EpmetErrorCode.ERR10005.getMsg()));
}
// 校验token
try {
if (AppClientConstant.APP_RESI.equals(baseTokenDto.getApp())) {
// 居民端
TokenDto resiTokenDto = getLoginUserInfoByToken(token, jwtTokenUtils, cpUserDetailRedis, TokenDto.class);
validateTokenDto(resiTokenDto, token);
customerId = resiTokenDto.getCustomerId();
} else if (AppClientConstant.APP_GOV.equals(baseTokenDto.getApp())) {
// 政府端
GovTokenDto govTokenDto = getLoginUserInfoByToken(token, jwtTokenUtils, cpUserDetailRedis, GovTokenDto.class);
validateTokenDto(govTokenDto, token);
customerId = govTokenDto.getCustomerId();
} else if(AppClientConstant.APP_OPER.equals(baseTokenDto.getApp())){
//运营端
TokenDto resiTokenDto = getLoginUserInfoByToken(token, jwtTokenUtils, cpUserDetailRedis, TokenDto.class);
validateTokenDto(resiTokenDto, token);
customerId = resiTokenDto.getCustomerId();
}
} catch (RenException e) {
return response(exchange,new Result<>().error(e.getCode(),e.getMsg()));
}
}
//当前登录用户userId,添加到header中
if (baseTokenDto != null) {
String redisKey = baseTokenDto.getApp() + "-" + baseTokenDto.getClient() + "-" + baseTokenDto.getUserId();
logger.info("redisKey=" + redisKey);
ServerHttpRequest build = exchange.getRequest().mutate()
@ -114,14 +112,33 @@ public class CpAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CpA
.header(AppClientConstant.APP,baseTokenDto.getApp())
.header(AppClientConstant.CLIENT,baseTokenDto.getClient())
.header(AppClientConstant.USER_ID,baseTokenDto.getUserId())
.header(AppClientConstant.CUSTOMER_ID,customerId)
.header(AppClientConstant.TRANSACTION_SERIAL_KEY, new String[]{getTransactionSerial()})
.build();
return chain.filter(exchange.mutate().request(build).build());
}catch(RenException e){
return response(exchange,new Result<>().error(e.getCode(),e.getMsg()));
}
return chain.filter(exchange);
};
}
/**
* 获取事务流水号
* @return
*/
public static String getTransactionSerial() {
String[] letterPool = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"
, "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 2; i++) {
sb.append(letterPool[(int) (Math.random() * 25)]);
}
sb.append(System.currentTimeMillis());
return sb.toString();
}
//public TokenDto getLoginUserInfo(String token) {
// //是否过期
// Claims claims = jwtTokenUtils.getClaimByToken(token);
@ -160,7 +177,12 @@ public class CpAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CpA
return exchange.getResponse().writeWith(Flux.just(buffer));
}
private boolean pathMatcher(String requestUri) {
/**
* 是否需要认证
* @param requestUri
* @return
*/
private boolean needAuth(String requestUri) {
for (String url : cpProperty.getSwaggerUrls()) {
if (antPathMatcher.match(url, requestUri)) {
return false;
@ -213,4 +235,25 @@ public class CpAuthGatewayFilterFactory extends AbstractGatewayFilterFactory<CpA
}
}
}
/**
* 从请求中获取token
* @param request
* @return
*/
private String getTokenFromRequest(ServerHttpRequest request) {
HttpHeaders headers = request.getHeaders();
String token = headers.getFirst(Constant.AUTHORIZATION_HEADER);
if (StringUtils.isBlank(token)) {
token = headers.getFirst(Constant.TOKEN_HEADER);
logger.info("token=" + token);
} else {
logger.info("authorization=" + token);
}
if (StringUtils.isBlank(token)) {
token = request.getQueryParams().getFirst(Constant.AUTHORIZATION_HEADER);
logger.info("params token:" + token);
}
return token;
}
}

168
epmet-gateway/src/main/java/com/epmet/filter/FeignRequestFilter.java

@ -1,83 +1,85 @@
package com.epmet.filter;
import com.epmet.commons.tools.constant.AppClientConstant;
import com.epmet.commons.tools.constant.Constant;
import com.epmet.commons.tools.security.dto.BaseTokenDto;
import com.epmet.commons.tools.utils.CpUserDetailRedis;
import com.epmet.jwt.JwtTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* Feign调用发送请求的Filter
* 目前用于封装用户相关信息到request供上游微服务使用
*/
@Component
public class FeignRequestFilter implements GlobalFilter, UserTokenFilter {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private JwtTokenUtils jwtTokenUtils;
@Autowired
private CpUserDetailRedis cpUserDetailRedis;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
String token = headers.getFirst(Constant.AUTHORIZATION_HEADER);
if (StringUtils.isBlank(token)) {
token = headers.getFirst(Constant.TOKEN_HEADER);
logger.info("token=" + token);
} else {
logger.info("authorization=" + token);
}
if (StringUtils.isBlank(token)) {
token = request.getQueryParams().getFirst(Constant.AUTHORIZATION_HEADER);
logger.info("params token:" + token);
}
if (StringUtils.isBlank(token)) {
return chain.filter(exchange);
}
BaseTokenDto baseTokenDto = getBaseTokenDto(token, jwtTokenUtils);
if (baseTokenDto != null) {
ServerHttpRequest build = exchange.getRequest().mutate()
.header(AppClientConstant.USER_ID, new String[]{baseTokenDto.getUserId()})
.header(AppClientConstant.TRANSACTION_SERIAL_KEY, new String[]{getTransactionSerial()})
.build();
return chain.filter(exchange.mutate().request(build).build());
}
return chain.filter(exchange);
}
/**
* 获取事务流水号
* @return
*/
public static String getTransactionSerial() {
String[] letterPool = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"
, "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 2; i++) {
sb.append(letterPool[(int) (Math.random() * 25)]);
}
sb.append(System.currentTimeMillis());
return sb.toString();
}
}
//package com.epmet.filter;
//
//import com.epmet.commons.tools.constant.AppClientConstant;
//import com.epmet.commons.tools.constant.Constant;
//import com.epmet.commons.tools.security.dto.BaseTokenDto;
//import com.epmet.commons.tools.utils.CpUserDetailRedis;
//import com.epmet.jwt.JwtTokenUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Mono;
//
///**
// * Feign调用发送请求的Filter
// * 目前用于封装用户相关信息到request,供上游微服务使用
// * 已过时,功能移入CpAuthGatewayFilterFacotry
// */
//@Component
//@Deprecated
//public class FeignRequestFilter implements GlobalFilter, UserTokenFilter {
//
// private Logger logger = LoggerFactory.getLogger(getClass());
//
// @Autowired
// private JwtTokenUtils jwtTokenUtils;
// @Autowired
// private CpUserDetailRedis cpUserDetailRedis;
//
// @Override
// public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// ServerHttpRequest request = exchange.getRequest();
// HttpHeaders headers = request.getHeaders();
// String token = headers.getFirst(Constant.AUTHORIZATION_HEADER);
// if (StringUtils.isBlank(token)) {
// token = headers.getFirst(Constant.TOKEN_HEADER);
// logger.info("token=" + token);
// } else {
// logger.info("authorization=" + token);
// }
// if (StringUtils.isBlank(token)) {
// token = request.getQueryParams().getFirst(Constant.AUTHORIZATION_HEADER);
// logger.info("params token:" + token);
// }
//
// if (StringUtils.isBlank(token)) {
// return chain.filter(exchange);
// }
//
// BaseTokenDto baseTokenDto = getBaseTokenDto(token, jwtTokenUtils);
//
// if (baseTokenDto != null) {
// ServerHttpRequest build = exchange.getRequest().mutate()
// .header(AppClientConstant.USER_ID, new String[]{baseTokenDto.getUserId()})
// .header(AppClientConstant.TRANSACTION_SERIAL_KEY, new String[]{getTransactionSerial()})
// .build();
// return chain.filter(exchange.mutate().request(build).build());
// }
//
// return chain.filter(exchange);
// }
//
// /**
// * 获取事务流水号
// * @return
// */
// public static String getTransactionSerial() {
// String[] letterPool = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"
// , "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
//
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 2; i++) {
// sb.append(letterPool[(int) (Math.random() * 25)]);
// }
//
// sb.append(System.currentTimeMillis());
// return sb.toString();
// }
//}

Loading…
Cancel
Save