Java Code Examples for org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository

The following examples show how to use org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-security-samples   Source File: SecurityConfig.java    License: MIT License 6 votes vote down vote up
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
		ReactiveClientRegistrationRepository clientRegistrationRepository) {
	// Authenticate through configured OpenID Provider
	http.oauth2Login();
	// Also logout at the OpenID Connect provider
	http.logout(logout -> logout.logoutSuccessHandler(new OidcClientInitiatedServerLogoutSuccessHandler(
			clientRegistrationRepository)));
	// Require authentication for all requests
	http.authorizeExchange().anyExchange().authenticated();
	// Allow showing /home within a frame
	http.headers().frameOptions().mode(Mode.SAMEORIGIN);
	// Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
	http.csrf().disable();
	return http.build();
}
 
Example 2
@Test
public void credHubTemplatesConfiguredWithOAuth2() {
	this.context.withPropertyValues("spring.credhub.url=https://localhost",
			"spring.credhub.oauth2.registration-id=credhub-client",

			"spring.security.oauth2.client.registration.credhub-client.provider=uaa",
			"spring.security.oauth2.client.registration.credhub-client.client-id=test-client",
			"spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret",
			"spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials",
			"spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token")
			.run((context) -> {
				assertThat(context).hasSingleBean(CredHubTemplate.class);
				assertThat(context).hasSingleBean(ClientRegistrationRepository.class);
				assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class);
				assertThat(context).doesNotHaveBean(OAuth2AuthorizedClientManager.class);
				CredHubTemplate credHubTemplate = context.getBean(CredHubTemplate.class);
				assertThat(credHubTemplate.isUsingOAuth2()).isTrue();

				assertThat(context).hasSingleBean(ReactiveCredHubTemplate.class);
				assertThat(context).hasSingleBean(ReactiveClientRegistrationRepository.class);
				assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class);
				assertThat(context).doesNotHaveBean(ReactiveOAuth2AuthorizedClientManager.class);
				ReactiveCredHubTemplate reactiveCredHubTemplate = context.getBean(ReactiveCredHubTemplate.class);
				assertThat(reactiveCredHubTemplate.isUsingOAuth2()).isTrue();
			});
}
 
Example 3
@Test
public void shouldConfigureBeanWithOAuthUsingCustomProvider() {
	this.contextRunner
			.withPropertyValues(REGISTRATION_PREFIX + ".client-id=ms-dashboard",
					REGISTRATION_PREFIX + ".client-secret=secret",
					REGISTRATION_PREFIX + ".provider=keycloak",
					REGISTRATION_PREFIX + ".authorization-grant-type=client_credentials",
					PROVIDER_PREFIX + ".keycloak.authorization-uri=http://authorization-uri.com",
					PROVIDER_PREFIX + ".keycloak.token-uri=http://token-uri.com",
					PROVIDER_PREFIX + ".keycloak.user-info-uri=userInfoUri",
					PROVIDER_PREFIX + ".keycloak.user-name-attribute-name=login")
			.run(context -> {
				assertThat(context.containsBean("machine-to-machine-web-client")).isTrue();
				assertThat(context.containsBean("ms-dashboard-m2m-oauth-filter")).isTrue();
				assertThat(context.getBeansOfType(ReactiveClientRegistrationRepository.class)).isNotEmpty();
			});
}
 
Example 4
Source Project: syncope   Source File: SecurityConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnProperty(name = AM_TYPE, havingValue = "OAUTH2")
public ReactiveClientRegistrationRepository oauth2ClientRegistrationRepository() {
    return new InMemoryReactiveClientRegistrationRepository(
            ClientRegistration.withRegistrationId("OAUTH2").
                    redirectUriTemplate("{baseUrl}/{action}/oauth2/code/{registrationId}").
                    tokenUri(env.getProperty("am.oauth2.tokenUri")).
                    authorizationUri(env.getProperty("am.oauth2.authorizationUri")).
                    userInfoUri(env.getProperty("am.oauth2.userInfoUri")).
                    userNameAttributeName(env.getProperty("am.oauth2.userNameAttributeName")).
                    clientId(env.getProperty("am.oauth2.client.id")).
                    clientSecret(env.getProperty("am.oauth2.client.secret")).
                    scope(env.getProperty("am.oauth2.scopes", String[].class)).
                    authorizationGrantType(new AuthorizationGrantType(env.getProperty("am.oauth2.grantType"))).
                    build());
}
 
Example 5
Source Project: spring-security-samples   Source File: SecurityConfig.java    License: MIT License 5 votes vote down vote up
@Bean
WebClient tokenAugmentingWebClient(final ReactiveClientRegistrationRepository clientRegistrationRepository,
								   final ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
	return WebClient.builder()
		.filter(new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository))
		.build();
}
 
Example 6
Source Project: spring-credhub   Source File: TestApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager reactiveClientManager(
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ReactiveOAuth2AuthorizedClientService authorizedClientService) {
	AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager clientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
			clientRegistrationRepository, authorizedClientService);
	clientManager.setAuthorizedClientProvider(new ClientCredentialsReactiveOAuth2AuthorizedClientProvider());
	return clientManager;
}
 
Example 7
@Bean
public AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager reactiveClientManager(
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ReactiveOAuth2AuthorizedClientService authorizedClientService) {
	AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager clientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
			clientRegistrationRepository, authorizedClientService);
	clientManager.setAuthorizedClientProvider(new ClientCredentialsReactiveOAuth2AuthorizedClientProvider());
	return clientManager;
}
 
Example 8
/**
 * Create a {@code ReactiveClientRegistrationRepository} bean for use with an
 * OAuth2-enabled {@code ReactiveCredHubTemplate}, in case
 * {@link ReactiveOAuth2ClientAutoConfiguration} doesn't configure one.
 * @return the {@code ReactiveClientRegistrationRepository}
 */
@Bean
@ConditionalOnMissingBean
@ConditionalOnClass(name = "org.springframework.web.reactive.function.client.WebClient")
public ReactiveClientRegistrationRepository credHubReactiveClientRegistrationRepository() {
	List<ClientRegistration> registrations = new ArrayList<>(
			OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(this.properties).values());
	return new InMemoryReactiveClientRegistrationRepository(registrations);
}
 
Example 9
/**
 * Create the {@link ReactiveCredHubTemplate} that the application will use to
 * interact with CredHub.
 * @param credHubProperties {@link CredHubProperties} for CredHub
 * @param clientOptions client connection options
 * @param clientRegistrationRepository a repository of OAuth2 client registrations
 * @param authorizedClientRepository a repository of OAuth2 authorized clients
 * @return the {@link CredHubTemplate} bean
 */
@Bean
@ConditionalOnMissingBean
ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties,
		ClientOptions clientOptions, ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {

	return new CredHubTemplateFactory().reactiveCredHubTemplate(credHubProperties, clientOptions,
			clientRegistrationRepository, authorizedClientRepository);
}
 
Example 10
@Test
public void credHubTemplatesConfiguredWithOAuth2AndCustomClientManager() {
	this.context.withPropertyValues("spring.credhub.url=https://localhost",
			"spring.credhub.oauth2.registration-id=credhub-client",

			"spring.security.oauth2.client.registration.credhub-client.provider=uaa",
			"spring.security.oauth2.client.registration.credhub-client.client-id=test-client",
			"spring.security.oauth2.client.registration.credhub-client.client-secret=test-secret",
			"spring.security.oauth2.client.registration.credhub-client.authorization-grant-type=client_credentials",
			"spring.security.oauth2.client.provider.uaa.token-uri=https://example.com/uaa/oauth/token")
			.withUserConfiguration(ClientManagerConfiguration.class).run((context) -> {
				assertThat(context).hasSingleBean(CredHubTemplate.class);
				assertThat(context).hasSingleBean(ClientRegistrationRepository.class);
				assertThat(context).hasSingleBean(OAuth2AuthorizedClientRepository.class);
				assertThat(context).hasSingleBean(AuthorizedClientServiceOAuth2AuthorizedClientManager.class);
				CredHubTemplate credHubTemplate = context.getBean(CredHubTemplate.class);
				assertThat(credHubTemplate.isUsingOAuth2()).isTrue();

				assertThat(context).hasSingleBean(ReactiveCredHubTemplate.class);
				assertThat(context).hasSingleBean(ReactiveClientRegistrationRepository.class);
				assertThat(context).hasSingleBean(ServerOAuth2AuthorizedClientRepository.class);
				assertThat(context)
						.hasSingleBean(AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.class);
				ReactiveCredHubTemplate reactiveCredHubTemplate = context.getBean(ReactiveCredHubTemplate.class);
				assertThat(reactiveCredHubTemplate.isUsingOAuth2()).isTrue();
			});
}
 
Example 11
@Bean
AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager reactiveClientManager(
		OAuth2ClientProperties properties) {
	List<ClientRegistration> registrations = new ArrayList<>(
			OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values());
	ReactiveClientRegistrationRepository clientRegistrationRepository = new InMemoryReactiveClientRegistrationRepository(
			registrations);
	ReactiveOAuth2AuthorizedClientService authorizedClientService = new InMemoryReactiveOAuth2AuthorizedClientService(
			clientRegistrationRepository);
	return new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(clientRegistrationRepository,
			authorizedClientService);
}
 
Example 12
Source Project: spring-credhub   Source File: ReactiveCredHubTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link ReactiveCredHubTemplate} using the provided base URI and
 * {@link ClientHttpRequestFactory}.
 * @param credHubProperties connection properties for the CredHub server
 * @param clientHttpConnector the {@link ClientHttpConnector} to use when creating new
 * connections
 * @param clientRegistrationRepository a repository of OAuth2 client registrations
 * @param authorizedClientRepository a repository of authorized OAuth2 clients
 */
public ReactiveCredHubTemplate(CredHubProperties credHubProperties, ClientHttpConnector clientHttpConnector,
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
	Assert.notNull(credHubProperties, "credHubProperties must not be null");
	Assert.notNull(clientHttpConnector, "clientHttpConnector must not be null");
	Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository must not be null");
	Assert.notNull(authorizedClientRepository, "authorizedClientRepository must not be null");

	this.webClient = CredHubWebClientFactory.createWebClient(credHubProperties, clientHttpConnector,
			clientRegistrationRepository, authorizedClientRepository);
	this.usingOAuth2 = true;
}
 
Example 13
Source Project: spring-credhub   Source File: CredHubWebClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link WebClient} configured for communication with a CredHub server.
 * @param properties the CredHub connection properties
 * @param clientHttpConnector the {@link ClientHttpConnector} to use when creating new
 * connections
 * @param clientRegistrationRepository a repository of OAuth2 client registrations
 * @param authorizedClientRepository a repository of OAuth2 authorized clients
 * @return a configured {@link WebClient}
 */
static WebClient createWebClient(CredHubProperties properties, ClientHttpConnector clientHttpConnector,
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
	ReactiveOAuth2AuthorizedClientProvider clientProvider = buildClientProvider(clientHttpConnector);

	DefaultReactiveOAuth2AuthorizedClientManager defaultClientManager = buildClientManager(
			clientRegistrationRepository, authorizedClientRepository, clientProvider);

	return createWebClient(properties, clientHttpConnector, defaultClientManager);
}
 
Example 14
Source Project: spring-credhub   Source File: CredHubWebClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static DefaultReactiveOAuth2AuthorizedClientManager buildClientManager(
		ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository,
		ReactiveOAuth2AuthorizedClientProvider clientProvider) {
	DefaultReactiveOAuth2AuthorizedClientManager clientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
			clientRegistrationRepository, authorizedClientRepository);
	clientManager.setAuthorizedClientProvider(clientProvider);
	return clientManager;
}
 
Example 15
@Bean
@ConditionalOnMissingBean
@Conditional(ClientsConfiguredCondition.class)
public ReactiveClientRegistrationRepository clientRegistrationRepository(OAuth2ClientProperties properties) {
	List<ClientRegistration> registrations = new ArrayList<>(
			OAuth2ClientPropertiesRegistrationAdapter
					.getClientRegistrations(properties).values());
	return new InMemoryReactiveClientRegistrationRepository(registrations);
}
 
Example 16
@Test
public void shouldNotConfigureAnyAuthFilter() {
	this.contextRunner.run(context -> {
		assertThat(context.containsBean("machine-to-machine-web-client")).isTrue();
		assertThat(context.containsBean("ms-dashboard-m2m-basic-filter")).isFalse();
		assertThat(context.containsBean("ms-dashboard-m2m-oauth-filter")).isFalse();
		assertThat(context.getBeansOfType(ReactiveClientRegistrationRepository.class)).isEmpty();
	});
}
 
Example 17
@Test
public void shouldConfigureBeanWithOAuthUsingGitHubAsProvider() {
	this.contextRunner
			.withPropertyValues(REGISTRATION_PREFIX + ".client-id=ms-dashboard",
					REGISTRATION_PREFIX + ".client-secret=secret",
					REGISTRATION_PREFIX + ".provider=github")
			.run(context -> {
				assertThat(context.containsBean("machine-to-machine-web-client")).isTrue();
				assertThat(context.containsBean("ms-dashboard-m2m-oauth-filter")).isTrue();
				assertThat(context.getBeansOfType(ReactiveClientRegistrationRepository.class)).isNotEmpty();
			});
}
 
Example 18
Source Project: syncope   Source File: OAuth2SecurityConfigUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void forLogin(
        final ServerHttpSecurity http,
        final AMType amType,
        final ApplicationContext ctx) {

    ReactiveClientRegistrationRepository clientRegistrationRepository =
            ctx.getBean(ReactiveClientRegistrationRepository.class);

    ReactiveOAuth2AuthorizedClientService authorizedClientService =
            new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository);
    ServerOAuth2AuthorizedClientRepository authorizedClientRepository =
            new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService);

    OAuth2AuthorizationRequestRedirectWebFilter authRequestRedirectFilter =
            new OAuth2AuthorizationRequestRedirectWebFilter(clientRegistrationRepository);

    AuthenticationWebFilter authenticationFilter =
            new OAuth2LoginAuthenticationWebFilter(authenticationManager(amType), authorizedClientRepository);
    authenticationFilter.setRequiresAuthenticationMatcher(
            new PathPatternParserServerWebExchangeMatcher("/login/oauth2/code/{registrationId}"));
    authenticationFilter.setServerAuthenticationConverter(
            new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(clientRegistrationRepository));
    authenticationFilter.setAuthenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler());
    authenticationFilter.setAuthenticationFailureHandler((exchange, ex) -> Mono.error(ex));
    authenticationFilter.setSecurityContextRepository(new WebSessionServerSecurityContextRepository());

    MediaTypeServerWebExchangeMatcher htmlMatcher = new MediaTypeServerWebExchangeMatcher(MediaType.TEXT_HTML);
    htmlMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
    ServerAuthenticationEntryPoint entrypoint =
            new RedirectServerAuthenticationEntryPoint("/oauth2/authorization/" + amType.name());
    http.exceptionHandling().authenticationEntryPoint(new DelegateEntry(htmlMatcher, entrypoint).getEntryPoint());

    http.addFilterAt(authRequestRedirectFilter, SecurityWebFiltersOrder.HTTP_BASIC);
    http.addFilterAt(authenticationFilter, SecurityWebFiltersOrder.AUTHENTICATION);
}
 
Example 19
Source Project: syncope   Source File: SecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnProperty(name = AM_TYPE, havingValue = "OIDC")
public ReactiveClientRegistrationRepository oidcClientRegistrationRepository() {
    return new InMemoryReactiveClientRegistrationRepository(
            ClientRegistrations.fromOidcIssuerLocation(env.getProperty("am.oidc.configuration")).
                    registrationId("OIDC").
                    clientId(env.getProperty("am.oidc.client.id")).
                    clientSecret(env.getProperty("am.oidc.client.secret")).
                    build());
}
 
Example 20
Source Project: tutorials   Source File: WebClientConfig.java    License: MIT License 5 votes vote down vote up
@Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
    oauth.setDefaultClientRegistrationId("bael");
    return WebClient.builder()
        .filter(oauth)
        .build();
}
 
Example 21
Source Project: tutorials   Source File: WebClientConfig.java    License: MIT License 5 votes vote down vote up
@Bean
@Primary
WebClient webClientForAuthorized(ReactiveClientRegistrationRepository clientRegistrations, ServerOAuth2AuthorizedClientRepository authorizedClients) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients);
    oauth.setDefaultOAuth2AuthorizedClient(true);
    return WebClient.builder()
        .filter(oauth)
        .build();
}
 
Example 22
Source Project: tutorials   Source File: WebClientConfig.java    License: MIT License 5 votes vote down vote up
@Bean
WebClient otherWebClient(ReactiveClientRegistrationRepository clientRegistrations, ServerOAuth2AuthorizedClientRepository authorizedClients) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients);
    return WebClient.builder()
        .filter(oauth)
        .build();
}
 
Example 23
Source Project: tutorials   Source File: WebClientConfig.java    License: MIT License 5 votes vote down vote up
@Bean
WebClient webClientForAuthorized(ReactiveClientRegistrationRepository clientRegistrations, ServerOAuth2AuthorizedClientRepository authorizedClients) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients);
    return WebClient.builder()
        .filter(oauth)
        .build();
}
 
Example 24
Source Project: tutorials   Source File: Spring5ReactiveOauthApplication.java    License: MIT License 5 votes vote down vote up
@Bean
public WebClient webClient(ReactiveClientRegistrationRepository clientRegistrationRepo, ServerOAuth2AuthorizedClientRepository authorizedClientRepo) {
    ServerOAuth2AuthorizedClientExchangeFilterFunction filter = new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepo, authorizedClientRepo);
    return WebClient.builder()
        .filter(filter)
        .build();
}
 
Example 25
Source Project: spring-credhub   Source File: CredHubTemplateFactory.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Create a {@link ReactiveCredHubTemplate} for interaction with a CredHub server
 * using OAuth2 for authentication.
 * @param credHubProperties connection properties
 * @param clientOptions connection options
 * @param clientRegistrationRepository a repository of OAuth2 client registrations
 * @param authorizedClientRepository a repository of OAuth2 client authorizations
 * @return a {@code ReactiveCredHubTemplate}
 */
public ReactiveCredHubOperations reactiveCredHubTemplate(CredHubProperties credHubProperties,
		ClientOptions clientOptions, ReactiveClientRegistrationRepository clientRegistrationRepository,
		ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
	return new ReactiveCredHubTemplate(credHubProperties, clientHttpConnector(clientOptions),
			clientRegistrationRepository, authorizedClientRepository);
}