Java Code Examples for org.springframework.security.oauth2.client.OAuth2ClientContext

The following examples show how to use org.springframework.security.oauth2.client.OAuth2ClientContext. 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
@Test
public void testCanUseClientCredentialsWithEnableOAuth2Client() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class);
	TestPropertyValues
			.of("security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials")
			.applyTo(this.context);
	ConfigurationPropertySources.attach(this.context.getEnvironment());
	this.context.refresh();
	// The primary context is fine (not session scoped):
	OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class);
	assertThat(bean.getAccessTokenRequest()).isNotNull();
	assertThat(countBeans(ClientCredentialsResourceDetails.class)).isEqualTo(1);
	// Kind of a bug (should ideally be 1), but the cause is in Spring OAuth2 (there
	// is no need for the extra session-scoped bean). What this test proves is that
	// even if the user screws up and does @EnableOAuth2Client for client
	// credentials,
	// it will still just about work (because of the @Primary annotation on the
	// Boot-created instance of OAuth2ClientContext).
	assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(2);
}
 
Example 2
Source Project: DAFramework   Source File: OAuth2Util.java    License: MIT License 6 votes vote down vote up
public static Filter wechat(AuthorizationCodeResourceDetails client, ResourceServerProperties resourceServerProperties, String path, OAuth2ClientContext oauth2ClientContext) {
	OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(path);

	OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client, oauth2ClientContext);
	AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider();
	accessTokenProvider.setAuthorizationRequestEnhancer((request, resource, form, headers) -> {
		form.set("appid", resource.getClientId());
		form.set("secret", resource.getClientSecret());
		form.set("scope", "snsapi_userinfo");
		form.set("response_type", "code");
		form.set("#wechat_redirect", "");
	});
	accessTokenProvider.setMessageConverters(converters());
	oAuth2RestTemplate.setAccessTokenProvider(accessTokenProvider);

	oAuth2RestTemplate.setRetryBadAccessTokens(true);
	oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);

	UserInfoTokenServices tokenServices = new UserInfoTokenServices(resourceServerProperties.getUserInfoUri(), client.getClientId());
	tokenServices.setRestTemplate(oAuth2RestTemplate);
	oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
	return oAuth2ClientAuthenticationFilter;
}
 
Example 3
Source Project: DAFramework   Source File: OAuth2Util.java    License: MIT License 6 votes vote down vote up
public static Filter general(AuthorizationCodeResourceDetails client, ResourceServerProperties resourceServerProperties, String path, OAuth2ClientContext oauth2ClientContext) {
	OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(path){
		protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
		                                        FilterChain chain, Authentication authResult) throws IOException, ServletException {
			super.successfulAuthentication(request, response, chain, authResult);
			OAuth2AccessToken accessToken = restTemplate.getAccessToken();
			log.warn(new Gson().toJson(authResult));
			log.warn(new Gson().toJson(accessToken));
		}
	};
	OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client, oauth2ClientContext);
	oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
	UserInfoTokenServices tokenServices = new UserInfoTokenServices(resourceServerProperties.getUserInfoUri(), client.getClientId());
	tokenServices.setRestTemplate(oAuth2RestTemplate);
	oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
	return oAuth2ClientAuthenticationFilter;
}
 
Example 4
@Test
public void clientConfigured() throws Exception {
	this.context = new SpringApplicationBuilder(ClientConfiguration.class)
			.properties("spring.config.name=test", "server.port=0",
					"spring.cloud.gateway.enabled=false",
					"security.oauth2.resource.userInfoUri:https://example.com",
					"security.oauth2.client.clientId=foo")
			.run();
	RequestContextHolder.setRequestAttributes(
			new ServletRequestAttributes(new MockHttpServletRequest()));
	OAuth2ClientContext client = this.context.getBean(OAuth2ClientContext.class);
	assertThat(client.getAccessToken()).isNull();
	UserInfoTokenServices services = context.getBean(UserInfoTokenServices.class);
	OAuth2RestTemplate template = (OAuth2RestTemplate) ReflectionTestUtils
			.getField(services, "restTemplate");
	MockRestServiceServer server = MockRestServiceServer.createServer(template);
	server.expect(requestTo("https://example.com"))
			.andRespond(withSuccess("{\"id\":\"user\"}", MediaType.APPLICATION_JSON));
	services.loadAuthentication("FOO");
	assertThat(client.getAccessToken().getValue()).isEqualTo("FOO");
	server.verify();
}
 
Example 5
@Override
public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext,
        ClientHttpRequest request) {

    OAuth2AccessToken accessToken = clientContext.getAccessToken();
    if (accessToken == null) {
        throw new AccessTokenRequiredException(resource);
    }

    String tokenType = accessToken.getTokenType();

    if (!StringUtils.hasText(tokenType) || tokenType.equalsIgnoreCase(OAuth2AccessToken.BEARER_TYPE)) {
        tokenType = OAuth2AccessToken.BEARER_TYPE; // we'll assume basic bearer token type if none is specified.
    }

    request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue()));
}
 
Example 6
@Bean
@ConditionalOnMissingBean
public UserInfoRestTemplateFactory userInfoRestTemplateFactory(
		ObjectProvider<List<UserInfoRestTemplateCustomizer>> customizers,
		ObjectProvider<OAuth2ProtectedResourceDetails> details,
		ObjectProvider<OAuth2ClientContext> oauth2ClientContext) {
	return new DefaultUserInfoRestTemplateFactory(customizers, details, oauth2ClientContext);
}
 
Example 7
public DefaultUserInfoRestTemplateFactory(ObjectProvider<List<UserInfoRestTemplateCustomizer>> customizers,
		ObjectProvider<OAuth2ProtectedResourceDetails> details,
		ObjectProvider<OAuth2ClientContext> oauth2ClientContext) {
	this.customizers = customizers.getIfAvailable();
	this.details = details.getIfAvailable();
	this.oauth2ClientContext = oauth2ClientContext.getIfAvailable();
}
 
Example 8
@Test
public void withRestTemplate() {
	OAuth2ProtectedResourceDetails resource = new AuthorizationCodeResourceDetails();
	OAuth2ClientContext context = new DefaultOAuth2ClientContext();
	DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("FOO");
	token.setRefreshToken(new DefaultExpiringOAuth2RefreshToken("BAR", new Date(0L)));
	context.setAccessToken(token);
	this.services.setRestTemplate(new OAuth2RestTemplate(resource, context));
	assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("me");
	assertThat(context.getAccessToken().getValue()).isEqualTo("FOO");
	// The refresh token is still intact
	assertThat(context.getAccessToken().getRefreshToken()).isEqualTo(token.getRefreshToken());
}
 
Example 9
@Test
public void withRestTemplateChangesState() {
	OAuth2ProtectedResourceDetails resource = new AuthorizationCodeResourceDetails();
	OAuth2ClientContext context = new DefaultOAuth2ClientContext();
	context.setAccessToken(new DefaultOAuth2AccessToken("FOO"));
	this.services.setRestTemplate(new OAuth2RestTemplate(resource, context));
	assertThat(this.services.loadAuthentication("BAR").getName()).isEqualTo("me");
	assertThat(context.getAccessToken().getValue()).isEqualTo("BAR");
}
 
Example 10
@Before
public void init() {
	this.resource.setClientId("foo");
	given(this.template.getForEntity(any(String.class), eq(Map.class)))
			.willReturn(new ResponseEntity<>(this.map, HttpStatus.OK));
	given(this.template.getAccessToken()).willReturn(new DefaultOAuth2AccessToken("FOO"));
	given(this.template.getResource()).willReturn(this.resource);
	given(this.template.getOAuth2ClientContext()).willReturn(mock(OAuth2ClientContext.class));
}
 
Example 11
@Test
public void testClientIsNotResourceServer() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	this.context.register(ClientConfiguration.class, MinimalSecureWebApplication.class);
	this.context.refresh();
	assertThat(countBeans(RESOURCE_SERVER_CONFIG)).isEqualTo(0);
	assertThat(countBeans(AUTHORIZATION_SERVER_CONFIG)).isEqualTo(0);
	// Scoped target and proxy:
	assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(2);
}
 
Example 12
@Test
public void testCanUseClientCredentials() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	this.context.register(TestSecurityConfiguration.class, MinimalSecureWebApplication.class);
	TestPropertyValues
			.of("security.oauth2.client.clientId=client", "security.oauth2.client.grantType=client_credentials")
			.applyTo(this.context);
	ConfigurationPropertySources.attach(this.context.getEnvironment());
	this.context.refresh();
	OAuth2ClientContext bean = this.context.getBean(OAuth2ClientContext.class);
	assertThat(bean.getAccessTokenRequest()).isNotNull();
	assertThat(countBeans(ClientCredentialsResourceDetails.class)).isEqualTo(1);
	assertThat(countBeans(OAuth2ClientContext.class)).isEqualTo(1);
}
 
Example 13
Source Project: OAuth-2.0-Cookbook   Source File: FacebookConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
public OAuth2RestTemplate restTemplate(OAuth2ClientContext context) {
    OAuth2RestTemplate rest = new OAuth2RestTemplate(resourceDetails(), context);
    rest.setAccessTokenProvider(
        new AccessTokenProviderChain(
            Arrays.asList(new AuthorizationCodeAccessTokenProvider())));
    return rest;
}
 
Example 14
Source Project: OAuth-2.0-Cookbook   Source File: GoogleConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
public OAuth2RestTemplate restTemplate(OAuth2ClientContext context) {
    OAuth2RestTemplate rest = new OAuth2RestTemplate(resourceDetails(), context);
    AccessTokenProviderChain providerChain = new AccessTokenProviderChain(
            Arrays.asList(new AuthorizationCodeAccessTokenProvider()));
    rest.setAccessTokenProvider(providerChain);
    return rest;
}
 
Example 15
Source Project: OAuth-2.0-Cookbook   Source File: GoogleConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
public OAuth2RestTemplate restTemplate(OAuth2ClientContext context) {
    OAuth2RestTemplate rest = new OAuth2RestTemplate(resourceDetails(), context);
    AccessTokenProviderChain providerChain = new AccessTokenProviderChain(
            Arrays.asList(new AuthorizationCodeAccessTokenProvider()));
    rest.setAccessTokenProvider(providerChain);
    return rest;
}
 
Example 16
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {
    OAuth2ClientContext clientContext = applicationContext.getBean(OAuth2ClientContext.class);
    OAuth2AccessToken accessToken = clientContext.getAccessToken();

    request.getHeaders().set("Authorization", "Bearer " + accessToken.getValue());
    request.getHeaders().set("nonce", keyPairManager.getSignedContent(UUID.randomUUID().toString()));

    return execution.execute(request, body);
}
 
Example 17
/**
 * RestTempate that relays the OAuth2 token passed to the task webservice.
 * 
 * @param oauth2ClientContext
 * @return
 */
@Bean(name = "oAuth2RestTemplate")
@LoadBalanced
@Primary
public OAuth2RestTemplate restTemplate(OAuth2ClientContext context) {
	return new OAuth2RestTemplate(authServer(), context);
}
 
Example 18
@Bean
public OAuth2RestTemplate oauth2RestTemplate(
		OAuth2ProtectedResourceDetails resource,
		OAuth2ClientContext oauth2Context) {
	return new OAuth2RestTemplate(resource, oauth2Context);

}
 
Example 19
@Test
public void applyAuthorizationHeaderOnlyOnce() {
	OAuth2ClientContext oAuth2ClientContext = mock(OAuth2ClientContext.class);
	when(oAuth2ClientContext.getAccessToken())
			.thenReturn(new MockOAuth2AccessToken("MOCKED_TOKEN"));

	OAuth2FeignRequestInterceptor oAuth2FeignRequestInterceptor = new OAuth2FeignRequestInterceptor(
			oAuth2ClientContext, new BaseOAuth2ProtectedResourceDetails());

	oAuth2FeignRequestInterceptor.apply(requestTemplate);

	// First idempotent call failed, retry mechanism kicks in, and token has expired
	// in the meantime

	OAuth2AccessToken expiredAccessToken = mock(OAuth2AccessToken.class);
	when(expiredAccessToken.isExpired()).thenReturn(true);
	when(oAuth2ClientContext.getAccessToken()).thenReturn(expiredAccessToken);
	AccessTokenRequest accessTokenRequest = mock(AccessTokenRequest.class);
	when(oAuth2ClientContext.getAccessTokenRequest()).thenReturn(accessTokenRequest);
	OAuth2AccessToken newToken = new MockOAuth2AccessToken("Fancy");
	oAuth2FeignRequestInterceptor
			.setAccessTokenProvider(new MockAccessTokenProvider(newToken));

	oAuth2FeignRequestInterceptor.apply(requestTemplate);

	Map<String, Collection<String>> headers = requestTemplate.headers();
	Assert.assertTrue("RequestTemplate must have a Authorization header",
			headers.containsKey("Authorization"));
	Assert.assertThat("Authorization must have a extract of Fancy",
			headers.get("Authorization"), hasSize(1));
	Assert.assertThat("Authorization must have a extract of Fancy",
			headers.get("Authorization"), contains("Bearer Fancy"));
}
 
Example 20
@Bean
public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
														OAuth2ProtectedResourceDetails resource,
														AccessTokenContextRelay accessTokenContextRelay) {
	return new CloudFeignClientInterceptor(oAuth2ClientContext, resource,accessTokenContextRelay);
}
 
Example 21
@Bean
public AccessTokenContextRelay accessTokenContextRelay(OAuth2ClientContext context) {
	return new AccessTokenContextRelay(context);
}
 
Example 22
/**
 * This OAuth2RestTemplate is only used by AuthorizationHeaderUtil that is currently used by TokenRelayRequestInterceptor
 */
@Bean
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
    OAuth2ClientContext oAuth2ClientContext) {
    return new OAuth2RestTemplate(oAuth2ProtectedResourceDetails, oAuth2ClientContext);
}
 
Example 23
/**
 * This OAuth2RestTemplate is used by org.springframework.cloud.security.oauth2.proxy.OAuth2TokenRelayFilter
 * from Spring Cloud Security to refresh the access token when needed.
 */
@Bean
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
    OAuth2ClientContext oAuth2ClientContext) {
    return new OAuth2RestTemplate(oAuth2ProtectedResourceDetails, oAuth2ClientContext);
}
 
Example 24
/**
 * This OAuth2RestTemplate is only used by AuthorizationHeaderUtil that is currently used by TokenRelayRequestInterceptor
 */
@Bean
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
    OAuth2ClientContext oAuth2ClientContext) {
    return new OAuth2RestTemplate(oAuth2ProtectedResourceDetails, oAuth2ClientContext);
}
 
Example 25
Source Project: openapi-generator   Source File: ClientConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnProperty("openapipetstore.security.petstoreAuth.client-id")
public OAuth2FeignRequestInterceptor petstoreAuthRequestInterceptor(OAuth2ClientContext oAuth2ClientContext) {
  return new OAuth2FeignRequestInterceptor(oAuth2ClientContext, petstoreAuthResourceDetails());
}
 
Example 26
Source Project: openapi-generator   Source File: ClientConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnProperty("openapipetstore.security.petstoreAuth.client-id")
public OAuth2ClientContext oAuth2ClientContext() {
  return new DefaultOAuth2ClientContext();
}
 
Example 27
Source Project: openapi-generator   Source File: ClientConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnProperty("openapipetstore.security.petstoreAuth.client-id")
public OAuth2FeignRequestInterceptor petstoreAuthRequestInterceptor(OAuth2ClientContext oAuth2ClientContext) {
  return new OAuth2FeignRequestInterceptor(oAuth2ClientContext, petstoreAuthResourceDetails());
}
 
Example 28
Source Project: openapi-generator   Source File: ClientConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnProperty("openapipetstore.security.petstoreAuth.client-id")
public OAuth2ClientContext oAuth2ClientContext() {
  return new DefaultOAuth2ClientContext();
}
 
Example 29
Source Project: oauth2lab   Source File: OAuth2Configuration.java    License: MIT License 4 votes vote down vote up
@Bean
public OAuth2RestTemplate restTemplate(OAuth2ClientContext context) {
    return new OAuth2RestTemplate(authorizationCode(), context);
}
 
Example 30
@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
	return new OAuth2RestTemplate(details, oauth2ClientContext);
}