org.springframework.security.oauth2.client.registration.ClientRegistration Java Examples

The following examples show how to use org.springframework.security.oauth2.client.registration.ClientRegistration. 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 File: SecurityConfiguration.java    From OAuth-2.0-Cookbook with MIT License 8 votes vote down vote up
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
    ClientRegistration registration = new ClientRegistration.Builder(properties.getClientId())
        .authorizationUri(properties.getAuthorizationUri())
        .clientSecret(properties.getClientSecret())
        .tokenUri(properties.getTokenUri())
        .redirectUri(properties.getRedirectUri())
        .scope(properties.getScopes().split(","))
        .clientName(properties.getClientName())
        .clientAlias(properties.getClientAlias())
        .jwkSetUri(properties.getJwkSetUri())
        .authorizationGrantType(properties.getAuthorizedGrantType())
        .userInfoUri(properties.getUserInfoUri())
        .build();

    return new InMemoryClientRegistrationRepository(Arrays.asList(registration));
}
 
Example #2
Source File: JwtBearerOAuth2AuthorizedClientProvider.java    From oauth2-protocol-patterns with Apache License 2.0 8 votes vote down vote up
/**
 * Attempt to authorize the {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided {@code context}.
 * Returns {@code null} if authorization is not supported,
 * e.g. the client's {@link ClientRegistration#getAuthorizationGrantType() authorization grant type}
 * is not {@link JwtBearerGrantRequest#JWT_BEARER_GRANT_TYPE jwt-bearer}.
 *
 * @param context the context that holds authorization-specific state for the client
 * @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not supported
 */
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
	Assert.notNull(context, "context cannot be null");

	ClientRegistration clientRegistration = context.getClientRegistration();
	if (!JwtBearerGrantRequest.JWT_BEARER_GRANT_TYPE.equals(clientRegistration.getAuthorizationGrantType())) {
		return null;
	}

	Jwt jwt = context.getAttribute(JWT_ATTRIBUTE_NAME);
	if (jwt == null) {
		return null;
	}

	OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
	if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
		// If client is already authorized but access token is NOT expired than no need for re-authorization
		return null;
	}

	JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwt);
	OAuth2AccessTokenResponse tokenResponse =
			this.accessTokenResponseClient.getTokenResponse(jwtBearerGrantRequest);

	return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken());
}
 
Example #3
Source File: GitLabOAuth2ProviderTest.java    From gaia with Mozilla Public License 2.0 7 votes vote down vote up
@Test
void getOAuth2User_shouldReturnANewOAuthUser() {
    // given
    var attributes = new HashMap<String, Object>();
    var user = mock(DefaultOAuth2User.class);
    var client = mock(OAuth2AuthorizedClient.class);
    var registration = ClientRegistration
            .withRegistrationId("test_registration_id")
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .clientId("test_client_id")
            .redirectUriTemplate("test_uri_template")
            .authorizationUri("test_authorization_uri")
            .tokenUri("test_token_uri")
            .build();
    var accessToken = mock(OAuth2AccessToken.class);

    // when
    when(user.getAttributes()).thenReturn(attributes);
    when(client.getClientRegistration()).thenReturn(registration);
    when(client.getAccessToken()).thenReturn(accessToken);
    when(accessToken.getTokenValue()).thenReturn("test_token");
    var result = gitLabOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example #4
Source File: TestSecurityConfiguration.java    From java-microservices-examples with Apache License 2.0 7 votes vote down vote up
private ClientRegistration.Builder clientRegistration() {
    Map<String, Object> metadata = new HashMap<>();
    metadata.put("end_session_endpoint", "https://jhipster.org/logout");

    return ClientRegistration.withRegistrationId("oidc")
        .redirectUriTemplate("{baseUrl}/{action}/oauth2/code/{registrationId}")
        .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
        .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
        .scope("read:user")
        .authorizationUri("https://jhipster.org/login/oauth/authorize")
        .tokenUri("https://jhipster.org/login/oauth/access_token")
        .jwkSetUri("https://jhipster.org/oauth/jwk")
        .userInfoUri("https://api.jhipster.org/user")
        .providerConfigurationMetadata(metadata)
        .userNameAttributeName("id")
        .clientName("Client Name")
        .clientId("client-id")
        .clientSecret("client-secret");
}
 
Example #5
Source File: CustomRequestSecurityConfig.java    From tutorials with MIT License 7 votes vote down vote up
private ClientRegistration getRegistration(String client) {
    String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");

    if (clientId == null) {
        return null;
    }

    String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
    if (client.equals("google")) {
        return CommonOAuth2Provider.GOOGLE.getBuilder(client)
            .clientId(clientId)
            .clientSecret(clientSecret)
            .build();
    }
    if (client.equals("facebook")) {
        return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
            .clientId(clientId)
            .clientSecret(clientSecret)
            .build();
    }
    return null;
}
 
Example #6
Source File: EurekaClientOAuth2AutoConfiguration.java    From spring-cloud-services-starters with Apache License 2.0 7 votes vote down vote up
@Bean
@ConditionalOnMissingBean(DiscoveryClientOptionalArgs.class)
public DiscoveryClientOptionalArgs discoveryClientOptionalArgs(
		EurekaClientOAuth2Properties eurekaClientOAuth2Properties) {
	List<ClientFilter> filters = new ArrayList<>();
	ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("eureka-client")
			.clientId(eurekaClientOAuth2Properties.getClientId())
			.clientSecret(eurekaClientOAuth2Properties.getClientSecret())
			.tokenUri(eurekaClientOAuth2Properties.getAccessTokenUri())
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).build();
	filters.add(new EurekaOAuth2ClientFilterAdapter(clientRegistration));

	DiscoveryClientOptionalArgs args = new DiscoveryClientOptionalArgs();
	args.setAdditionalFilters(filters);

	return args;
}
 
Example #7
Source File: ConfigClientOAuth2BootstrapConfigurationTest.java    From spring-cloud-services-starters with Apache License 2.0 6 votes vote down vote up
@Test
public void configServicePropertySourceLocatorHasOAuth2AuthorizedClientHttpRequestInterceptor() throws Exception {
	this.contextRunner.withPropertyValues("spring.cloud.config.client.oauth2.client-id=" + CLIENT_ID,
			"spring.cloud.config.client.oauth2.client-secret=" + CLIENT_SECRET,
			"spring.cloud.config.client.oauth2.access-token-uri=" + TOKEN_URI).run(context -> {
				assertThat(context).hasSingleBean(ConfigServicePropertySourceLocator.class);
				ConfigServicePropertySourceLocator locator = context
						.getBean(ConfigServicePropertySourceLocator.class);
				RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(locator, "restTemplate");
				assertThat(restTemplate).isNotNull();
				assertThat(restTemplate.getInterceptors()).hasSize(1);
				assertThat(restTemplate.getInterceptors().get(0))
						.isInstanceOf(OAuth2AuthorizedClientHttpRequestInterceptor.class);
				OAuth2AuthorizedClientHttpRequestInterceptor interceptor = (OAuth2AuthorizedClientHttpRequestInterceptor) restTemplate
						.getInterceptors().get(0);
				ClientRegistration clientRegistration = interceptor.clientRegistration;
				assertThat(clientRegistration.getClientId()).isEqualTo(CLIENT_ID);
				assertThat(clientRegistration.getClientSecret()).isEqualTo(CLIENT_SECRET);
				assertThat(clientRegistration.getProviderDetails().getTokenUri()).isEqualTo(TOKEN_URI);
				assertThat(clientRegistration.getAuthorizationGrantType())
						.isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS);
			});
}
 
Example #8
Source File: SecurityConfiguration.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private ClientRegistration createMicrosoftRegistration() {
    ClientRegistration registration = new ClientRegistration.Builder(microsoft.getClientId())
        .authorizationUri(microsoft.getAuthorizationUri())
        .clientSecret(microsoft.getClientSecret())
        .tokenUri(microsoft.getTokenUri())
        .redirectUri(microsoft.getRedirectUri())
        .scope(microsoft.getScopes().split(","))
        .clientName(microsoft.getClientName())
        .clientAlias(microsoft.getClientAlias())
        .jwkSetUri(microsoft.getJwkSetUri())
        .authorizationGrantType(microsoft.getAuthorizedGrantType())
        .userInfoUri(microsoft.getUserInfoUri())
        .clientAuthenticationMethod(ClientAuthenticationMethod.POST)
        .build();


    return registration;
}
 
Example #9
Source File: DataFlowClientAutoConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
private ClientHttpRequestInterceptor clientCredentialsTokenResolvingInterceptor(
		ClientRegistration clientRegistration, ClientRegistrationRepository clientRegistrationRepository,
		String clientId) {
	Authentication principal = createAuthentication(clientId);
	OAuth2AuthorizedClientService authorizedClientService = new InMemoryOAuth2AuthorizedClientService(
			clientRegistrationRepository);
	AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
			clientRegistrationRepository, authorizedClientService);
	OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
			.clientCredentials().build();
	authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

	OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
			.withClientRegistrationId(DEFAULT_REGISTRATION_ID).principal(principal).build();

	return (request, body, execution) -> {
		OAuth2AuthorizedClient authorizedClient = authorizedClientManager.authorize(authorizeRequest);
		request.getHeaders().setBearerAuth(authorizedClient.getAccessToken().getTokenValue());
		return execution.execute(request, body);
	};
}
 
Example #10
Source File: SecurityConfiguration.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
    ClientRegistration registration = new ClientRegistration.Builder(properties.getClientId())
            .authorizationUri(properties.getAuthorizationUri())
            .clientSecret(properties.getClientSecret())
            .tokenUri(properties.getTokenUri())
            .redirectUri(properties.getRedirectUri())
            .scope(properties.getScopes().split(","))
            .clientName(properties.getClientName())
            .clientAlias(properties.getClientAlias())
            .authorizationGrantType(properties.getAuthorizedGrantType())
            .userInfoUri(properties.getUserInfoUri())
            .clientAuthenticationMethod(new ClientAuthenticationMethod("get"))
            .build();

    return new InMemoryClientRegistrationRepository(Arrays.asList(registration));
}
 
Example #11
Source File: SecurityConfig.java    From tutorials with MIT License 6 votes vote down vote up
private ClientRegistration getRegistration(String client) {
    String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");

    if (clientId == null) {
        return null;
    }

    String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
    if (client.equals("google")) {
        return CommonOAuth2Provider.GOOGLE.getBuilder(client)
            .clientId(clientId)
            .clientSecret(clientSecret)
            .build();
    }
    if (client.equals("facebook")) {
        return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
            .clientId(clientId)
            .clientSecret(clientSecret)
            .build();
    }
    return null;
}
 
Example #12
Source File: FacebookAuthorizationGrantTokenExchanger.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private HTTPRequest createTokenRequest(ClientRegistration clientRegistration,
       AuthorizationGrant authorizationCodeGrant, URI tokenUri,
       ClientAuthentication clientAuthentication) throws MalformedURLException {

    HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.GET, tokenUri.toURL());
    httpRequest.setContentType(CommonContentTypes.APPLICATION_URLENCODED);
    clientAuthentication.applyTo(httpRequest);
    Map<String,String> params = httpRequest.getQueryParameters();
    params.putAll(authorizationCodeGrant.toParameters());
    if (clientRegistration.getScope() != null && !clientRegistration.getScope().isEmpty()) {
        params.put("scope", clientRegistration.getScope().stream().reduce((a, b) -> a + " " + b).get());
    }
    if (clientRegistration.getClientId() != null) {
        params.put("client_id", clientRegistration.getClientId());
    }
    httpRequest.setQuery(URLUtils.serializeParameters(params));
    httpRequest.setAccept(MediaType.APPLICATION_JSON_VALUE);
    httpRequest.setConnectTimeout(30000);
    httpRequest.setReadTimeout(30000);
    return httpRequest;
}
 
Example #13
Source File: DemoApplicationTests.java    From keycloak-springsecurity5-sample with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void requestAuthorizeClientWhenInvalidClientThenStatusBadRequest() throws Exception {
	HtmlPage page = this.webClient.getPage("/");

	ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");

	HtmlAnchor clientAnchorElement = this.getClientAnchorElement(page, clientRegistration);
	assertThat(clientAnchorElement).isNotNull();
	clientAnchorElement.setAttribute("href", clientAnchorElement.getHrefAttribute() + "-invalid");

	WebResponse response = null;
	try {
		clientAnchorElement.click();
	} catch (FailingHttpStatusCodeException ex) {
		response = ex.getResponse();
	}

	assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
}
 
Example #14
Source File: VaultTokenRenewalAutoConfiguration.java    From spring-cloud-services-starters with Apache License 2.0 6 votes vote down vote up
@Bean
public VaultTokenRefresher vaultTokenRefresher(ConfigClientProperties configClientProperties,
		ConfigClientOAuth2Properties configClientOAuth2Properties,
		@Qualifier("vaultTokenRenewal") RestTemplate restTemplate,
		@Value("${spring.cloud.config.token}") String vaultToken,
		// Default to a 300 second (5 minute) TTL
		@Value("${vault.token.ttl:300000}") long renewTTL) {
	ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("config-client")
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
			.clientId(configClientOAuth2Properties.getClientId())
			.clientSecret(configClientOAuth2Properties.getClientSecret())
			.tokenUri(configClientOAuth2Properties.getAccessTokenUri()).build();
	restTemplate.getInterceptors().add(new OAuth2AuthorizedClientHttpRequestInterceptor(clientRegistration));
	String obscuredToken = vaultToken.substring(0, 4) + "[*]" + vaultToken.substring(vaultToken.length() - 4);
	String refreshUri = configClientProperties.getUri()[0] + "/vault/v1/auth/token/renew-self";
	// convert to seconds, since that's what Vault wants
	long renewTTLInMS = renewTTL / 1000;
	HttpEntity<Map<String, Long>> request = buildTokenRenewRequest(vaultToken, renewTTLInMS);
	return new VaultTokenRefresher(restTemplate, obscuredToken, renewTTL, refreshUri, request);
}
 
Example #15
Source File: TestSecurityConfiguration.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private ClientRegistration.Builder clientRegistration() {
    Map<String, Object> metadata = new HashMap<>();
    metadata.put("end_session_endpoint", "https://jhipster.org/logout");

    return ClientRegistration.withRegistrationId("oidc")
        .redirectUriTemplate("{baseUrl}/{action}/oauth2/code/{registrationId}")
        .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
        .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
        .scope("read:user")
        .authorizationUri("https://jhipster.org/login/oauth/authorize")
        .tokenUri("https://jhipster.org/login/oauth/access_token")
        .jwkSetUri("https://jhipster.org/oauth/jwk")
        .userInfoUri("https://api.jhipster.org/user")
        .providerConfigurationMetadata(metadata)
        .userNameAttributeName("id")
        .clientName("Client Name")
        .clientId("client-id")
        .clientSecret("client-secret");
}
 
Example #16
Source File: JwtBearerGrantRequestEntityConverter.java    From oauth2-protocol-patterns with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@link MultiValueMap} of the form parameters used for the Access Token Request body.
 *
 * @param jwtBearerGrantRequest the Jwt Bearer grant request
 * @return a {@link MultiValueMap} of the form parameters used for the Access Token Request body
 */
private MultiValueMap<String, String> buildFormParameters(JwtBearerGrantRequest jwtBearerGrantRequest) {
	ClientRegistration clientRegistration = jwtBearerGrantRequest.getClientRegistration();

	MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
	formParameters.add(OAuth2ParameterNames.GRANT_TYPE, jwtBearerGrantRequest.getGrantType().getValue());
	formParameters.add("assertion", jwtBearerGrantRequest.getJwt().getTokenValue());
	if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
		formParameters.add(OAuth2ParameterNames.SCOPE,
				StringUtils.collectionToDelimitedString(jwtBearerGrantRequest.getClientRegistration().getScopes(), " "));
	}
	if (ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod())) {
		formParameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
		formParameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
	}

	return formParameters;
}
 
Example #17
Source File: ConfigClientAutoConfigResourceTest.java    From spring-cloud-services-starters with Apache License 2.0 6 votes vote down vote up
@Test
public void plainTextConfigClientIsCreated() throws Exception {
	this.contextRunner.withPropertyValues("spring.cloud.config.client.oauth2.client-id=acme",
			"spring.cloud.config.client.oauth2.client-secret=acmesecret",
			"spring.cloud.config.client.oauth2.access-token-uri=acmetokenuri").run(context -> {
				assertThat(context).hasSingleBean(ConfigClientProperties.class);
				assertThat(context).hasSingleBean(OAuth2ConfigResourceClient.class);
				OAuth2ConfigResourceClient plainTextConfigClient = context
						.getBean(OAuth2ConfigResourceClient.class);
				RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(plainTextConfigClient,
						"restTemplate");
				assertThat(restTemplate).isNotNull();
				assertThat(restTemplate.getInterceptors()).hasSize(1);
				assertThat(restTemplate.getInterceptors().get(0))
						.isInstanceOf(OAuth2AuthorizedClientHttpRequestInterceptor.class);
				OAuth2AuthorizedClientHttpRequestInterceptor interceptor = (OAuth2AuthorizedClientHttpRequestInterceptor) restTemplate
						.getInterceptors().get(0);
				ClientRegistration clientRegistration = interceptor.clientRegistration;
				assertThat(clientRegistration.getClientId()).isEqualTo("acme");
				assertThat(clientRegistration.getClientSecret()).isEqualTo("acmesecret");
				assertThat(clientRegistration.getProviderDetails().getTokenUri()).isEqualTo("acmetokenuri");
				assertThat(clientRegistration.getAuthorizationGrantType())
						.isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS);
			});
}
 
Example #18
Source File: VaultTokenRenewalAutoConfigurationTest.java    From spring-cloud-services-starters with Apache License 2.0 6 votes vote down vote up
@Test
public void scheduledVaultTokenRefresh() {
	contextRunner.withPropertyValues("spring.cloud.config.token=footoken", "vault.token.renew.rate=1000",
			"spring.cloud.config.client.oauth2.clientId=" + CLIENT_ID,
			"spring.cloud.config.client.oauth2.clientSecret=" + CLIENT_SECRET,
			"spring.cloud.config.client.oauth2.accessTokenUri=" + TOKEN_URI).run(context -> {
				RestTemplate restTemplate = context.getBean("mockRestTemplate", RestTemplate.class);
				await().atMost(Duration.FIVE_SECONDS).untilAsserted(() -> {
					verify(restTemplate, atLeast(4)).postForObject(anyString(), any(HttpEntity.class), any());
					assertThat(restTemplate.getInterceptors()).hasSize(1);
					assertThat(restTemplate.getInterceptors().get(0))
							.isInstanceOf(OAuth2AuthorizedClientHttpRequestInterceptor.class);
					OAuth2AuthorizedClientHttpRequestInterceptor interceptor = (OAuth2AuthorizedClientHttpRequestInterceptor) restTemplate
							.getInterceptors().get(0);
					ClientRegistration clientRegistration = interceptor.clientRegistration;
					assertThat(clientRegistration.getClientId()).isEqualTo(CLIENT_ID);
					assertThat(clientRegistration.getClientSecret()).isEqualTo(CLIENT_SECRET);
					assertThat(clientRegistration.getProviderDetails().getTokenUri()).isEqualTo(TOKEN_URI);
					assertThat(clientRegistration.getAuthorizationGrantType())
							.isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS);
				});
			});
}
 
Example #19
Source File: UaaConfiguration.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@Bean
@LoadBalanced
public RestTemplate uaaRestTemplate() {
    ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID);
    if (null == clientRegistration) {
        throw new IllegalArgumentException("Invalid Client Registration with Id: " + CLIENT_REGISTRATION_ID);
    }

    return restTemplateBuilder
        .messageConverters(
            new FormHttpMessageConverter(),
            new OAuth2AccessTokenResponseHttpMessageConverter())
        .errorHandler(new OAuth2ErrorResponseErrorHandler())
        .basicAuthentication(clientRegistration.getClientId(), clientRegistration.getClientSecret())
        .build();
}
 
Example #20
Source File: SecurityConfig.java    From syncope with 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 #21
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
    RequestEntity requestEntity = RequestEntity
        .post(URI.create(clientRegistration.getProviderDetails().getTokenUri()))
        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
        .body(formParameters);

    try {
        ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
        return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to get access token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
 
Example #22
Source File: TestSecurityConfiguration.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
private ClientRegistration.Builder clientRegistration() {
    Map<String, Object> metadata = new HashMap<>();
    metadata.put("end_session_endpoint", "https://jhipster.org/logout");

    return ClientRegistration.withRegistrationId("oidc")
        .redirectUriTemplate("{baseUrl}/{action}/oauth2/code/{registrationId}")
        .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
        .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
        .scope("read:user")
        .authorizationUri("https://jhipster.org/login/oauth/authorize")
        .tokenUri("https://jhipster.org/login/oauth/access_token")
        .jwkSetUri("https://jhipster.org/oauth/jwk")
        .userInfoUri("https://api.jhipster.org/user")
        .providerConfigurationMetadata(metadata)
        .userNameAttributeName("id")
        .clientName("Client Name")
        .clientId("client-id")
        .clientSecret("client-secret");
}
 
Example #23
Source File: TestSecurityConfiguration.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
private ClientRegistration.Builder clientRegistration() {
    Map<String, Object> metadata = new HashMap<>();
    metadata.put("end_session_endpoint", "https://jhipster.org/logout");

    return ClientRegistration.withRegistrationId("oidc")
        .redirectUriTemplate("{baseUrl}/{action}/oauth2/code/{registrationId}")
        .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
        .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
        .scope("read:user")
        .authorizationUri("https://jhipster.org/login/oauth/authorize")
        .tokenUri("https://jhipster.org/login/oauth/access_token")
        .jwkSetUri("https://jhipster.org/oauth/jwk")
        .userInfoUri("https://api.jhipster.org/user")
        .providerConfigurationMetadata(metadata)
        .userNameAttributeName("id")
        .clientName("Client Name")
        .clientId("client-id")
        .clientSecret("client-secret");
}
 
Example #24
Source File: UaaAuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private Optional<OAuth2AuthorizedClient> refreshAuthorizedClient(Authentication authentication) {
    ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID);
    if (clientRegistration == null) {
        throw new IllegalArgumentException("Invalid Client Registration with Id: " + CLIENT_REGISTRATION_ID);
    }

    OAuth2AccessToken accessToken = retrieveNewAccessToken(clientRegistration);
    if (accessToken == null) {
        log.info("Unable to get access token for user");
        return Optional.empty();
    }
    OAuth2AuthorizedClient updatedAuthorizedClient = new OAuth2AuthorizedClient(
        clientRegistration,
        authentication.getName(),
        accessToken
    );
    clientRegistrationService.saveAuthorizedClient(updatedAuthorizedClient, authentication);
    return Optional.of(updatedAuthorizedClient);
}
 
Example #25
Source File: DataServiceClientRegistrationRepository.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ClientRegistration toClientRegistration(OidcClient oidcClient) {
  return ClientRegistration.withRegistrationId(oidcClient.getRegistrationId())
      .authorizationGrantType(toAuthorizationGrantType(oidcClient))
      .authorizationUri(oidcClient.getAuthorizationUri())
      .clientAuthenticationMethod(toClientAuthenticationMethod(oidcClient))
      .clientId(oidcClient.getClientId())
      .clientName(oidcClient.getClientName())
      .clientSecret(oidcClient.getClientSecret())
      .jwkSetUri(oidcClient.getJwkSetUri())
      .redirectUriTemplate(DEFAULT_REDIRECT_URI_TEMPLATE)
      .scope(oidcClient.getScopes())
      .tokenUri(oidcClient.getTokenUri())
      .userInfoUri(oidcClient.getUserInfoUri())
      .userNameAttributeName(oidcClient.getUsernameAttributeName())
      .build();
}
 
Example #26
Source File: GitHubOAuth2ProviderTest.java    From gaia with Mozilla Public License 2.0 5 votes vote down vote up
@Test
void getOAuth2User_shouldReturnANewOAuthUser() {
    // given
    var attributes = new HashMap<String, Object>();
    var user = mock(DefaultOAuth2User.class);
    var client = mock(OAuth2AuthorizedClient.class);
    var registration = ClientRegistration
            .withRegistrationId("test_registration_id")
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .clientId("test_client_id")
            .redirectUriTemplate("test_uri_template")
            .authorizationUri("test_authorization_uri")
            .tokenUri("test_token_uri")
            .build();
    var accessToken = mock(OAuth2AccessToken.class);

    // when
    when(user.getAttributes()).thenReturn(attributes);
    when(client.getClientRegistration()).thenReturn(registration);
    when(client.getAccessToken()).thenReturn(accessToken);
    when(accessToken.getTokenValue()).thenReturn("test_token");
    var result = gitHubOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example #27
Source File: UaaTestSecurityConfiguration.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
private ClientRegistration.Builder clientRegistration() {
    return ClientRegistration.withRegistrationId(CLIENT_REGISTRATION_ID)
        .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
        .tokenUri("https://uaa/oauth/token")
        .clientName("Client Name")
        .clientId("client-id")
        .clientSecret("client-secret");
}
 
Example #28
Source File: SecurityConfiguration.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
@Conditional(ClientsConfiguredCondition.class)
public ReactiveClientRegistrationRepository clientRegistrationRepository(OAuth2ClientProperties properties) {
	List<ClientRegistration> registrations = new ArrayList<>(
			OAuth2ClientPropertiesRegistrationAdapter
					.getClientRegistrations(properties).values());
	return new InMemoryReactiveClientRegistrationRepository(registrations);
}
 
Example #29
Source File: CredHubRestTemplateFactory.java    From spring-credhub with Apache License 2.0 5 votes vote down vote up
private static ClientRegistration getClientRegistration(ClientRegistrationRepository clientRegistrationRepository,
		String clientId) {
	ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(clientId);

	if (clientRegistration == null) {
		throw new IllegalStateException("The CredHub OAuth2 client registration ID '" + clientId
				+ "' is not a valid Spring Security OAuth2 client registration");
	}

	return clientRegistration;
}
 
Example #30
Source File: ResettableOAuth2AuthorizedClientService.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Copy of {@link InMemoryOAuth2AuthorizedClientService#loadAuthorizedClient(String, String)} */
@SuppressWarnings("unchecked")
@Override
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(
    String clientRegistrationId, String principalName) {
  Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
  Assert.hasText(principalName, "principalName cannot be empty");
  ClientRegistration registration =
      this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
  if (registration == null) {
    return null;
  }
  return (T) this.authorizedClients.get(this.getIdentifier(registration, principalName));
}