禁止网关直接传输 login-user

This commit is contained in:
YunaiV 2022-06-25 22:50:33 +08:00
parent 97b931f782
commit d79514d821
2 changed files with 15 additions and 4 deletions

View File

@ -12,14 +12,11 @@ import org.springframework.cloud.client.loadbalancer.reactive.ReactorLoadBalance
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.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import javax.annotation.Resource;
import java.util.function.Consumer;
import java.util.function.Function;
/**
@ -47,8 +44,11 @@ public class TokenAuthenticationFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(final ServerWebExchange exchange, GatewayFilterChain chain) {
String token = SecurityFrameworkUtils.obtainAuthorization(exchange);
// 移除 login-user 的请求头避免伪造模拟
SecurityFrameworkUtils.removeLoginUser(exchange);
// 情况一如果没有 Token 令牌则直接继续 filter
String token = SecurityFrameworkUtils.obtainAuthorization(exchange);
if (StrUtil.isEmpty(token)) {
return chain.filter(exchange);
}

View File

@ -58,6 +58,17 @@ public class SecurityFrameworkUtils {
exchange.getAttributes().put(LOGIN_USER_TYPE_ATTR, token.getUserType());
}
public static ServerWebExchange removeLoginUser(ServerWebExchange exchange) {
// 如果不包含直接返回
if (!exchange.getRequest().getHeaders().containsKey(LOGIN_USER_HEADER)) {
return exchange;
}
// 如果包含则移除参考 RemoveRequestHeaderGatewayFilterFactory 实现
ServerHttpRequest request = exchange.getRequest().mutate()
.headers(httpHeaders -> httpHeaders.remove(LOGIN_USER_HEADER)).build();
return exchange.mutate().request(request).build();
}
/**
* 获得登录用户的编号
*