* [BAEL-4849] Article code

* [BAEL-4968] Article code

* [BAEL-4968] Article code

* [BAEL-4968] Article code

* [BAEL-4968] Remove extra comments

* WIP:Update to latest Boot

* WIP: Backend App

* WIP: resource server

* WIP: Change endpoint path

* WIP: Add Postman sample

* WIP: Add keycloak baeldung realm

* WIP: Change lombok scope

* WIP: Remove lombok dependency

* [BEAL-5260] README-OAuth
This commit is contained in:
psevestre 2022-01-23 00:32:51 -03:00 committed by GitHub
parent db396b39a9
commit 7dde535340
13 changed files with 2771 additions and 13 deletions

View File

@ -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
```

File diff suppressed because it is too large Load Diff

View File

@ -83,23 +83,99 @@
<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>
<properties>
<spring-cloud-dependencies.version>Hoxton.SR3</spring-cloud-dependencies.version>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
<!-- <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>
<junit-bom.version>5.5.2</junit-bom.version>
<oauth2-oidc-sdk.version>9.19</oauth2-oidc-sdk.version>
<!-- <junit-bom.version>5.5.2</junit-bom.version> -->
</properties>
<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>
</profiles>
</project>

View File

@ -1,6 +1,5 @@
package com.baeldung.springcloudgateway.custompredicates.config;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
@ -24,14 +23,20 @@ public class CustomPredicatesConfig {
public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) {
return builder.routes()
.route("dsl_golden_route", r -> r.path("/dsl_api/**")
.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")
.predicate(gf.apply(new Config(true, "customerId"))))
.route("dsl_common_route", r -> r.path("/dsl_api/**")
)
.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")
.predicate(gf.apply(new Config(false, "customerId"))))
)
.build();
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,26 @@
server:
port: 8087
spring:
cloud:
gateway:
redis:
enabled: false
routes:
- id: quotes
uri: http://localhost:8085
predicates:
- Path=/quotes/**
filters: - TokenRelay=
security:
oauth2:
client: provider: keycloak:
issuer-uri: http://localhost:8083/auth/realms/baeldung
registration: quotes-client:
provider: keycloak
client-id: quotes-client
client-secret: 0e082231-a70d-48e8-b8a5-fbfb743041b6
scope: - email
- profile
- roles

View File

@ -0,0 +1,19 @@
server:
port: 8086
spring:
security:
oauth2:
resourceserver:
opaquetoken:
introspection-uri: http://localhost:8083/auth/realms/baeldung/protocol/openid-connect/token/introspect
client-id: quotes-client
client-secret: 0e082231-a70d-48e8-b8a5-fbfb743041b6
cloud:
gateway:
redis:
enabled: false
routes:
- id: quotes
uri: http://localhost:8085
predicates:
- Path=/quotes/**

View File

@ -0,0 +1,12 @@
server.port=8085
# Disable gateway & redis as we don't need them in this application
spring.cloud.gateway.enabled=false
spring.cloud.gateway.redis.enabled=false
# Resource server settings
spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=http://localhost:8083/auth/realms/baeldung/protocol/openid-connect/token/introspect
spring.security.oauth2.resourceserver.opaquetoken.client-id=quotes-client
spring.security.oauth2.resourceserver.opaquetoken.client-secret=0e082231-a70d-48e8-b8a5-fbfb743041b6

View File

@ -0,0 +1,203 @@
{
"info": {
"_postman_id": "b3d00e23-c2cd-40ce-a90b-673efb25e5c0",
"name": "Baeldung - OAuth",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Token",
"event": [
{
"listen": "test",
"script": {
"exec": [
"var jsonData = pm.response.json();\r",
"pm.environment.set(\"access_token\", jsonData.access_token);\r",
"pm.environment.set(\"refresh_token\", jsonData.refresh_token);\r",
"pm.environment.set(\"backend_token\", \"Bearer \" + jsonData.access_token);"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "urlencoded",
"urlencoded": [
{
"key": "client_id",
"value": "{{client_id}}",
"type": "text"
},
{
"key": "client_secret",
"value": "{{client_secret}}",
"type": "text"
},
{
"key": "grant_type",
"value": "password",
"type": "text"
},
{
"key": "scope",
"value": "email roles profile",
"type": "text"
},
{
"key": "username",
"value": "maxwell.smart",
"type": "text"
},
{
"key": "password",
"value": "1234",
"type": "text"
}
]
},
"url": {
"raw": "{{keycloack_base}}/token",
"host": [
"{{keycloack_base}}"
],
"path": [
"token"
]
}
},
"response": []
},
{
"name": "Quote",
"protocolProfileBehavior": {
"disabledSystemHeaders": {
"accept": true
}
},
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{access_token}}",
"type": "string"
}
]
},
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "http://localhost:8085/quotes/:symbol",
"protocol": "http",
"host": [
"localhost"
],
"port": "8085",
"path": [
"quotes",
":symbol"
],
"variable": [
{
"key": "symbol",
"value": "IBM"
}
]
}
},
"response": []
},
{
"name": "Quote via Gateway",
"protocolProfileBehavior": {
"disabledSystemHeaders": {
"accept": true
}
},
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{access_token}}",
"type": "string"
}
]
},
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json",
"type": "text"
}
],
"url": {
"raw": "http://localhost:8086/quotes/:symbol",
"protocol": "http",
"host": [
"localhost"
],
"port": "8086",
"path": [
"quotes",
":symbol"
],
"variable": [
{
"key": "symbol",
"value": "IBM"
}
]
}
},
"response": []
}
],
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
""
]
}
}
],
"variable": [
{
"key": "keycloack_base",
"value": "http://localhost:8083/auth/realms/baeldung/protocol/openid-connect"
},
{
"key": "client_id",
"value": "quotes-client"
},
{
"key": "client_secret",
"value": "56be94c8-b20a-4374-899c-e39cb022d3f8"
}
]
}