JAVA-13321 Added new gateway module to existing microservices e-book
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
# OAuth Test Setup
|
||||
|
||||
In order to test the OAuth-secured gateway configurations, please follow the steps below
|
||||
|
||||
## Keycloak setup
|
||||
|
||||
1. Clone or download the https://github.com/Baeldung/spring-security-oauth project
|
||||
2. Replace the file `oauth-rest/oauth-authorization-server/src/main/resources/baeldung-realm.json`
|
||||
with the one provider here
|
||||
3. Go to the oauth-rest/oauth-authorization-server folder and use maven to build the project
|
||||
4. Run the Keycloack service with `mvn spring-boot:run`
|
||||
5. Once Keycloak is up and running, go to `http://localhost:8083/auth/admin/master/console/#/realms/baeldung` and
|
||||
log in with using `bael-admin/pass` as credentials
|
||||
6. Create two test users, so that one belongs to the *Golden Customers* group and the other doesn't.
|
||||
|
||||
## Quotes backend
|
||||
|
||||
Use the provided maven profile:
|
||||
|
||||
```
|
||||
$ mvn spring-boot:run -Pquotes-application
|
||||
```
|
||||
|
||||
## Gateway as Resource Server
|
||||
|
||||
Use the provided maven profile:
|
||||
|
||||
```
|
||||
$ mvn spring-boot:run -Pgateway-as-resource-server
|
||||
```
|
||||
|
||||
## Gateway as OAuth 2.0 Client
|
||||
|
||||
Use the provided maven profile:
|
||||
|
||||
```
|
||||
$ mvn spring-boot:run -Pgateway-as-oauth-client
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
## Spring Cloud Gateway
|
||||
|
||||
This module contains articles about Spring Cloud Gateway
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Exploring the New Spring Cloud Gateway](http://www.baeldung.com/spring-cloud-gateway)
|
||||
- [Writing Custom Spring Cloud Gateway Filters](https://www.baeldung.com/spring-cloud-custom-gateway-filters)
|
||||
- [Spring Cloud Gateway Routing Predicate Factories](https://www.baeldung.com/spring-cloud-gateway-routing-predicate-factories)
|
||||
- [Spring Cloud Gateway WebFilter Factories](https://www.baeldung.com/spring-cloud-gateway-webfilter-factories)
|
||||
- [Using Spring Cloud Gateway with OAuth 2.0 Patterns](https://www.baeldung.com/spring-cloud-gateway-oauth2)
|
||||
- [URL Rewriting With Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway-url-rewriting)
|
||||
- [Processing the Response Body in Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway-response-body)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,194 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>gateway-2</artifactId>
|
||||
<name>spring-cloud-gateway</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring.cloud</groupId>
|
||||
<artifactId>spring-cloud-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud-dependencies.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-gateway</artifactId>
|
||||
</dependency>
|
||||
<!-- Circuit Breaker -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</artifactId>
|
||||
</dependency>
|
||||
<!-- Redis -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
|
||||
</dependency>
|
||||
<!-- Embedded Redis -->
|
||||
<dependency>
|
||||
<groupId>it.ozimov</groupId>
|
||||
<artifactId>embedded-redis</artifactId>
|
||||
<version>${redis.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator-cdi</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
</dependency>
|
||||
<!-- Spring security -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>quotes-application</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.springcloudgateway.oauth.backend.QuotesApplication</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>gateway-as-resource-server</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.springcloudgateway.oauth.server.ResourceServerGatewayApplication</mainClass>
|
||||
<jvmArguments>-Dspring.profiles.active=resource-server</jvmArguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>gateway-as-oauth-client</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.springcloudgateway.oauth.server.ResourceServerGatewayApplication</mainClass>
|
||||
<jvmArguments>-Dspring.profiles.active=oauth-client</jvmArguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>gateway-url-rewrite</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.springcloudgateway.rewrite.URLRewriteGatewayApplication</mainClass>
|
||||
<jvmArguments>-Dspring.profiles.active=url-rewrite</jvmArguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- <spring-cloud-dependencies.version>Hoxton.SR3</spring-cloud-dependencies.version> -->
|
||||
<!-- <spring-boot.version>2.2.6.RELEASE</spring-boot.version> -->
|
||||
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
|
||||
<redis.version>0.7.2</redis.version>
|
||||
<oauth2-oidc-sdk.version>9.19</oauth2-oidc-sdk.version>
|
||||
<!-- <junit-bom.version>5.5.2</junit-bom.version> -->
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:customfilters-global-application.properties")
|
||||
public class CustomFiltersGatewayApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CustomFiltersGatewayApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
@Configuration
|
||||
public class WebClientConfig {
|
||||
|
||||
@Bean
|
||||
WebClient client() {
|
||||
return WebClient.builder()
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.factories;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale.LanguageRange;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class ChainRequestGatewayFilterFactory extends AbstractGatewayFilterFactory<ChainRequestGatewayFilterFactory.Config> {
|
||||
|
||||
final Logger logger = LoggerFactory.getLogger(ChainRequestGatewayFilterFactory.class);
|
||||
|
||||
private final WebClient client;
|
||||
|
||||
public ChainRequestGatewayFilterFactory(WebClient client) {
|
||||
super(Config.class);
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> shortcutFieldOrder() {
|
||||
return Arrays.asList("languageServiceEndpoint", "defaultLanguage");
|
||||
}
|
||||
|
||||
@Override
|
||||
public GatewayFilter apply(Config config) {
|
||||
return (exchange, chain) -> {
|
||||
return client.get()
|
||||
.uri(config.getLanguageServiceEndpoint())
|
||||
.exchange()
|
||||
.flatMap(response -> {
|
||||
return (response.statusCode()
|
||||
.is2xxSuccessful()) ? response.bodyToMono(String.class) : Mono.just(config.getDefaultLanguage());
|
||||
})
|
||||
.map(LanguageRange::parse)
|
||||
.map(range -> {
|
||||
exchange.getRequest()
|
||||
.mutate()
|
||||
.headers(h -> h.setAcceptLanguage(range));
|
||||
|
||||
String allOutgoingRequestLanguages = exchange.getRequest()
|
||||
.getHeaders()
|
||||
.getAcceptLanguage()
|
||||
.stream()
|
||||
.map(r -> r.getRange())
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
logger.info("Chain Request output - Request contains Accept-Language header: " + allOutgoingRequestLanguages);
|
||||
|
||||
return exchange;
|
||||
})
|
||||
.flatMap(chain::filter);
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
public static class Config {
|
||||
private String languageServiceEndpoint;
|
||||
private String defaultLanguage;
|
||||
|
||||
public Config() {
|
||||
}
|
||||
|
||||
public String getLanguageServiceEndpoint() {
|
||||
return languageServiceEndpoint;
|
||||
}
|
||||
|
||||
public void setLanguageServiceEndpoint(String languageServiceEndpoint) {
|
||||
this.languageServiceEndpoint = languageServiceEndpoint;
|
||||
}
|
||||
|
||||
public String getDefaultLanguage() {
|
||||
return defaultLanguage;
|
||||
}
|
||||
|
||||
public void setDefaultLanguage(String defaultLanguage) {
|
||||
this.defaultLanguage = defaultLanguage;
|
||||
}
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.factories;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class LoggingGatewayFilterFactory extends AbstractGatewayFilterFactory<LoggingGatewayFilterFactory.Config> {
|
||||
|
||||
final Logger logger = LoggerFactory.getLogger(LoggingGatewayFilterFactory.class);
|
||||
|
||||
public static final String BASE_MSG = "baseMessage";
|
||||
public static final String PRE_LOGGER = "preLogger";
|
||||
public static final String POST_LOGGER = "postLogger";
|
||||
|
||||
public LoggingGatewayFilterFactory() {
|
||||
super(Config.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> shortcutFieldOrder() {
|
||||
return Arrays.asList(BASE_MSG, PRE_LOGGER, POST_LOGGER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GatewayFilter apply(Config config) {
|
||||
return new OrderedGatewayFilter((exchange, chain) -> {
|
||||
if (config.isPreLogger())
|
||||
logger.info("Pre GatewayFilter logging: " + config.getBaseMessage());
|
||||
return chain.filter(exchange)
|
||||
.then(Mono.fromRunnable(() -> {
|
||||
if (config.isPostLogger())
|
||||
logger.info("Post GatewayFilter logging: " + config.getBaseMessage());
|
||||
}));
|
||||
}, 1);
|
||||
}
|
||||
|
||||
public static class Config {
|
||||
private String baseMessage;
|
||||
private boolean preLogger;
|
||||
private boolean postLogger;
|
||||
|
||||
public Config() {
|
||||
};
|
||||
|
||||
public Config(String baseMessage, boolean preLogger, boolean postLogger) {
|
||||
super();
|
||||
this.baseMessage = baseMessage;
|
||||
this.preLogger = preLogger;
|
||||
this.postLogger = postLogger;
|
||||
}
|
||||
|
||||
public String getBaseMessage() {
|
||||
return this.baseMessage;
|
||||
}
|
||||
|
||||
public boolean isPreLogger() {
|
||||
return preLogger;
|
||||
}
|
||||
|
||||
public boolean isPostLogger() {
|
||||
return postLogger;
|
||||
}
|
||||
|
||||
public void setBaseMessage(String baseMessage) {
|
||||
this.baseMessage = baseMessage;
|
||||
}
|
||||
|
||||
public void setPreLogger(boolean preLogger) {
|
||||
this.preLogger = preLogger;
|
||||
}
|
||||
|
||||
public void setPostLogger(boolean postLogger) {
|
||||
this.postLogger = postLogger;
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.factories;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
@Component
|
||||
public class ModifyRequestGatewayFilterFactory extends AbstractGatewayFilterFactory<ModifyRequestGatewayFilterFactory.Config> {
|
||||
|
||||
final Logger logger = LoggerFactory.getLogger(ModifyRequestGatewayFilterFactory.class);
|
||||
|
||||
public ModifyRequestGatewayFilterFactory() {
|
||||
super(Config.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> shortcutFieldOrder() {
|
||||
return Arrays.asList("defaultLocale");
|
||||
}
|
||||
|
||||
@Override
|
||||
public GatewayFilter apply(Config config) {
|
||||
return (exchange, chain) -> {
|
||||
if (exchange.getRequest()
|
||||
.getHeaders()
|
||||
.getAcceptLanguage()
|
||||
.isEmpty()) {
|
||||
|
||||
String queryParamLocale = exchange.getRequest()
|
||||
.getQueryParams()
|
||||
.getFirst("locale");
|
||||
|
||||
Locale requestLocale = Optional.ofNullable(queryParamLocale)
|
||||
.map(l -> Locale.forLanguageTag(l))
|
||||
.orElse(config.getDefaultLocale());
|
||||
|
||||
exchange.getRequest()
|
||||
.mutate()
|
||||
.headers(h -> h.setAcceptLanguageAsLocales(Collections.singletonList(requestLocale)));
|
||||
}
|
||||
|
||||
String allOutgoingRequestLanguages = exchange.getRequest()
|
||||
.getHeaders()
|
||||
.getAcceptLanguage()
|
||||
.stream()
|
||||
.map(range -> range.getRange())
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
logger.info("Modify request output - Request contains Accept-Language header: {}", allOutgoingRequestLanguages);
|
||||
|
||||
ServerWebExchange modifiedExchange = exchange.mutate()
|
||||
.request(originalRequest -> originalRequest.uri(UriComponentsBuilder.fromUri(exchange.getRequest()
|
||||
.getURI())
|
||||
.replaceQueryParams(new LinkedMultiValueMap<String, String>())
|
||||
.build()
|
||||
.toUri()))
|
||||
.build();
|
||||
|
||||
logger.info("Removed all query params: {}", modifiedExchange.getRequest()
|
||||
.getURI());
|
||||
|
||||
return chain.filter(modifiedExchange);
|
||||
};
|
||||
}
|
||||
|
||||
public static class Config {
|
||||
private Locale defaultLocale;
|
||||
|
||||
public Config() {
|
||||
}
|
||||
|
||||
public Locale getDefaultLocale() {
|
||||
return defaultLocale;
|
||||
}
|
||||
|
||||
public void setDefaultLocale(String defaultLocale) {
|
||||
this.defaultLocale = Locale.forLanguageTag(defaultLocale);
|
||||
};
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.factories;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||
import org.springframework.http.server.reactive.ServerHttpResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class ModifyResponseGatewayFilterFactory extends AbstractGatewayFilterFactory<ModifyResponseGatewayFilterFactory.Config> {
|
||||
|
||||
final Logger logger = LoggerFactory.getLogger(ModifyResponseGatewayFilterFactory.class);
|
||||
|
||||
public ModifyResponseGatewayFilterFactory() {
|
||||
super(Config.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GatewayFilter apply(Config config) {
|
||||
return (exchange, chain) -> {
|
||||
return chain.filter(exchange)
|
||||
.then(Mono.fromRunnable(() -> {
|
||||
ServerHttpResponse response = exchange.getResponse();
|
||||
|
||||
Optional.ofNullable(exchange.getRequest()
|
||||
.getQueryParams()
|
||||
.getFirst("locale"))
|
||||
.ifPresent(qp -> {
|
||||
String responseContentLanguage = response.getHeaders()
|
||||
.getContentLanguage()
|
||||
.getLanguage();
|
||||
|
||||
response.getHeaders()
|
||||
.add("Bael-Custom-Language-Header", responseContentLanguage);
|
||||
logger.info("Added custom header to Response");
|
||||
});
|
||||
}));
|
||||
};
|
||||
}
|
||||
|
||||
public static class Config {
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.factories;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.reactivestreams.Publisher;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyResponseBodyGatewayFilterFactory;
|
||||
import org.springframework.cloud.gateway.filter.factory.rewrite.RewriteFunction;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import com.fasterxml.jackson.core.TreeNode;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class ScrubResponseGatewayFilterFactory extends AbstractGatewayFilterFactory<ScrubResponseGatewayFilterFactory.Config> {
|
||||
|
||||
final Logger logger = LoggerFactory.getLogger(ScrubResponseGatewayFilterFactory.class);
|
||||
private ModifyResponseBodyGatewayFilterFactory modifyResponseBodyFilterFactory;
|
||||
|
||||
public ScrubResponseGatewayFilterFactory(ModifyResponseBodyGatewayFilterFactory modifyResponseBodyFilterFactory) {
|
||||
super(Config.class);
|
||||
this.modifyResponseBodyFilterFactory = modifyResponseBodyFilterFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> shortcutFieldOrder() {
|
||||
return Arrays.asList("fields", "replacement");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public GatewayFilter apply(Config config) {
|
||||
|
||||
return modifyResponseBodyFilterFactory
|
||||
.apply(c -> c.setRewriteFunction(JsonNode.class, JsonNode.class, new Scrubber(config)));
|
||||
}
|
||||
|
||||
public static class Config {
|
||||
|
||||
private String fields;
|
||||
private String replacement;
|
||||
|
||||
|
||||
public String getFields() {
|
||||
return fields;
|
||||
}
|
||||
public void setFields(String fields) {
|
||||
this.fields = fields;
|
||||
}
|
||||
public String getReplacement() {
|
||||
return replacement;
|
||||
}
|
||||
public void setReplacement(String replacement) {
|
||||
this.replacement = replacement;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class Scrubber implements RewriteFunction<JsonNode,JsonNode> {
|
||||
private final Pattern fields;
|
||||
private final String replacement;
|
||||
|
||||
public Scrubber(Config config) {
|
||||
this.fields = Pattern.compile(config.getFields());
|
||||
this.replacement = config.getReplacement();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Publisher<JsonNode> apply(ServerWebExchange t, JsonNode u) {
|
||||
return Mono.just(scrubRecursively(u));
|
||||
}
|
||||
|
||||
private JsonNode scrubRecursively(JsonNode u) {
|
||||
if ( !u.isContainerNode()) {
|
||||
return u;
|
||||
}
|
||||
|
||||
if ( u.isObject()) {
|
||||
ObjectNode node = (ObjectNode)u;
|
||||
node.fields().forEachRemaining((f) -> {
|
||||
if ( fields.matcher(f.getKey()).matches() && f.getValue().isTextual()) {
|
||||
f.setValue(TextNode.valueOf(replacement));
|
||||
}
|
||||
else {
|
||||
f.setValue(scrubRecursively(f.getValue()));
|
||||
}
|
||||
});
|
||||
}
|
||||
else if ( u.isArray()) {
|
||||
ArrayNode array = (ArrayNode)u;
|
||||
for ( int i = 0 ; i < array.size() ; i++ ) {
|
||||
array.set(i, scrubRecursively(array.get(i)));
|
||||
}
|
||||
}
|
||||
|
||||
return u;
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.global;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||
import org.springframework.cloud.gateway.filter.GlobalFilter;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class FirstPreLastPostGlobalFilter implements GlobalFilter, Ordered {
|
||||
|
||||
final Logger logger = LoggerFactory.getLogger(FirstPreLastPostGlobalFilter.class);
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
logger.info("First Pre Global Filter");
|
||||
return chain.filter(exchange)
|
||||
.then(Mono.fromRunnable(() -> {
|
||||
logger.info("Last Post Global Filter");
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.global;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties("logging.global")
|
||||
public class LoggingGlobalFilterProperties {
|
||||
|
||||
private boolean enabled;
|
||||
private boolean requestHeaders;
|
||||
private boolean requestBody;
|
||||
private boolean responseHeaders;
|
||||
private boolean responseBody;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
public boolean isRequestHeaders() {
|
||||
return requestHeaders;
|
||||
}
|
||||
public void setRequestHeaders(boolean requestHeaders) {
|
||||
this.requestHeaders = requestHeaders;
|
||||
}
|
||||
public boolean isRequestBody() {
|
||||
return requestBody;
|
||||
}
|
||||
public void setRequestBody(boolean requestBody) {
|
||||
this.requestBody = requestBody;
|
||||
}
|
||||
public boolean isResponseHeaders() {
|
||||
return responseHeaders;
|
||||
}
|
||||
public void setResponseHeaders(boolean responseHeaders) {
|
||||
this.responseHeaders = responseHeaders;
|
||||
}
|
||||
public boolean isResponseBody() {
|
||||
return responseBody;
|
||||
}
|
||||
public void setResponseBody(boolean responseBody) {
|
||||
this.responseBody = responseBody;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.global;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.gateway.filter.GlobalFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Configuration
|
||||
public class LoggingGlobalFiltersConfigurations {
|
||||
|
||||
final Logger logger = LoggerFactory.getLogger(LoggingGlobalFiltersConfigurations.class);
|
||||
|
||||
@Bean
|
||||
public GlobalFilter postGlobalFilter() {
|
||||
return (exchange, chain) -> {
|
||||
return chain.filter(exchange)
|
||||
.then(Mono.fromRunnable(() -> {
|
||||
logger.info("Global Post Filter executed");
|
||||
}));
|
||||
};
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.global;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
|
||||
import org.springframework.cloud.gateway.filter.GlobalFilter;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@Component
|
||||
public class LoggingGlobalPreFilter implements GlobalFilter {
|
||||
|
||||
final Logger logger = LoggerFactory.getLogger(LoggingGlobalPreFilter.class);
|
||||
|
||||
@Override
|
||||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
|
||||
logger.info("Global Pre Filter executed");
|
||||
return chain.filter(exchange);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.gatewayapp.routes;
|
||||
|
||||
import org.springframework.cloud.gateway.route.RouteLocator;
|
||||
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.factories.LoggingGatewayFilterFactory;
|
||||
import com.baeldung.springcloudgateway.customfilters.gatewayapp.filters.factories.LoggingGatewayFilterFactory.Config;
|
||||
|
||||
/**
|
||||
* Note: We want to keep this as an example of configuring a Route with a custom filter
|
||||
*
|
||||
* This corresponds with the properties configuration we have
|
||||
*/
|
||||
// @Configuration
|
||||
public class ServiceRouteConfiguration {
|
||||
|
||||
@Bean
|
||||
public RouteLocator routes(RouteLocatorBuilder builder, LoggingGatewayFilterFactory loggingFactory) {
|
||||
|
||||
return builder.routes()
|
||||
.route("service_route_java_config", r -> r.path("/service/**")
|
||||
.filters(f -> f.rewritePath("/service(?<segment>/?.*)", "$\\{segment}")
|
||||
.filter(loggingFactory.apply(new Config("My Custom Message", true, true))))
|
||||
.uri("http://localhost:8081"))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.secondservice;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:secondservice-application.properties")
|
||||
public class SecondServiceApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SecondServiceApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.secondservice.web;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
public class SecondServiceRestController {
|
||||
|
||||
@GetMapping("/resource/language")
|
||||
public Mono<ResponseEntity<String>> getResource() {
|
||||
return Mono.just(ResponseEntity.ok()
|
||||
.body("es"));
|
||||
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.service;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:service-application.properties")
|
||||
public class ServiceApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ServiceApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.springcloudgateway.customfilters.service.web;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
public class ServiceRestController {
|
||||
|
||||
@GetMapping("/resource")
|
||||
public Mono<ResponseEntity<String>> getResource() {
|
||||
return Mono.just(ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_LANGUAGE, Locale.ENGLISH.getLanguage())
|
||||
.body("Service Resource"));
|
||||
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.springcloudgateway.custompredicates;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
|
||||
@SpringBootApplication
|
||||
public class CustomPredicatesApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder(CustomPredicatesApplication.class)
|
||||
.profiles("customroutes")
|
||||
.run(args);
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.springcloudgateway.custompredicates.config;
|
||||
|
||||
import org.springframework.cloud.gateway.route.RouteLocator;
|
||||
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory;
|
||||
import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory.Config;
|
||||
import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService;
|
||||
|
||||
@Configuration
|
||||
public class CustomPredicatesConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
public GoldenCustomerRoutePredicateFactory goldenCustomer(GoldenCustomerService goldenCustomerService) {
|
||||
return new GoldenCustomerRoutePredicateFactory(goldenCustomerService);
|
||||
}
|
||||
|
||||
|
||||
//@Bean
|
||||
public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) {
|
||||
|
||||
return builder.routes()
|
||||
.route("dsl_golden_route", r ->
|
||||
r.predicate(gf.apply(new Config(true, "customerId")))
|
||||
.and()
|
||||
.path("/dsl_api/**")
|
||||
.filters(f -> f.stripPrefix(1))
|
||||
.uri("https://httpbin.org")
|
||||
)
|
||||
.route("dsl_common_route", r ->
|
||||
r.predicate(gf.apply(new Config(false, "customerId")))
|
||||
.and()
|
||||
.path("/dsl_api/**")
|
||||
.filters(f -> f.stripPrefix(1))
|
||||
.uri("https://httpbin.org")
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.springcloudgateway.custompredicates.factories;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
|
||||
import org.springframework.http.HttpCookie;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
public class GoldenCustomerRoutePredicateFactory extends AbstractRoutePredicateFactory<GoldenCustomerRoutePredicateFactory.Config> {
|
||||
|
||||
private final GoldenCustomerService goldenCustomerService;
|
||||
|
||||
public GoldenCustomerRoutePredicateFactory(GoldenCustomerService goldenCustomerService ) {
|
||||
super(Config.class);
|
||||
this.goldenCustomerService = goldenCustomerService;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<String> shortcutFieldOrder() {
|
||||
return Arrays.asList("isGolden","customerIdCookie");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Predicate<ServerWebExchange> apply(Config config) {
|
||||
|
||||
return (ServerWebExchange t) -> {
|
||||
List<HttpCookie> cookies = t.getRequest()
|
||||
.getCookies()
|
||||
.get(config.getCustomerIdCookie());
|
||||
|
||||
boolean isGolden;
|
||||
if ( cookies == null || cookies.isEmpty()) {
|
||||
isGolden = false;
|
||||
}
|
||||
else {
|
||||
String customerId = cookies.get(0).getValue();
|
||||
isGolden = goldenCustomerService.isGoldenCustomer(customerId);
|
||||
}
|
||||
|
||||
return config.isGolden()?isGolden:!isGolden;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@Validated
|
||||
public static class Config {
|
||||
boolean isGolden = true;
|
||||
|
||||
@NotEmpty
|
||||
String customerIdCookie = "customerId";
|
||||
|
||||
|
||||
public Config() {}
|
||||
|
||||
public Config( boolean isGolden, String customerIdCookie) {
|
||||
this.isGolden = isGolden;
|
||||
this.customerIdCookie = customerIdCookie;
|
||||
}
|
||||
|
||||
public boolean isGolden() {
|
||||
return isGolden;
|
||||
}
|
||||
|
||||
public void setGolden(boolean value) {
|
||||
this.isGolden = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the customerIdCookie
|
||||
*/
|
||||
public String getCustomerIdCookie() {
|
||||
return customerIdCookie;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param customerIdCookie the customerIdCookie to set
|
||||
*/
|
||||
public void setCustomerIdCookie(String customerIdCookie) {
|
||||
this.customerIdCookie = customerIdCookie;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.springcloudgateway.custompredicates.service;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class GoldenCustomerService {
|
||||
|
||||
public boolean isGoldenCustomer(String customerId) {
|
||||
|
||||
// TODO: Add some AI logic to check is this customer deserves a "golden" status ;^)
|
||||
if ( "baeldung".equalsIgnoreCase(customerId)) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.springcloudgateway.introduction;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:introduction-application.properties")
|
||||
public class IntroductionGatewayApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(IntroductionGatewayApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.springcloudgateway.oauth.backend;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.NimbusReactiveOpaqueTokenIntrospector;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
|
||||
|
||||
import com.baeldung.springcloudgateway.oauth.shared.KeycloakReactiveTokenInstrospector;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:quotes-application.properties")
|
||||
@EnableWebFluxSecurity
|
||||
public class QuotesApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(QuotesApplication.class);
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
public ReactiveOpaqueTokenIntrospector keycloakIntrospector(OAuth2ResourceServerProperties props) {
|
||||
|
||||
NimbusReactiveOpaqueTokenIntrospector delegate = new NimbusReactiveOpaqueTokenIntrospector(
|
||||
props.getOpaquetoken().getIntrospectionUri(),
|
||||
props.getOpaquetoken().getClientId(),
|
||||
props.getOpaquetoken().getClientSecret());
|
||||
|
||||
return new KeycloakReactiveTokenInstrospector(delegate);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.springcloudgateway.oauth.backend.domain;
|
||||
|
||||
|
||||
public class Quote {
|
||||
|
||||
private String symbol;
|
||||
private double price;
|
||||
|
||||
/**
|
||||
* @return the symbol
|
||||
*/
|
||||
public String getSymbol() {
|
||||
return symbol;
|
||||
}
|
||||
/**
|
||||
* @param symbol the symbol to set
|
||||
*/
|
||||
public void setSymbol(String symbol) {
|
||||
this.symbol = symbol;
|
||||
}
|
||||
/**
|
||||
* @return the price
|
||||
*/
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
/**
|
||||
* @param price the price to set
|
||||
*/
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.springcloudgateway.oauth.backend.web;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.springcloudgateway.oauth.backend.domain.Quote;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
@RestController
|
||||
public class QuoteApi {
|
||||
private static final GrantedAuthority GOLD_CUSTOMER = new SimpleGrantedAuthority("gold");
|
||||
|
||||
@GetMapping("/quotes/{symbol}")
|
||||
public Mono<Quote> getQuote(@PathVariable("symbol") String symbol, BearerTokenAuthentication auth ) {
|
||||
|
||||
Quote q = new Quote();
|
||||
q.setSymbol(symbol);
|
||||
|
||||
if ( auth.getAuthorities().contains(GOLD_CUSTOMER)) {
|
||||
q.setPrice(10.0);
|
||||
}
|
||||
else {
|
||||
q.setPrice(12.0);
|
||||
}
|
||||
return Mono.just(q);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.springcloudgateway.oauth.server;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableWebFluxSecurity
|
||||
public class ResourceServerGatewayApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ResourceServerGatewayApplication.class,args);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.springcloudgateway.oauth.shared;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* Custom ReactiveTokenIntrospector to map realm roles into Spring GrantedAuthorities
|
||||
*
|
||||
*/
|
||||
public class KeycloakReactiveTokenInstrospector implements ReactiveOpaqueTokenIntrospector {
|
||||
|
||||
private final ReactiveOpaqueTokenIntrospector delegate;
|
||||
|
||||
public KeycloakReactiveTokenInstrospector(ReactiveOpaqueTokenIntrospector delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
|
||||
|
||||
return delegate.introspect(token)
|
||||
.map( this::mapPrincipal);
|
||||
}
|
||||
|
||||
protected OAuth2AuthenticatedPrincipal mapPrincipal(OAuth2AuthenticatedPrincipal principal) {
|
||||
|
||||
return new DefaultOAuth2AuthenticatedPrincipal(
|
||||
principal.getName(),
|
||||
principal.getAttributes(),
|
||||
extractAuthorities(principal));
|
||||
}
|
||||
|
||||
protected Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
|
||||
|
||||
//
|
||||
Map<String,List<String>> realm_access = principal.getAttribute("realm_access");
|
||||
List<String> roles = realm_access.getOrDefault("roles", Collections.emptyList());
|
||||
List<GrantedAuthority> rolesAuthorities = roles.stream()
|
||||
.map(SimpleGrantedAuthority::new)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Set<GrantedAuthority> allAuthorities = new HashSet<>();
|
||||
allAuthorities.addAll(principal.getAuthorities());
|
||||
allAuthorities.addAll(rolesAuthorities);
|
||||
|
||||
return allAuthorities;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user