How to forward a path variable in Spring Cloud Gateway 2.0?
If we have an microservice that has 2 endpoints: /users and /users/{id} and is running on port 8080, how to forward the request to the endpoint with the id path variable?
The following gateway configuration successfully forwards to the /users end point, but the second route forwards the request to the same /users endpoint of the real service.
#Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("users", t -> t.path("/users").uri("http://localhost:8080/users"))
.route("userById", t -> t.path("/users/**").uri("http://localhost:8080/users/"))
.build();
}
I'm using spring-cloud-starter-gateway from spring cloud Finchley.BUILD-SNAPSHOT
A rewritePath filter has to be used:
#Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("users", t -> t.path("/users")
.uri("http://localhost:8080/users"))
.route("userById", t -> t.path("/users/**")
.filters(rw -> rw.rewritePath("/users/(?<segment>.*)", "/users/${segment}"))
.uri("http://localhost:8080/users/"))
.build();
}
The YAML version is specified in the documentation:
spring:
cloud:
gateway:
routes:
- id: rewritepath_route
uri: http://example.org
predicates:
- Path=/foo/**
filters:
- RewritePath=/foo/(?<segment>.*), /$\{segment}
After some research, please find below what worked for me. Both methods produce the same result.
Here is my set-up:
the gateway is running on http://localhost:8090
a base path called /context serves as the entry point of the gateway
a service called my-resources running on http://localhost:8091/my-resources. When /my-resources is invoked without parameters, it returns all resources. When it is invoked with a parameters it returns the resource with the corresponding RID (if any)
The gateway is configured so that all path variables (possibly none) transmitted to http://localhost:8090/context/my-resources/ is forwarded to uri http://localhost:8091/my-resources/.
Method 1: using application.yml
spring:
cloud:
gateway:
routes:
- id: route_id
predicates:
- Path=/context/my-resources/**
filters:
- RewritePath=/context/my-resources/(?<RID>.*), /my-resources/$\{RID}
uri: http://localhost:8091
Method 2: using Java like configuration
#Bean
public RouteLocator routes(RouteLocatorBuilder routeBuilder) {
return routeBuilder.routes()
.route("route_id",
route -> route
.path("/context/my-resources/**")
.filters(f -> f.rewritePath("/context/my-resources/(?<RID>.*)", "/my-resources/${RID}"))
.uri("http://localhost:8091")
)
.build();
}
Related
It is normal to use most of the time, and 404 appears occasionally. I don’t know how to locate the problem.
controller file:
#RestController
#RequestMapping("/auth")
#RequiredArgsConstructor
public class AuthController {
private final AuthService authService;
#GetMapping("info")
public Result info(#RequestParam("token") String token) {
Map<String, Object> stringObjectMap = authService.getInfo(token);
return ResultGenerator.success(stringObjectMap);
}
}
GET: localhost:9000/v1/auth/info?token=gNGLJLLZsluDsIQw This ERROR MESSAGE is displaying time to time:
{
"timestamp": "2021-06-29T06:46:35.477+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/auth/info"
}
version info:
spring boot: 2.2.6.RELEASE
spring cloud: Hoxton.SR1
Append:
spring cloud gateway yml config:
spring:
application:
name: gateway-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
gateway:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Origin
globalcors:
cors-configurations:
"[/**]":
allowCredentials: true
allowedOrigins: "*"
allowedHeaders: "Origin, X-Requested-With, Content-Type, Accept, Content-Length, TOKEN, Authorization"
allowedMethods: "GET, POST, PATCH, PUT, DELETE, OPTIONS"
maxAge: 3628800
discovery:
locator:
enabled: true
lower-case-service-id: true
routes:
- id: auth-service
uri: lb://auth-service
predicates:
- Path=/v1/auth/**
filters:
- StripPrefix=1
- id: bus-service
uri: lb://bus-service
predicates:
- Path=/v1/**
filters:
- StripPrefix=1
Solution to be verified
I used the zipkin, found the route /v1/auth/info matched to bus-service(/v1/**), so return 404 not found.
From this to the conclusion:The writing order of the route does not guarantee its matching priority. So must add order configuration.
Try removing #RequestMapping("/auth") and replacing #GetMapping("info") to look like below:
#GetMapping("auth/info")
public Result info(#RequestParam("token") String token) {
Map<String, Object> stringObjectMap = authService.getInfo(token);
Please add / before info like this
#GetMapping("/info")
public Result info(#RequestParam("token") String token) {
Map<String, Object> stringObjectMap = authService.getInfo(token);
return ResultGenerator.success(stringObjectMap);
}
Since you are using #RequestParam, you need to pass value like this
localhost:9000/auth/info?token="token_value"
Please check this:
If the url has a lb scheme (ie lb://myservice), it will use the Spring
Cloud LoadBalancerClient to resolve the name (myservice in the
previous example) to an actual host and port and replace the URI in
the same attribute.
By default when a service instance cannot be found in the LoadBalancer
a 503 will be returned. You can configure the Gateway to return a 404
by setting spring.cloud.gateway.loadbalancer.use404=true.
You can also try to specify an order in routes list:
routes:
- id: auth-service
uri: lb://auth-service
order: 0
predicates:
- Path=/v1/auth/**
filters:
- StripPrefix=1
- id: bus-service
uri: lb://bus-service
order: 1
predicates:
- Path=/v1/**
filters:
- StripPrefix=1
I have Spring gateway: localhost:7856 and microservice - "my-service", for example localhost:8081. I can get access to endpoint localhost:8081/actuator/health -> {"status": "UP"}. But I need to access such endpoint through gateway like localhost:7856/my-service/actuator/health
My gateway config:
zuul:
ignoredServices: '*'
routes:
my-service:
path: /my-service/**
serviceId: my-service
stripPrefix: false
Here, crucial moment, I can't change stripPrefix to true. I know, that I can add
management:
endpoints:
web:
base-path: /my-service/actuator
but it wouldn't be good solution, because in that case also need to change eureka config (for eureka default endpoint is service-name/actuator/health) for check health status for microservices. Or I can create additional endpoint that would redirect to what I need. But I'm trying to find the best decision, may be its a special property for zuul or overriding zuul classes ?
Finally, I found a solution.
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.SimpleRouteLocator;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties.ZuulRoute;
public class CustomRouteLocator extends SimpleRouteLocator {
public CustomRouteLocator(String servletPath, ZuulProperties properties) {
super(servletPath, properties);
}
#Override
protected Route getRoute(ZuulRoute route, String path) {
boolean oldPrefix = route.isStripPrefix();
if (path.matches(".*/actuator/.*")) {
route.setStripPrefix(true);
}
Route resultRoute = super.getRoute(route, path);
route.setStripPrefix(oldPrefix);
return resultRoute;
}
}
I turn on/off stripPrefix property. That works well.
There are 2 ways to add request and response headers via a bean from RouteLocator or via properties.
However would need an example to add default filters (below) via a bean as the service-response-value and service-request-value would be a dynamic value :
spring
cloud:
gateway:
default-filters:
- AddRequestHeader= service-request, service-request-value
- AddResponseHeader= service-response, service-response-value
Spring Cloud Gateway doesn't support default filters via Beans
https://github.com/spring-cloud/spring-cloud-gateway/issues/263
I am using Spring boot 2.3.3.RELASE and using webflux. Using the below router config.
#Bean
public RouterFunction<ServerResponse> itemRoute() {
return RouterFunctions.route(POST("/api/v1/item").and(accept(APPLICATION_JSON)), itemHandler::createItem)
.andRoute(GET("/api/v1/item/{itemId}").and(accept(APPLICATION_JSON)), itemHandler::getItemById)
.andRoute(GET("/api/v1/item/list").and(accept(APPLICATION_JSON)), itemHandler::getItems);
}
When I hit /api/v1/item/1 ---> It works as expected.
But, hitting /api/v1/list also goes to getItemById instead of getItems. /api/v1/item/list also considered as /api/v1/item/{itemId} and list is coming as itemId.
Anything wrong with this?
Spring documentation for andRoute
Return a composed routing function that routes to the given handler function if this route does not match and the given request predicate applies.
The key word here is composed. It means that you can declare multiple routes that all together must match together for the route to trigger.
what you are looking for is probably just using the plain route builder function.
Taken example from the spring documentation:
RouterFunction<ServerResponse> route = route()
.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson)
.GET("/person", accept(APPLICATION_JSON), handler::listPeople)
.POST("/person", handler::createPerson)
.add(otherRoute)
.build();
or you could use the path builder function is another option.
RouterFunction<ServerResponse> route = route()
.path("/api/person", builder -> builder
.POST( ...)
.GET( ... )
.GET( ... )
).build())
.build()
Webflux Router Function
My current architecture for my web app has a gateway server that orchestrates a bunch of microservices, authorisation occurs at the gateway if a given principle is authenticated they can talk to some downstream services.
The downstream service gets hold of the required data to identify a given authenticated client. However spring securities default behaviour kicks in and throws the expected:
org.springframework.security.access.AccessDeniedException: Access is denied
Given that I can use the session id and + XSRF token in any given Microservice to validate the user is authenticated and know which user is logged in (i'm currently using Http Basic).
My question is there a simpler / declarative approach that could be used in place of having to adding a filter to every Microservice to override spring securities default behaviour? (see my example Pseudo code)
See the attached diagram: Architecture.
Spring web security config for resource server:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public SessionRepository<ExpiringSession> sessionRepository() {
return new MapSessionRepository();
}
#Bean
HeaderHttpSessionStrategy sessionStrategy() {
return new HeaderHttpSessionStrategy();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and().authorizeRequests().anyRequest().authenticated();
final SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter<ExpiringSession>(
sessionRepository());
sessionRepositoryFilter
.setHttpSessionStrategy(new HeaderHttpSessionStrategy());
http.addFilterBefore(sessionRepositoryFilter,
ChannelProcessingFilter.class).csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
}
public SessionRepository<ExpiringSession> getSessionRepository(){
return sessionRepository();
}
}
Header values at the resource microservice:
KEY: cookie VALUE: XSRF-TOKEN=[token_value]; SESSION=[session_value]
KEY: x-requested-with VALUE: XMLHttpRequest
KEY: x-auth-token VALUE: a32302fd-589b-42e1-8b9d-1991a080e904
...
Planned approach (Pseudo code) attach a new filter to the spring securities filter chain that if given flags are true, allow access to secured endpoints.
**
* A custom filter that can grant access to the current resource
* if there is a valid XSRF-TOKEN and SESSION present in the shared
* session cache.
*/
public class CustomAuthenticationFilter extends AnAppropriateFilterChainFilter {
#Autowired
SessionRepository sessionRepository;
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
boolean csrfTokenExists = sessionRepository.findByCsrfTokenId(request);
boolean sessionExists = sessionRepository.findBySessionId(request);
if (csrfTokenExists && sessionExists) {
// everything is okay
} else {
// invalidate the request as being authenticated
throw new InsufficientAuthenticationException("Invalid csrf + session pair");
}
}
}
After updating my spring boot parent to 2.0.1 Release and changing my spring cloud version to Finchley the issue was resolved by spring boot.
Note session repository and HttpSessionStrategy aren't required,
HttpSessionStrategy is now depreciated since spring session became spring session core.
Using the externalised config for redis and spring boot, all the dependant systems automatically use that cache for validating a valid session providing you have spring security on your class path.
Note if you are using the gateway pattern and Zuul Proxy ensure your proxy routes include the sensitive-headers: property in your app YML / properties, see examples below:
Example auth + gateway using Springboot Configuration of a shared session cache.
Auth Gateway
spring:
profiles: dev
redis:
host: localhost
port: 6379
session:
store-type: redis
server:
port: 8080
zuul:
routes:
# local routes
api:
url: forward:/api
path: /api/**
sensitive-headers:
# cloud-resource
resource:
url: http://localhost:9002
path: /resource/**
strip-prefix: false
sensitive-headers:
proxy:
auth:
routes:
resource: passthru
ui: none
api: passthru
security:
sessions: ALWAYS
Some Secured Resource Server
spring:
profiles: dev
redis:
host: localhost
port: 6379
session:
store-type: redis
security:
enabled: false
server:
port: 9002
security:
# Never create a session, but if one exists use it
sessions: NEVER
# don't display the auth box
basic:
enabled: false
management:
security:
enabled: false