Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions spring-security-modules/spring-security-oidc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
<description>Spring OpenID Connect sample project</description>

<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<relativePath>../../parent-boot-3</relativePath>
<version>0.0.1-SNAPSHOT</version>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.11</version>
<relativePath/>
</parent>

<dependencies>
Expand All @@ -28,6 +28,15 @@
<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-authorization-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<properties>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.baeldung.tokenexchange.authserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AuthServerApplication {

public static void main(String[] args) {
SpringApplication application = new SpringApplication(AuthServerApplication.class);
application.setAdditionalProfiles("authserver");
application.run(args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.baeldung.tokenexchange.client;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;

@RestController
@RequestMapping("/")
public class ClientApi {
private static final String TARGET_RESOURCE_SERVER_URL = "http://localhost:8081/user/message";
private final RestClient restClient;

public ClientApi(RestClient restClient) {
this.restClient = restClient;
}

@GetMapping
public String index(@AuthenticationPrincipal OidcUser user) {
return "<html><body><title>Hello</title><p>Hello '" +
user.getSubject() + " (" + user.getAuthorizedParty() + ")" +
"' from the Token Exchange Client!</p></br><p>" +
"Use the <a href=\"/client/api/hello\">/api/hello</a> endpoint to access the resource server.</p></body></html>";
}

@GetMapping("/api/hello")
public String hello(@RegisteredOAuth2AuthorizedClient(registrationId = "messaging-client-oidc") OAuth2AuthorizedClient oauth2AuthorizedClient) {
RestClient.ResponseSpec responseSpec = restClient.get().uri(TARGET_RESOURCE_SERVER_URL)
.headers(headers -> headers.setBearerAuth(oauth2AuthorizedClient.getAccessToken().getTokenValue()))
.retrieve();

String messageFromResourceServer = responseSpec.toEntity(String.class).getBody();
return "<html><body><title>Token Exchange</title><p>Token Exchange Client!</p></br><p>" +
"The resource server: <strong>" + messageFromResourceServer + "</strong></p></body></html>";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.baeldung.tokenexchange.client;

import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.config.http.SessionCreationPolicy.NEVER;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.client.RestClient;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> {authorize
.requestMatchers("/login/**","/error/**").permitAll()
.anyRequest().authenticated();
})
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session ->
session.sessionCreationPolicy(NEVER))
.oauth2Login(withDefaults())
.oauth2Client(withDefaults());
return http.build();
}

@Bean
public RestClient restClient() {
return RestClient.builder()
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.baeldung.tokenexchange.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.baeldung.tokenexchange.authserver.AuthServerApplication;

@SpringBootApplication
public class TokenExchangeClientApplication {

public static void main(String[] args) {
SpringApplication application = new SpringApplication(TokenExchangeClientApplication.class);
application.setAdditionalProfiles("client");
application.run(args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.baeldung.tokenexchange.messageservice;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageController {

@GetMapping("/message")
public String getUser(){
return "message";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.baeldung.tokenexchange.messageservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MessageServiceApplication {

public static void main(String[] args) {
SpringApplication application = new SpringApplication(MessageServiceApplication.class);
application.setAdditionalProfiles("messageservice");
application.run(args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.baeldung.tokenexchange.messageservice;

import static org.springframework.security.config.Customizer.withDefaults;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated())
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(resource -> resource.jwt(withDefaults()));
return http.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.baeldung.tokenexchange.userservice;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.client.RestClient;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated())
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(resource -> resource.jwt(Customizer.withDefaults()))
.oauth2Client(Customizer.withDefaults());
return http.build();
}

@Bean
public RestClient restClient() {
return RestClient.builder()
.build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.baeldung.tokenexchange.userservice;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.TokenExchangeOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.RestClientTokenExchangeTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.TokenExchangeGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;

@Configuration
public class TokenExchangeConfig {

@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {

TokenExchangeOAuth2AuthorizedClientProvider tokenExchangeAuthorizedClientProvider =
new TokenExchangeOAuth2AuthorizedClientProvider();

OAuth2AuthorizedClientProvider authorizedClientProvider =
OAuth2AuthorizedClientProviderBuilder.builder()
.provider(tokenExchangeAuthorizedClientProvider)
.build();

DefaultOAuth2AuthorizedClientManager authorizedClientManager =
new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

return authorizedClientManager;
}

@Bean
public OAuth2AccessTokenResponseClient<TokenExchangeGrantRequest> accessTokenResponseClient() {
return new RestClientTokenExchangeTokenResponseClient();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.baeldung.tokenexchange.userservice;

import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;

@RestController
public class UserController {
private static final String TARGET_RESOURCE_SERVER_URL = "http://localhost:8082/message";
private final OAuth2AuthorizedClientManager authorizedClientManager;
private final RestClient restClient;

public UserController(OAuth2AuthorizedClientManager authorizedClientManager, RestClient restClient) {
this.authorizedClientManager = authorizedClientManager;
this.restClient = restClient;
}

@GetMapping("/user/message")
public String message(JwtAuthenticationToken jwtAuthentication) {

OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("my-token-exchange-client")
.principal(jwtAuthentication)
.build();

OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);

assert authorizedClient != null;

OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
if (accessToken == null) {
return "token exchange resource server";
}

RestClient.ResponseSpec responseSpec = restClient.get().uri(TARGET_RESOURCE_SERVER_URL)
.headers(headers -> headers.setBearerAuth(accessToken.getTokenValue()))
.retrieve();
ResponseEntity<String> responseEntity = responseSpec.toEntity(String.class);
return responseEntity.getBody();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.baeldung.tokenexchange.userservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UserServiceApplication {

public static void main(String[] args) {
SpringApplication application = new SpringApplication(UserServiceApplication.class);
application.setAdditionalProfiles("userservice");
application.run(args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
server:
port: 9001

logging:
level:
org.springframework.security: trace

spring:
security:
user:
name: baeldung
password: password
oauth2:
authorizationserver:
client:
oidc-client:
registration:
client-id: "user-service"
client-secret: "{noop}secret"
client-authentication-methods:
- "client_secret_basic"
- "none"
authorization-grant-types:
- "authorization_code"
- "client_credentials"
scopes:
- "openid"
- "user.read"
redirect-uris:
- "http://127.0.0.1:8081/login/oauth2/code/user-service"
- "http://localhost:8080/client/login/oauth2/code/messaging-client-oidc"
- "http://127.0.0.1:8080/client/login/oauth2/code/messaging-client-oidc"
token-exchange-client:
registration:
client-id: "token-exchange-client"
client-secret: "{noop}token"
client-authentication-methods:
- "client_secret_basic"
- "client_secret_post"
authorization-grant-types:
- "urn:ietf:params:oauth:grant-type:token-exchange"
scopes:
- "openid"
- "message.read"
Loading