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

The following examples show how to use org.springframework.security.oauth2.client.registration.ClientRegistration. 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: tutorials   Source File: CustomRequestSecurityConfig.java    License: 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 2
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 3
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 4
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
/**
 * 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 6
@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 7
Source Project: tutorials   Source File: SecurityConfig.java    License: 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 8
Source Project: OAuth-2.0-Cookbook   Source File: SecurityConfiguration.java    License: 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())
        .jwkSetUri(properties.getJwkSetUri())
        .authorizationGrantType(properties.getAuthorizedGrantType())
        .userInfoUri(properties.getUserInfoUri())
        .build();

    return new InMemoryClientRegistrationRepository(Arrays.asList(registration));
}
 
Example 9
Source Project: OAuth-2.0-Cookbook   Source File: SecurityConfiguration.java    License: 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 10
Source Project: OAuth-2.0-Cookbook   Source File: SecurityConfiguration.java    License: 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
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 12
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 13
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 14
Source Project: jhipster-registry   Source File: UaaConfiguration.java    License: 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 15
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
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 17
@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 18
@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 19
@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 20
@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 21
@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 22
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 23
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 24
Source Project: gaia   Source File: GitHubOAuth2ProviderTest.java    License: 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 25
Source Project: gaia   Source File: GitLabOAuth2ProviderTest.java    License: 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 = gitLabOAuth2Provider.getOAuth2User(user, client);

    // then
    assertThat(result).isNotNull()
            .hasFieldOrPropertyWithValue("provider", "test_registration_id")
            .hasFieldOrPropertyWithValue("token", "test_token")
            .hasFieldOrPropertyWithValue("attributes", attributes);
}
 
Example 26
private ClientRegistration getClientRegistration() {
    if (clientRegistration == null) {
        try {
            clientRegistration = getProvider().getClientRegistration();
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Client url is not correct.", e);
        }
    }
    return clientRegistration;
}
 
Example 27
@Override
public ClientRegistration getClientRegistration() throws URISyntaxException {
    URI keycloakUri = new URI(getUrl()).resolve("/auth/realms/" + getRealmId() + "/protocol/openid-connect");
    return ClientRegistration.withRegistrationId(getType().name())
            .clientId(getClientId())
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
            .scope("openid","profile", "email")
            .authorizationUri(keycloakUri + "/auth")
            .tokenUri(keycloakUri + "/token")
            .jwkSetUri(keycloakUri + "/certs")
            .userNameAttributeName(getUserNameAttribute())
            .build();
}
 
Example 28
private List<ClientRegistration> getClientRegistrations() {
	ResolvableType type = ResolvableType.forInstance(this.clientRegistrationRepository).as(Iterable.class);
	if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
		return StreamSupport.stream(((Iterable<ClientRegistration>) clientRegistrationRepository).spliterator(), false)
				.collect(Collectors.toList());
	}
	return Collections.emptyList();
}
 
Example 29
Source Project: tutorials   Source File: SecurityConfig.java    License: MIT License 5 votes vote down vote up
public ClientRegistrationRepository clientRegistrationRepository() {
    List<ClientRegistration> registrations = clients.stream()
        .map(c -> getRegistration(c))
        .filter(registration -> registration != null)
        .collect(Collectors.toList());

    return new InMemoryClientRegistrationRepository(registrations);
}
 
Example 30
/**
 * 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());
}