kandi background
Explore Kits

spring-cloud-gateway | Gateway built on Spring Framework 5.x and Spring Boot 2 | REST library

 by   spring-cloud Java Version: Current License: Apache-2.0

 by   spring-cloud Java Version: Current License: Apache-2.0

Download this library from

kandi X-RAY | spring-cloud-gateway Summary

spring-cloud-gateway is a Java library typically used in Web Services, REST, Spring Boot, Spring, Swagger applications. spring-cloud-gateway has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 6, Spring Boot 3 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • spring-cloud-gateway has a highly active ecosystem.
  • It has 3382 star(s) with 2588 fork(s). There are 224 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 275 open issues and 1695 have been closed. On average issues are closed in 178 days. There are 28 open pull requests and 0 closed requests.
  • It has a negative sentiment in the developer community.
  • The latest version of spring-cloud-gateway is current.
spring-cloud-gateway Support
Best in #REST
Average in #REST
spring-cloud-gateway Support
Best in #REST
Average in #REST

quality kandi Quality

  • spring-cloud-gateway has 0 bugs and 0 code smells.
spring-cloud-gateway Quality
Best in #REST
Average in #REST
spring-cloud-gateway Quality
Best in #REST
Average in #REST

securitySecurity

  • spring-cloud-gateway has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • spring-cloud-gateway code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
spring-cloud-gateway Security
Best in #REST
Average in #REST
spring-cloud-gateway Security
Best in #REST
Average in #REST

license License

  • spring-cloud-gateway is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
spring-cloud-gateway License
Best in #REST
Average in #REST
spring-cloud-gateway License
Best in #REST
Average in #REST

buildReuse

  • spring-cloud-gateway releases are not available. You will need to build from source code and install.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • It has 29007 lines of code, 2760 functions and 398 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
spring-cloud-gateway Reuse
Best in #REST
Average in #REST
spring-cloud-gateway Reuse
Best in #REST
Average in #REST
Top functions reviewed by kandi - BETA

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.

  • Custom custom routes .
  • Determines if the route is allowed for the given route id
  • Add a weight configuration
  • Creates HttpClient instance .
  • Helper method to lookup routes .
  • Returns headers filters .
  • Creates custom headers for the exchange .
  • Helper method to exchange a request entity .
  • Gets the input stream .
  • Returns the routes .

spring-cloud-gateway Key Features

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

copy iconCopydownload iconDownload
$ ./mvnw install

Working with the code

copy iconCopydownload iconDownload
$ ./mvnw eclipse:eclipse

Checkstyle

copy iconCopydownload iconDownload
(3)

IDE setup

copy iconCopydownload iconDownload
(3)

Duplicate Finder

copy iconCopydownload iconDownload
<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

copy iconCopydownload iconDownload
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

copy iconCopydownload iconDownload
@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

copy iconCopydownload iconDownload
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

copy iconCopydownload iconDownload
@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

copy iconCopydownload iconDownload
"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

copy iconCopydownload iconDownload
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

copy iconCopydownload iconDownload
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

copy iconCopydownload iconDownload
@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

copy iconCopydownload iconDownload
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

copy iconCopydownload iconDownload
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

Community Discussions

Trending Discussions on spring-cloud-gateway
  • spring cloud gateway only forwards to base path of url
  • implementation of Gateway Global filter in Kotlin to Java implementation
  • Disable OPTIONS request before POST in React
  • 500 Internal Server Error in redirect-uri request Webflux + OAuth2.0
  • Disable OPTIONS request before POST and DELETE requests
  • How to load balance requests to all application pods when using Spring Cloud Gateway
  • How to prevent springboot gateway to forward to last element in the chain
  • Spring cloud gateway 2.5 with eureka return 404
  • java.lang.IllegalArgumentException: Unable to find GatewayFilterFactory with name JwtAuthenticationFilterGatewayFilterFactory
  • Spring Cloud Gateway Pass Client Certificate Information
Trending Discussions on spring-cloud-gateway

QUESTION

spring cloud gateway only forwards to base path of url

Asked 2022-Mar-20 at 18:59

I'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:59

Ok, 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();
  }

Source https://stackoverflow.com/questions/71545944

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install spring-cloud-gateway

In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. The following files can be found in the Spring Cloud Build project. Go to File → Settings → Editor → Code style. There click on the icon next to the Scheme section. There, click on the Import Scheme value and pick the Intellij IDEA code style XML option. Import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml file. Go to File → Settings → Editor → Inspections. There click on the icon next to the Profile section. There, click on the Import Profile and import the spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml file. To have Intellij work with Checkstyle, you have to install the Checkstyle plugin. It’s advisable to also install the Assertions2Assertj to automatically convert the JUnit assertions.
Default Checkstyle rules
File header setup
Default suppression rules
Project defaults for Intellij that apply most of Checkstyle rules
Project style conventions for Intellij that apply most of Checkstyle rules
checkstyle.header.file - please point it to the Spring Cloud Build’s, spring-cloud-build-tools/src/main/resources/checkstyle-header.txt file either in your cloned repo or via the https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt URL.
checkstyle.suppressions.file - default suppressions. Please point it to the Spring Cloud Build’s, spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml file either in your cloned repo or via the https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml URL.
checkstyle.additional.suppressions.file - this variable corresponds to suppressions in your local project. E.g. you’re working on spring-cloud-contract. Then point to the project-root/src/checkstyle/checkstyle-suppressions.xml folder. Example for spring-cloud-contract would be: /home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml.

Support

The spring-cloud-build module has a "docs" profile, and if you switch that on it will try to build asciidoc sources from src/main/asciidoc. As part of that process it will look for a README.adoc and process it by loading all the includes, but not parsing or rendering it, just copying it to ${main.basedir} (defaults to ${basedir}, i.e. the root of the project). If there are any changes in the README it will then show up after a Maven build as a modified file in the correct place. Just commit it and push the change.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.