Support
Quality
Security
License
Reuse
kandi has reviewed spring-cloud-gateway and discovered the below as its top functions. This is intended to give you an instant insight into spring-cloud-gateway implemented functionality, and help decide if they suit your requirements.
Java 17
Spring Framework 6
Spring Boot 3
Dynamic routing
Route matching built into Spring Handler Mapping
Route matching on HTTP Request (Path, Method, Header, Host, etc…)
Filters scoped to Matching Route
Filters can modify downstream HTTP Request and HTTP Response (Add/Remove Headers, Add/Remove Parameters, Rewrite Path, Set Path, Hystrix, etc…)
API or configuration driven
Supports Spring Cloud DiscoveryClient for configuring Routes
Basic Compile and Test
$ ./mvnw install
Working with the code
$ ./mvnw eclipse:eclipse
Checkstyle
(3)
IDE setup
(3)
Duplicate Finder
<build>
<plugins>
<plugin>
<groupId>org.basepom.maven</groupId>
<artifactId>duplicate-finder-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
spring cloud gateway only forwards to base path of url
private final URI routingTargetWithPath = URI.create("http://hapi.fhir.org/baseR4");
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("patient", r -> r
.path("/Patient", "/Patient/*")
.and()
.method(GET)
.filters(f -> f.prefixPath(routingTargetWithPath.getPath()))
.uri(routingTargetWithPath)
)
.build();
}
implementation of Gateway Global filter in Kotlin to Java implementation
@Component
public class AddCredentialsGlobalFilter implements GlobalFilter {
private final String usernameHeader = "logged-in-user";
private final String rolesHeader = "logged-in-user-roles";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return exchange.getPrincipal().flatMap(p -> {
List<GrantedAuthority> authorities = (List<GrantedAuthority>) ((Authentication)p).getAuthorities();
String rolesString = authorities != null
? authorities.stream().map(Object::toString).collect(Collectors.joining(";"))
: "";
ServerHttpRequest request = exchange.getRequest().mutate()
.header(usernameHeader, p.getName())
.header(rolesHeader, rolesString)
.build();
return chain.filter(exchange.mutate().request(request).build());
});
}
}
Disable OPTIONS request before POST in React
module.exports = {
devServer: {
proxy: 'http://1.1.1.1:8080',
},
## macOS
open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials
## windows
chrome.exe --disable-web-security
## linux
google-chrome --disable-web-security
-----------------------
module.exports = {
devServer: {
proxy: 'http://1.1.1.1:8080',
},
## macOS
open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials
## windows
chrome.exe --disable-web-security
## linux
google-chrome --disable-web-security
-----------------------
module.exports = {
devServer: {
proxy: 'http://1.1.1.1:8080',
},
## macOS
open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials
## windows
chrome.exe --disable-web-security
## linux
google-chrome --disable-web-security
-----------------------
module.exports = {
devServer: {
proxy: 'http://1.1.1.1:8080',
},
## macOS
open -na Google\ Chrome --args --user-data-dir=/tmp/temporary-chrome-profile-dir --disable-web-security --disable-site-isolation-trials
## windows
chrome.exe --disable-web-security
## linux
google-chrome --disable-web-security
500 Internal Server Error in redirect-uri request Webflux + OAuth2.0
@Configuration(proxyBeanMethods = false)
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class WebFluxSecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, AuthenticationManager authenticationManager) {
return http
.httpBasic().disable()
.csrf().disable()
.authorizeExchange(exchanges -> exchanges
.pathMatchers(HttpMethod.GET, "/oauth2/authorization/**",
"/actuator",
"/actuator/**",
"/auth/login",
"/login/**")
.permitAll()
.anyExchange()
.authenticated()
.oauth2Login()
.authenticationManager(authenticationManager)
.and()
.build();
}
}
Disable OPTIONS request before POST and DELETE requests
"proxy": "your-backend-base-url"
-----------------------
npm install http-proxy-middleware --save
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3080',
changeOrigin: true,
})
);
};
devServer: {
historyApiFallBack: true,
contentBase: path.resolve(__dirname, 'public'),
proxy: {
'/v1/**': {
target: 'http://url',
secure: false,
changeOrigin: true
}
}
},
-----------------------
npm install http-proxy-middleware --save
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3080',
changeOrigin: true,
})
);
};
devServer: {
historyApiFallBack: true,
contentBase: path.resolve(__dirname, 'public'),
proxy: {
'/v1/**': {
target: 'http://url',
secure: false,
changeOrigin: true
}
}
},
-----------------------
npm install http-proxy-middleware --save
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:3080',
changeOrigin: true,
})
);
};
devServer: {
historyApiFallBack: true,
contentBase: path.resolve(__dirname, 'public'),
proxy: {
'/v1/**': {
target: 'http://url',
secure: false,
changeOrigin: true
}
}
},
How to load balance requests to all application pods when using Spring Cloud Gateway
implementation("org.springframework.cloud:spring-cloud-loadbalancer")
implementation("org.springframework.cloud:spring-cloud-starter-kubernetes-fabric8")
Spring cloud gateway 2.5 with eureka return 404
spring:
application:
name: api-gateway
cloud:
gateway:
discovery:
locator:
lower-case-service-id: true
enabled: false
routes:
- id: my-service
uri: lb://my-service
predicates:
- Path=/service/**
filters:
- RewritePath=/service(?<segment>/?.*), /${segment}
java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name JwtAuthenticationFilterGatewayFilterFactory
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/get")
.filters(f -> f.addRequestHeader("Hello", "World"))
.uri("http://httpbin.org:80"))
.build();
}
Spring Cloud Gateway Pass Client Certificate Information
public class ClientSSLToHeaderFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest req = exchange.getRequest();
SslInfo info = req.getSslInfo();
if(info != null) {
X509Certificate[] certs = info.getPeerCertificates();
if(certs != null && certs.length > 0) {
ServerHttpRequest request = exchange.getRequest().mutate()
.headers(httpHeaders -> {
try {
certs[0].checkValidity();
String encodedCert = new String(Base64.getEncoder().encode(certs[0].getEncoded()));
httpHeaders.add("SSL_CLIENT_CERT", encodedCert);
httpHeaders.add("SSL_CLIENT_VERIFY", "success");
} catch(CertificateEncodingException | CertificateExpiredException
| CertificateNotYetValidException e) {
// TODO Auto-generated catch block
log.log(Level.ERROR, e, e);
}
}).build();
return chain.filter(exchange.mutate().request(request).build());
}
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return -1;
}
Spring Cloud Gateway Preflight Cors Error with Angular
http.cors();
@Configuration
@EnableWebMvc
public class RestServiceCorsApplication implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
-----------------------
http.cors();
@Configuration
@EnableWebMvc
public class RestServiceCorsApplication implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
-----------------------
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTIONS
spring.cloud.gateway.routes[0].predicates[1] = Method=GET,POST,OPTIONS
-----------------------
allowedMethods:
- GET
- POST
- DELETE
- PUT
- OPTIONS
spring.cloud.gateway.routes[0].predicates[1] = Method=GET,POST,OPTIONS
QUESTION
spring cloud gateway only forwards to base path of url
Asked 2022-Mar-20 at 18:59I'm trying to build a simple api-gateway using spring-cloud-gateway. So far I understood the basic principle but I'm running in a specific Problem:
The target url which I'm forwarding my request potentially contains zero, one or multiple path segments. Unfortunately, these path segments are ignored.
private final String routingTargetWithPath = "http://hapi.fhir.org/baseR4";
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("patient", r -> r
.path("/Patient", "/Patient/*")
.and()
.method(GET)
.uri(routingTargetWithPath)
)
.build();
}
Using curl sending the request to my api-gateway:
curl http://localhost:8080/Patient
and accordingly
curl http://localhost:8080/Patient/2069748
I would assume the requests would be routed to:
http://hapi.fhir.org/baseR4/Patient
and accordingly
http://hapi.fhir.org/baseR4/Patient/2069748
But instead they are being routed to:
http://hapi.fhir.org/Patient
and accordingly
http://hapi.fhir.org/Patient/2069748
So, the path of the configured routing url is ignored. Unfortunately, I can't do a manual rewrite here, since in production the "routingTarget" will be configured and I don't know, if and how many path segments it will contain.
How can I achieve to route to the complete configured routing target?
ANSWER
Answered 2022-Mar-20 at 18:59Ok, I found the answer: According to here it is intentional, that the path of the uri is ignored. So in my case, the set path filter would fix the problem:
private final URI routingTargetWithPath = URI.create("http://hapi.fhir.org/baseR4");
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("patient", r -> r
.path("/Patient", "/Patient/*")
.and()
.method(GET)
.filters(f -> f.prefixPath(routingTargetWithPath.getPath()))
.uri(routingTargetWithPath)
)
.build();
}
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Explore Related Topics
Save this library and start creating your kit