网关服务配置
routes配置
server:
port: 8090
spring:
cloud:
gateway:
routes:
# 下游服务1
- id: demo1
uri: http://127.0.0.1:8091
predicates:
- Path=/gateway/demo1/**
filters:
- StripPrefix=1
# 下游服务2
- id: demo2
uri: http://127.0.0.1:8092
predicates:
- Path=/gateway/demo2/**
filters: # 转发到下游服务需要剥离路径个数
- StripPrefix=1
filter配置
package com.solargrids.gateway.config;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.solargrids.commonModule.commonDto.UserDto;
import com.solargrids.commonModule.commonResult.CommonResult;
import com.solargrids.commonModule.commonResult.ResultEnum;
import com.solargrids.commonModule.commonUtils.JWTUtil;
import com.solargrids.commonModule.exception.TokenAuthenticationException;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Map;
@Component
public class TokenFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//登录页放开
ServerHttpRequest serverHttpRequest = exchange.getRequest();
ServerHttpResponse serverHttpResponse = exchange.getResponse();
String uri = serverHttpRequest.getURI().getPath();
if (uri.indexOf("/ems/ops/User/Login") >= 0) {
return chain.filter(exchange);
}
//从请求头内获取token,解析出用户信息
String token = serverHttpRequest.getHeaders().getFirst("authorization");
if(StringUtils.isEmpty(token)){
return getVoidMono(serverHttpResponse,ResultEnum.TOKEN_MISS.getCode(),ResultEnum.TOKEN_MISS.getMessage());
}
DecodedJWT decodedJWT = null;
try {
//验证Token的合法性
decodedJWT = JWTUtil.verify(token);
} catch (TokenAuthenticationException exception) {
return getVoidMono(serverHttpResponse,exception.getCode(),exception.getMessage());
}
Map<String, Claim> claims = decodedJWT.getClaims();
String userId = claims.get("userId").asString();
String userNo = claims.get("userNo").asString();
String userName = claims.get("userName").asString();
//将userId透传给下游服务
ServerHttpRequest request = serverHttpRequest.mutate().headers(httpHeaders -> {
httpHeaders.add(UserDto.USER_ID, userId);
httpHeaders.add(UserDto.USER_NO, userNo);
httpHeaders.add(UserDto.USER_NAME, userName);
}).build();
return chain.filter(exchange.mutate().request(request).build());
}
@Override
@Cacheable()
public int getOrder() {
return -100;
}
private Mono<Void> getVoidMono(ServerHttpResponse serverHttpResponse, int code,String msg) {
serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
CommonResult responseResult = CommonResult.failed(code,msg);
DataBuffer dataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(responseResult).getBytes());
return serverHttpResponse.writeWith(Flux.just(dataBuffer));
}
}
应用服务demo1配置
interceptor配置
package com.solargrids.ops.config;
import com.solargrids.commonModule.commonDto.UserDto;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 1065246
* @description:
* @createTime:2023/3/2 11:54
*/
public class UserContextInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//从请求头内获取用户信息
String userId = request.getHeader(UserDto.USER_ID);
String userNo = request.getHeader(UserDto.USER_NO);
String userName = request.getHeader(UserDto.USER_NAME);
UserDto userDto = new UserDto();
userDto.setUserId(Integer.parseInt(userId));
userDto.setUserNo(userNo);
userDto.setUserName(userName);
UserThreadLocal.set(userDto);
return true;
}
@Override
public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception e) {
UserThreadLocal.clear();
}
public static UserDto getCurrentUser() {
return UserThreadLocal.getCurrentUser();
}
private static class UserThreadLocal {
private UserThreadLocal() {
}
private static final ThreadLocal<UserDto> USER_INFO_THREAD_LOCAL = new ThreadLocal<>();
/**
* 清除用户信息
*/
public static void clear() {
USER_INFO_THREAD_LOCAL.remove();
}
/**
* 存储用户信息
*/
public static void set(UserDto userDTO) {
USER_INFO_THREAD_LOCAL.set(userDTO);
}
/**
* 获取当前用户信息
*/
public static UserDto getCurrentUser() {
return USER_INFO_THREAD_LOCAL.get();
}
}
}
WebMvc配置
@Component
public class WebSerializeConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(0,new MappingJackson2HttpMessageConverter());
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserContextInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/User/Login");
}
}