org.springframework.security.oauth2.core.AuthorizationGrantType Java Examples

The following examples show how to use org.springframework.security.oauth2.core.AuthorizationGrantType. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #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: 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 #9
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 #10
Source File: AuthorizationHeaderUtil.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) {

        MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
        formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue());
        formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue());
        formParameters.add(OAuth2ParameterNames.CLIENT_ID, currentClient.getClientRegistration().getClientId());
        RequestEntity requestEntity = RequestEntity
            .post(URI.create(currentClient.getClientRegistration().getProviderDetails().getTokenUri()))
            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .body(formParameters);
        try {
            RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret());
            ResponseEntity<OAuthIdpTokenResponseDTO> responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class);
            return toOAuth2AccessTokenResponse(responseEntity.getBody());
        } catch (OAuth2AuthorizationException e) {
            log.error("Unable to refresh token", e);
            throw new OAuth2AuthenticationException(e.getError(), e);
        }
    }
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: DataFlowClientAutoConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Bean
public InMemoryClientRegistrationRepository clientRegistrationRepository(
	DataFlowClientProperties properties) {
	ClientRegistration clientRegistration = ClientRegistration
		.withRegistrationId(DEFAULT_REGISTRATION_ID)
		.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
		.tokenUri(properties.getAuthentication().getTokenUri())
		.clientId(properties.getAuthentication().getClientId())
		.clientSecret(properties.getAuthentication().getClientSecret())
		.scope(properties.getAuthentication().getScope())
		.build();
	return new InMemoryClientRegistrationRepository(clientRegistration);
}
 
Example #16
Source File: DataFlowConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Bean
public InMemoryClientRegistrationRepository clientRegistrationRepository(
		ComposedTaskProperties properties) {
	final ClientRegistration clientRegistration = ClientRegistration
			.withRegistrationId("default")
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
			.tokenUri(properties.getOauth2ClientCredentialsTokenUri())
			.clientId(properties.getOauth2ClientCredentialsClientId())
			.clientSecret(properties.getOauth2ClientCredentialsClientSecret())
			.scope(properties.getOauth2ClientCredentialsScopes())
			.build();
	return new InMemoryClientRegistrationRepository(clientRegistration);
}
 
Example #17
Source File: ConfigClientOAuth2BootstrapConfiguration.java    From spring-cloud-services-starters with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
	RestTemplate restTemplate = new RestTemplate();
	ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("config-client")
			.clientId(configClientOAuth2Properties.getClientId())
			.clientSecret(configClientOAuth2Properties.getClientSecret())
			.tokenUri(configClientOAuth2Properties.getAccessTokenUri())
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).build();
	restTemplate.getInterceptors().add(new OAuth2AuthorizedClientHttpRequestInterceptor(clientRegistration));
	locator.setRestTemplate(restTemplate);
}
 
Example #18
Source File: DataFlowConfiguration.java    From composed-task-runner with Apache License 2.0 5 votes vote down vote up
@Bean
public InMemoryClientRegistrationRepository clientRegistrationRepository(
		ComposedTaskProperties properties) {
	final ClientRegistration clientRegistration = ClientRegistration
			.withRegistrationId("default")
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
			.tokenUri(properties.getOauth2ClientCredentialsTokenUri())
			.clientId(properties.getOauth2ClientCredentialsClientId())
			.clientSecret(properties.getOauth2ClientCredentialsClientSecret())
			.scope(properties.getOauth2ClientCredentialsScopes())
			.build();
	return new InMemoryClientRegistrationRepository(clientRegistration);
}
 
Example #19
Source File: ConfigResourceClientAutoConfiguration.java    From spring-cloud-services-starters with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(ConfigResourceClient.class)
@ConditionalOnProperty(prefix = "spring.cloud.config.client.oauth2",
		name = { "client-id", "client-secret", "access-token-uri" })
public ConfigResourceClient configResourceClient(ConfigClientProperties configClientProperties,
		ConfigClientOAuth2Properties configClientOAuth2Properties) {
	ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("config-client")
			.clientId(configClientOAuth2Properties.getClientId())
			.clientSecret(configClientOAuth2Properties.getClientSecret())
			.tokenUri(configClientOAuth2Properties.getAccessTokenUri())
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).build();
	RestTemplate restTemplate = new RestTemplate();
	restTemplate.getInterceptors().add(new OAuth2AuthorizedClientHttpRequestInterceptor(clientRegistration));
	return new OAuth2ConfigResourceClient(restTemplate, configClientProperties);
}
 
Example #20
Source File: KeycloakProviderConfiguration.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
@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 #21
Source File: TokenRelayGatewayFilterFactoryTests.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Test
public void whenPrincipalExistsAuthorizationHeaderAdded() {
	OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
	when(accessToken.getTokenValue()).thenReturn("mytoken");

	ClientRegistration clientRegistration = ClientRegistration
			.withRegistrationId("myregistrationid")
			.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
			.clientId("myclientid").tokenUri("mytokenuri").build();
	OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
			clientRegistration, "joe", accessToken);

	when(repository.loadAuthorizedClient(anyString(),
			any(OAuth2AuthenticationToken.class), any(ServerWebExchange.class)))
					.thenReturn(Mono.just(authorizedClient));

	OAuth2AuthenticationToken authenticationToken = new OAuth2AuthenticationToken(
			mock(OAuth2User.class), Collections.emptyList(), "myId");
	SecurityContextImpl securityContext = new SecurityContextImpl(
			authenticationToken);
	SecurityContextServerWebExchange exchange = new SecurityContextServerWebExchange(
			mockExchange, Mono.just(securityContext));

	filter.filter(exchange, filterChain).block(TIMEOUT);

	assertThat(request.getHeaders()).containsEntry(HttpHeaders.AUTHORIZATION,
			Collections.singletonList("Bearer mytoken"));
}
 
Example #22
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 #23
Source File: FacebookProperties.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
public void setAuthorizedGrantType(AuthorizationGrantType authorizedGrantType) {
    this.authorizedGrantType = authorizedGrantType;
}
 
Example #24
Source File: FacebookProperties.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
public AuthorizationGrantType getAuthorizedGrantType() {
    return authorizedGrantType;
}
 
Example #25
Source File: MicrosoftRegistrationProperties.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
public AuthorizationGrantType getAuthorizedGrantType() {
    return authorizedGrantType;
}
 
Example #26
Source File: GoogleRegistrationProperties.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
public AuthorizationGrantType getAuthorizedGrantType() {
    return authorizedGrantType;
}
 
Example #27
Source File: GoogleRegistrationProperties.java    From OAuth-2.0-Cookbook with MIT License 4 votes vote down vote up
public AuthorizationGrantType getAuthorizedGrantType() {
    return authorizedGrantType;
}