spring-cloud-gateway icon indicating copy to clipboard operation
spring-cloud-gateway copied to clipboard

How to modify request / response body?

Open re6exp opened this issue 9 years ago • 37 comments

Is it possible?

re6exp avatar Nov 16 '17 13:11 re6exp

You can use WebFilter, here the README:

  • Filters can modify downstream HTTP Request and HTTP Response (Add/Remove Headers, Add/Remove Parameters, Rewrite Path, Set Path, Hystrix, etc…​)

Here the example how to add request parameter:

.route("addrequestheader_route") .uri("http://localhost:8080") .predicate(path("/search")) .add(addRequestParameter("value1", "value2"))

or

spring: cloud: gateway: routes: - id: addrequestparameter_route uri: http://localhost:8080 predicates: - Path=/search filters: - AddRequestParameter=value1, value2

henriqamaral avatar Nov 24 '17 22:11 henriqamaral

Thank you, but I found how to do that. I don't know whether WebFilter can be used here, but Spencer uses for it the GatewayFilter.

See the correct example in WeirdBob's closed issue.

25 нояб. 2017 г. 1:25 пользователь "Henrique Amaral" < [email protected]> написал:

You can use WebFilter, here the README:

  • Filters can modify downstream HTTP Request and HTTP Response (Add/Remove Headers, Add/Remove Parameters, Rewrite Path, Set Path, Hystrix, etc…​)

Here the example how to add request parameter:

.route("addrequestheader_route") .uri("http://localhost:8080") .predicate(path("/search")) .add(addRequestParameter("value1", "value2"))

or

spring: cloud: gateway: routes:

  • id: addrequestparameter_route uri: http://localhost:8080 predicates:
  • Path=/search filters:
  • AddRequestParameter=value1, value2

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/spring-cloud/spring-cloud-gateway/issues/113#issuecomment-346902240, or mute the thread https://github.com/notifications/unsubscribe-auth/ACzyA1oVyB9YsVxA3R1D3gbCeJ3WZ-Pwks5s50JYgaJpZM4QgeKW .

re6exp avatar Nov 24 '17 22:11 re6exp

I didn't get how to change the response body. I have a json in the body and I want to add a property to it.

Example config:

spring:
    cloud:
        gateway:
            routes:
              - id: test
                uri: http://jsonplaceholder.typicode.com:80
                predicates:
                  - Path=/**
                filters:
                  - MyFilter

My custom filter:

@Component
class MyFilter : GatewayFilterFactory {
    override fun apply(args: Tuple?): GatewayFilter {
        return GatewayFilter { exchange, chain ->
// I want to add a property to json response body, say, "a": 123. How?
            chain.filter(exchange)
        }
    }
}

I want to add a property to json response body, say, "a": 123. How?

ofabricio avatar Dec 01 '17 21:12 ofabricio

Search an other closed issue by "body" keyword, there is an example from WeirdBob and my additional comment to it. You can also use an appropriate Decoder to get a map or the object you are interested in.

re6exp avatar Dec 01 '17 22:12 re6exp

Thanks. I found the issue you said and it kinda works. The problem is that that filter works for every route (because I'm using @Component I guess), but I'd like to apply it to a specific route through the configuration file as above (.yml, and not through .route().filters()) . How can I do that?

If I remove the @Component and set:

    filters:
      - MyFilter

it says:

Caused by: java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name MyFilter

ofabricio avatar Dec 01 '17 22:12 ofabricio

See how Spencer does. There is some builder behind which is responsible for built-in filters creation. Do not use component, you see, it's another model of data flow, not old known MVC.

re6exp avatar Dec 02 '17 00:12 re6exp

Ah, you write about configuration file. Sorry. I do not using this approach because of ľd prefer fine tuning. I didn't research this way, not sure.

re6exp avatar Dec 02 '17 00:12 re6exp

Keep in mind, it's a quite young project...

re6exp avatar Dec 02 '17 00:12 re6exp

Hey guys, is it possible to modify response and return it immediately? for example I'm adding authorization and I want to reject further filtering if user is unauthorized?

malinovskiy-alex avatar Jan 29 '18 17:01 malinovskiy-alex

Look for an example in closed issues. There is an example from @WeirdBob (post filter implementation).

re6exp avatar Jan 29 '18 17:01 re6exp

As I understood from the example this filter will be invoked after request will be processed. I need to return response immediately in case of invalid authentication.

malinovskiy-alex avatar Jan 29 '18 19:01 malinovskiy-alex

@malinovskiy-alex see https://github.com/spring-cloud/spring-cloud-gateway/blob/master/spring-cloud-gateway-core/src/main/java/org/springframework/cloud/gateway/filter/factory/RequestRateLimiterGatewayFilterFactory.java#L69-L70 for how short circuit the request.

spencergibb avatar Jan 29 '18 20:01 spencergibb

Hey @spencergibb Thanks for your answer. The main question for me here is how can I modify response body in such case.

malinovskiy-alex avatar Jan 30 '18 08:01 malinovskiy-alex

@spencergibb Any thoughts on the question above? Thanks in advance

malinovskiy-alex avatar Feb 02 '18 23:02 malinovskiy-alex

@malinovskiy-alex Why don't you just throw an exception in your filter? you can then implement a WebExceptionHandler to return the response you want (headers & body). Throwing an exception will stop the filtering chain.

WeirdBob avatar Feb 06 '18 12:02 WeirdBob

That was one of the possible solutions, but I thought that there is some common way to update response body directly.

malinovskiy-alex avatar Feb 06 '18 13:02 malinovskiy-alex

Also will this solution not brake reactive logic of the cloud api gateway?

malinovskiy-alex avatar Feb 06 '18 13:02 malinovskiy-alex

I'm no expert but I'd say if you want to stop the filter chain, not route the request because of the authorization, the most logical thing to do is to throw an exception. It doesn't break the reactive logic, in the WebExceptionHandler you still have to return a Mono and you write in the response with a Publisher<> (even if for an error we just write a Mono). If you want to modify the response after the request has been routed and processed by the downstream server and it's the standard processing of your request, then see the examples linked in the comments of this issue on how to use a filter to decorate the response object. In our project we use both methods depending on the case: exceptions for all the error handling (authentication, authorization, missing security headers, malformed requests ...), and filters to modify the request/response bodies as part of the standard processing (requests are deciphered, we remove some fields of the responses and recipher them ...)

WeirdBob avatar Feb 06 '18 14:02 WeirdBob

Ok, thanks for your response. Let me check approach with webexceptionhandler.

malinovskiy-alex avatar Feb 06 '18 14:02 malinovskiy-alex

It works. Thank you.

malinovskiy-alex avatar Feb 06 '18 15:02 malinovskiy-alex