在Spring Cloud网关API中,如何添加动态标头或查询参数?



我正在使用Spring Cloud网关和前端Angular 2的应用程序,对于登录,我使用Keyclock SSO。

但是,在登录后,我需要在前端以某种加密格式发送一些用户信息,可以通过报头或查询参数发送。对于Spring Cloud网关,我写了下面的代码,但它不工作。

这是我的自定义GlobalFilter,我试图添加它的标题和参数,但在前端我没有得到它。

@Component
public class InterceptorFilterGatewayFilterFactory extends AbstractGatewayFilterFactory<InterceptorFilterGatewayFilterFactory.Config> {

public InterceptorFilterGatewayFilterFactory() {
super(Config.class);
}
@Override
public Config newConfig() {
return new Config();
}
public static class Config {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
ServerHttpRequest sr = exchange.getRequest();
Mono var10000 = exchange.getPrincipal().filter((principal) -> principal instanceof OAuth2AuthenticationToken)
.map(p -> p).map((p) -> {
LinkedHashSet<URI> attr = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
ServerHttpRequest request = exchange.getRequest();
// Here I try to add query parameter
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
queryParams.put("e", Collections.singletonList(toHexString(ja.toString().getBytes())));

URI newUri = UriComponentsBuilder.fromUri(request.getURI())
.replaceQueryParams(unmodifiableMultiValueMap(queryParams))
.build(true).toUri();

ServerHttpRequest updatedRequest = exchange.getRequest().mutate().uri(newUri)
.build();
// Here I add header
updatedRequest.mutate().header("e", toHexString(ja.toString().getBytes())).build();

return exchange.mutate().request(updatedRequest).build();
}).defaultIfEmpty(exchange).flatMap(chain::filter);
}
return var10000;
};
}

和在应用程序yml文件我提供路由如下:

- id: appDepartmentWise
predicates:
- Path=/app/*/sso_login
- Method=GET,POST
uri: http://localhost:9000/app/
filters:
- PreserveHostHeader
- RewritePath=/.*, /app/index.html
- InterceptorFilter
- AddRequestParameter=e,*

缺少什么配置,以及如何添加动态头或查询参数?

如果它可以帮助任何人添加动态查询参数和重定向页面,您可以使用下面的代码:

@GetMapping("/user")
public Mono<Void> sendRedirect(ServerWebExchange exchange, Principal p) {
// Here we can can create string which can have dynamic parameters
String responseData = "e="+p..getName();
return Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.FOUND);
// this used to get the base URL.
UriComponents uriComponents = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).replacePath(exchange.getRequest().getPath().contextPath().value()).replaceQuery((String)null).fragment((String)null).build();
// As below we can re-generate the URL and redirect it.
response.getHeaders().setLocation(URI.create(uriComponents.toUriString()+"/app/Dept"+"/sso_login?"+responseData));
});
}

最新更新