如何更改 AbstractGatewayFilterFactory 中的响应正文 - Spring Cloud Api Gateway

问题描述 投票:0回答:1
我的目标是检查授权令牌的每个入站查询,如果检查失败(即 HTTP 401:“查询中没有授权令牌”),则将其重定向到具有可理解描述的另一个 URL。我为此使用

AbstractGatewayFilterFactory

这是我尝试过的两种方法。请看一下它,让我知道我做错了什么,或者建议您自己的方法(如果更适合我的目标)。

1。第一种方法:改变请求。

这里的问题:它被重定向到正确的路径,但主机不正确。

  • 例如,最初的请求是:

    “http:USERSERVICE /用户/任务”

  • 我想将其重定向到

    “http:APIGW:8080/apigw/askauth”

  • 但最终它被重定向到

    “http:USERSERVICE/apigw/askauth” :所以它是两个 URL 的混合体,它忽略了我想要的 HOST 重定向到并仅使用相对路径。

代码在这里:

@Component public class UserAuthenticationFilter extends AbstractGatewayFilterFactory<UserAuthenticationFilter.Config> { @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { try { //...some code here for check the Token... } catch (TokenNotFoundException e) { URI redirectUri = URI.create("http:127.0.0.1:8080/apigw/askauth"); ServerHttpRequest request = exchange .getRequest() .mutate() .uri(redirectUri) .method(HttpMethod.GET) .build(); ServerWebExchange mutatedExchange = exchange .mutate() .request(request) .build(); mutatedExchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI()); return chain.filter(mutatedExchange); } return chain.filter(exchange.mutate().request(request).build()); }; };

2。第二种方法:将响应更改为 HTTP 401。

它工作正常,但我无法设置可读的消息,因为 ServerHttpResponse 响应没有这样的选项。所以我只是给出 401 ERROR 没有可读的描述,这根本不好。

@Component public class UserAuthenticationFilter extends AbstractGatewayFilterFactory<UserAuthenticationFilter.Config> { @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { try { //...some code here for check the Token... } catch (TokenNotFoundException e) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); return response.setComplete(); } return chain.filter(exchange.mutate().request(request).build()); }; };
    
spring-boot spring-security microservices api-gateway
1个回答
1
投票
检查这个

.... exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); exchange.getResponse().getHeaders().put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE)); byte[] yourObjects; try { Map<String, String> data=new HashMap<>(); data.put("name","Mafei"); yourObjects = new ObjectMapper().writeValueAsBytes(data); } catch (JsonProcessingException e) { throw new RuntimeException(e); } return exchange.getResponse() .writeWith(Mono.just(exchange.getResponse() .bufferFactory().wrap(yourObjects)));
但不建议通过消息向黑客提供建议😜

© www.soinside.com 2019 - 2024. All rights reserved.