網(wǎng)關(guān)服務(wù)配置
routes配置
server:
port: 8090
spring:
cloud:
gateway:
routes:
# 下游服務(wù)1
- id: demo1
uri: http://127.0.0.1:8091
predicates:
- Path=/gateway/demo1/**
filters:
- StripPrefix=1
# 下游服務(wù)2
- id: demo2
uri: http://127.0.0.1:8092
predicates:
- Path=/gateway/demo2/**
filters: # 轉(zhuǎn)發(fā)到下游服務(wù)需要?jiǎng)冸x路徑個(gè)數(shù)
- 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) {
//登錄頁(yè)放開(kāi)
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);
}
//從請(qǐng)求頭內(nèi)獲取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 {
//驗(yàn)證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透?jìng)鹘o下游服務(wù)
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));
}
}
應(yīng)用服務(wù)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 {
//從請(qǐng)求頭內(nèi)獲取用戶信息
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();
}
/**
* 存儲(chǔ)用戶信息
*/
public static void set(UserDto userDTO) {
USER_INFO_THREAD_LOCAL.set(userDTO);
}
/**
* 獲取當(dāng)前用戶信息
*/
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");
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者