org.springframework.security.oauth2.client.OAuth2RestTemplate类的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(11.3k)|赞(0)|评价(0)|浏览(284)

本文整理了Java中org.springframework.security.oauth2.client.OAuth2RestTemplate类的一些代码示例,展示了OAuth2RestTemplate类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。OAuth2RestTemplate类的具体详情如下:
包路径:org.springframework.security.oauth2.client.OAuth2RestTemplate
类名称:OAuth2RestTemplate

OAuth2RestTemplate介绍

[英]Rest template that is able to make OAuth2-authenticated REST requests with the credentials of the provided resource.
[中]Rest模板,能够使用所提供资源的凭据发出OAuth2认证的Rest请求。

代码示例

Official Spring framework guide

代码示例来源:origin: spring-guides/tut-spring-boot-oauth2

@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
  return new OAuth2RestTemplate(resource, context);
}

Official Spring framework guide

代码示例来源:origin: spring-guides/tut-spring-boot-oauth2

private Filter ssoFilter(ClientResources client, String path) {
  OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
      path);
  OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
  filter.setRestTemplate(template);
  UserInfoTokenServices tokenServices = new UserInfoTokenServices(
      client.getResource().getUserInfoUri(), client.getClient().getClientId());
  tokenServices.setRestTemplate(template);
  filter.setTokenServices(tokenServices);
  return filter;
}

Official Spring framework guide

代码示例来源:origin: spring-guides/tut-spring-boot-oauth2

private Filter ssoFilter() {
  OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
      "/login/facebook");
  OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
  facebookFilter.setRestTemplate(facebookTemplate);
  UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
      facebook().getClientId());
  tokenServices.setRestTemplate(facebookTemplate);
  facebookFilter.setTokenServices(tokenServices);
  return facebookFilter;
}

Official Spring framework guide

代码示例来源:origin: spring-guides/tut-spring-boot-oauth2

private Filter ssoFilter(ClientResources client, String path) {
  OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(path);
  OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
  oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
  UserInfoTokenServices tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(),
      client.getClient().getClientId());
  tokenServices.setRestTemplate(oAuth2RestTemplate);
  oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
  return oAuth2ClientAuthenticationFilter;
}

代码示例来源:origin: sqshq/piggymetrics

@Bean
  public OAuth2RestTemplate clientCredentialsRestTemplate() {
    return new OAuth2RestTemplate(clientCredentialsResourceDetails());
  }
}

代码示例来源:origin: spring-projects/spring-security-oauth

private OAuth2RestTemplate createRestTemplate(
    OAuth2ProtectedResourceDetails resource, AccessTokenRequest request) {
  OAuth2ClientContext context = new DefaultOAuth2ClientContext(request);
  OAuth2RestTemplate client = new OAuth2RestTemplate(resource, context);
  setupConnectionFactory(client);
  client.setErrorHandler(new DefaultResponseErrorHandler() {
    // Pass errors through in response entity for status code analysis
    public boolean hasError(ClientHttpResponse response) throws IOException {
      return false;
    }
  });
  if (accessTokenProvider != null) {
    client.setAccessTokenProvider(accessTokenProvider);
  }
  return client;
}

代码示例来源:origin: spring-projects/spring-security-oauth

@Test
@OAuth2ContextConfiguration(value=ResourceOwner.class, initialize=false)
public void testTokenEndpointWrongPassword() throws Exception {
  ResourceOwnerPasswordResourceDetails resource = (ResourceOwnerPasswordResourceDetails) context
      .getResource();
  resource.setPassword("bogus");
  try {			
    new OAuth2RestTemplate(resource).getAccessToken();
  } catch (OAuth2AccessDeniedException e) {
    String summary = ((OAuth2Exception)e.getCause()).getSummary();
    assertTrue("Wrong summary: " + summary, summary.contains("Bad credentials"));
  }
}

代码示例来源:origin: spring-projects/spring-security-oauth

client.setAccessTokenProvider(accessTokenProvider);
return client.getAccessToken();

代码示例来源:origin: spring-projects/spring-security-oauth

private void verifyAuthorizationPage(OAuth2RestTemplate restTemplate, String location) {
  final AtomicReference<String> confirmationPage = new AtomicReference<String>();
  AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider() {
    @Override
    protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() {
      return new ResponseExtractor<ResponseEntity<Void>>() {
        public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
          confirmationPage.set(StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")));
          return new ResponseEntity<Void>(response.getHeaders(), response.getStatusCode());
        }
      };
    }
  };
  try {
    provider.obtainAuthorizationCode(restTemplate.getResource(), restTemplate.getOAuth2ClientContext().getAccessTokenRequest());
  } catch (UserApprovalRequiredException e) {
    // ignore
  }
  String page = confirmationPage.get();
  verifyAuthorizationPage(page);
}

代码示例来源:origin: PacktPublishing/OAuth-2.0-Cookbook

@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;
}

代码示例来源:origin: spring-cloud/spring-cloud-dataflow

resource.setGrantType("password");
final OAuth2RestTemplate template = new OAuth2RestTemplate(resource,
    new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
template.setAccessTokenProvider(userAccessTokenProvider());
  accessToken = template.getAccessToken();

代码示例来源:origin: cloudfoundry/uaa

private OAuth2RestTemplate createRestTemplate(OAuth2ProtectedResourceDetails resource,
        AccessTokenRequest accessTokenRequest) {
  OAuth2ClientContext context = new DefaultOAuth2ClientContext(accessTokenRequest);
  OAuth2RestTemplate client = new OAuth2RestTemplate(resource, context);
  client.setRequestFactory(new SimpleClientHttpRequestFactory() {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
      super.prepareConnection(connection, httpMethod);
      connection.setInstanceFollowRedirects(false);
    }
  });
  client.setErrorHandler(new OAuth2ErrorHandler(client.getResource()) {
    // Pass errors through in response entity for status code analysis
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
      return false;
    }
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
    }
  });
  List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
  list.add(new StringHttpMessageConverter());
  list.add(new MappingJackson2HttpMessageConverter());
  client.setMessageConverters(list);
  return client;
}

代码示例来源:origin: kbastani/spring-cloud-event-sourcing-example

/**
 * Get the authenticated user from the user service
 *
 * @return the currently authenticated user
 */
public User getAuthenticatedUser() {
  return oAuth2RestTemplate.getForObject("http://user-service/uaa/v1/me", User.class);
}

代码示例来源:origin: com.bosch.bis.base/bis-service-connector

OAuth2AccessToken getAccessToken() {
  return oauth2RestTemplate != null ? oauth2RestTemplate.getAccessToken() : null;
}

代码示例来源:origin: spring-projects/spring-security-oauth

@Override
protected ClientHttpRequest createRequest(URI uri, HttpMethod method) throws IOException {
  OAuth2AccessToken accessToken = getAccessToken();
  AuthenticationScheme authenticationScheme = resource.getAuthenticationScheme();
  if (AuthenticationScheme.query.equals(authenticationScheme)
      || AuthenticationScheme.form.equals(authenticationScheme)) {
    uri = appendQueryParameter(uri, accessToken);
  }
  ClientHttpRequest req = super.createRequest(uri, method);
  if (AuthenticationScheme.header.equals(authenticationScheme)) {
    authenticator.authenticate(resource, getOAuth2ClientContext(), req);
  }
  return req;
}

代码示例来源:origin: org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure

@Override
public OAuth2RestTemplate getUserInfoRestTemplate() {
  if (this.oauth2RestTemplate == null) {
    this.oauth2RestTemplate = createOAuth2RestTemplate(
        this.details == null ? DEFAULT_RESOURCE_DETAILS : this.details);
    this.oauth2RestTemplate.getInterceptors()
        .add(new AcceptJsonRequestInterceptor());
    AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider();
    accessTokenProvider.setTokenRequestEnhancer(new AcceptJsonRequestEnhancer());
    this.oauth2RestTemplate.setAccessTokenProvider(accessTokenProvider);
    if (!CollectionUtils.isEmpty(this.customizers)) {
      AnnotationAwareOrderComparator.sort(this.customizers);
      for (UserInfoRestTemplateCustomizer customizer : this.customizers) {
        customizer.customize(this.oauth2RestTemplate);
      }
    }
  }
  return this.oauth2RestTemplate;
}

代码示例来源:origin: org.cloudfoundry/cloudfoundry-client-spring

private static void setRequestFactory(OAuth2RestTemplate restTemplate, HostnameVerifier hostnameVerifier, SSLContext sslContext) {
  if (hostnameVerifier != null && sslContext != null) {
    CustomSslSimpleClientHttpRequestFactory requestFactory = new CustomSslSimpleClientHttpRequestFactory(hostnameVerifier, sslContext);
    restTemplate.setRequestFactory(requestFactory);
    restTemplate.setAccessTokenProvider(getAccessTokenProvider(requestFactory));
  }
}

代码示例来源:origin: kbastani/spring-cloud-event-sourcing-example

oAuth2RestTemplate.getForObject(String.format("http://inventory-service/v1/inventory?productIds=%s", currentCart.getLineItems()
    .stream()
    .map(LineItem::getProductId)
Order orderResponse = oAuth2RestTemplate.postForObject("http://order-service/v1/orders",
    currentCart.getLineItems().stream()
        .map(prd ->
  oAuth2RestTemplate.postForEntity(String.format("http://order-service/v1/orders/%s/events", orderResponse.getOrderId()),
      new OrderEvent(OrderEventType.CREATED, orderResponse.getOrderId()), ResponseEntity.class);
User user = oAuth2RestTemplate.getForObject("http://user-service/uaa/v1/me", User.class);

代码示例来源:origin: spring-projects/spring-security-oauth

/**
 * @return the current OAuth2 context
 */
public OAuth2ClientContext getOAuth2ClientContext() {
  return client.getOAuth2ClientContext();
}

代码示例来源:origin: stackoverflow.com

protected RestKeyCloakClient()
{
  MultiValueMap<String, String> header = new LinkedMultiValueMap<String, String>();
  OAuth2RestTemplate client;
  DefaultAccessTokenRequest accessTokenRequest = new DefaultAccessTokenRequest();
  DefaultOAuth2ClientContext context = new DefaultOAuth2ClientContext(accessTokenRequest);
  OAuth2AccessTokenSupport support = new OAuth2AccessTokenSupport()
  {
  };
  List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
  messageConverters.add(new FormOAuth2AccessTokenMessageConverter());
  messageConverters.add(new FormOAuth2ExceptionHttpMessageConverter());
  MappingJackson2HttpMessageConverter jackson = new MappingJackson2HttpMessageConverter();
  List<MediaType> mediaTypes = new ArrayList<MediaType>();
  mediaTypes.add(new MediaType("application", "x-www-form-urlencoded"));
  jackson.setSupportedMediaTypes(mediaTypes);
  messageConverters.add(jackson);
  support.setMessageConverters(messageConverters);
  client = new OAuth2RestTemplate(getAuthDetails(null, null), context);
  client.setErrorHandler(errorHandler);
  client.setRequestFactory(factory);
  token = client.getAccessToken();
}

相关文章