org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken()方法的使用及代码示例

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

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

OAuth2RestTemplate.getAccessToken介绍

[英]Acquire or renew an access token for the current context if necessary. This method will be called automatically when a request is executed (and the result is cached), but can also be called as a standalone method to pre-populate the token.
[中]如有必要,获取或续订当前上下文的访问令牌。该方法将在执行请求(并缓存结果)时自动调用,但也可以作为独立方法调用,以预填充令牌。

代码示例

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

return client.getAccessToken();

代码示例来源: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

@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: com.bosch.bis.base/bis-service-connector

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

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

private void startOAuth2Dance() {
  restTemplate.getAccessToken();
}

代码示例来源:origin: tigerphz/tgcloud-master

/**
   * Apply.
   *
   * @param template the template
   */
  @Override
  public void apply(RequestTemplate template) {
    log.debug("Constructing Header {} for Token {}", HttpHeaders.AUTHORIZATION, BEARER_TOKEN_TYPE);
    template.header(HttpHeaders.AUTHORIZATION, String.format("%s %s", BEARER_TOKEN_TYPE, oAuth2RestTemplate.getAccessToken().toString()));
  }
}

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

public void doFilter(ServletRequest req, ServletResponse res,
           FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request = (HttpServletRequest) req;
  if (localMatcher.matches(request)) {
    restTemplate.getAccessToken();
    chain.doFilter(req, res);
  } else {
    super.doFilter(req, res, chain);
  }
}

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

@Override
public void doFilter(ServletRequest req, ServletResponse res,
  FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request = (HttpServletRequest) req;
  if (localMatcher.matches(request)) {
    restTemplate.getAccessToken();
    chain.doFilter(req, res);
  } else {
    super.doFilter(req, res, chain);
  }
}

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

@Override
public void doFilter(ServletRequest req, ServletResponse res,
   FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request = (HttpServletRequest) req;
  if (localMatcher.matches(request)) {
    restTemplate.getAccessToken();
    chain.doFilter(req, res);
  } else {
    super.doFilter(req, res, chain);
  }
}

代码示例来源:origin: com.bosch.bis.monitoring/bis-event-publisher-impl

public void updateOAuth2AuthenticationHeader() {
  if (connection.getOauth2RestTemplate() != null) {
    String token = connection.getOauth2RestTemplate().getAccessToken().getValue();
    manager.getHeaders().set("Authorization", "Bearer " + token);
    LOG.info("Added JWT token to Websocket request headers.");
  } else {
    LOG.warn("No JWT authentication used for websocket connection.");
  }
}

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

return client.getAccessToken();

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

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
  throws AuthenticationException, IOException, ServletException {
  try {
    OAuth2AccessToken accessToken = restTemplate.getAccessToken();
    FacebookUser facebookUser = userIdentity.findOrCreateFrom(accessToken);
    repository.save(facebookUser);
    Authentication authentication = new UsernamePasswordAuthenticationToken(
        facebookUser, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
    publish(new AuthenticationSuccessEvent(authentication));
    return authentication;
  } catch (OAuth2Exception e) {
    BadCredentialsException error = new BadCredentialsException(
        "Cannot retrieve the access token", e);
    publish(new OAuth2AuthenticationFailureEvent(error));
    throw error;
  }
}

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

/**
 * Returns {@code true} if the user (using the access-token from
 * {@link OAuth2RestTemplate}) has full {@link AccessLevel#FULL} for the provided
 * {@code applicationId}
 *
 * @return true of the user is a space developer in Cloud Foundry
 */
public boolean isSpaceDeveloper() {
  final OAuth2AccessToken accessToken = this.oAuth2RestTemplate.getAccessToken();
  logger.info("The accessToken is: " + accessToken.getValue());
  final AccessLevel accessLevel = getAccessLevel(
      accessToken.getValue(), applicationId);
  if (AccessLevel.FULL.equals(accessLevel)) {
    return true;
  }
  else {
    return false;
  }
}

代码示例来源:origin: org.springframework.cloud/spring-cloud-dataflow-server-cloudfoundry-autoconfig

/**
 * Returns {@code true} if the user (using the access-token from
 * {@link OAuth2RestTemplate}) has full {@link AccessLevel#FULL} for the provided
 * {@code applicationId}
 *
 * @return true of the user is a space developer in Cloud Foundry
 */
public boolean isSpaceDeveloper() {
  final OAuth2AccessToken accessToken = this.oAuth2RestTemplate.getAccessToken();
  logger.info("The accessToken is: " + accessToken.getValue());
  final AccessLevel accessLevel = getAccessLevel(
      accessToken.getValue(), applicationId);
  if (AccessLevel.FULL.equals(accessLevel)) {
    return true;
  }
  else {
    return false;
  }
}

代码示例来源:origin: org.springframework.cloud/spring-cloud-dataflow-platform-cloudfoundry

/**
 * Returns {@code true} if the user (using the access-token from
 * {@link OAuth2RestTemplate}) has full {@link AccessLevel#FULL} for the provided
 * {@code applicationId}
 *
 * @return true of the user is a space developer in Cloud Foundry
 */
public boolean isSpaceDeveloper() {
  final OAuth2AccessToken accessToken = this.oAuth2RestTemplate.getAccessToken();
  logger.info("The accessToken is: " + accessToken.getValue());
  final AccessLevel accessLevel = getAccessLevel(
      accessToken.getValue(), applicationId);
  if (AccessLevel.FULL.equals(accessLevel)) {
    return true;
  }
  else {
    return false;
  }
}

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

@Override
public Authentication attemptAuthentication(
  HttpServletRequest request, HttpServletResponse response)
  throws AuthenticationException, IOException, ServletException {
  try {
    OAuth2AccessToken accessToken = restTemplate.getAccessToken();
    Claims claims = Claims.createFrom(jsonMapper, accessToken);
    GoogleUser googleUser = userIdentity.findOrCreateFrom(claims);
    repository.save(googleUser);
    Authentication authentication = new UsernamePasswordAuthenticationToken(
      googleUser, null, googleUser.getAuthorities());
    publish(new AuthenticationSuccessEvent(authentication));
    return authentication;
  } catch (OAuth2Exception e) {
    BadCredentialsException error = new BadCredentialsException(
        "Cannot retrieve the access token", e);
    publish(new OAuth2AuthenticationFailureEvent(error));
    throw error;
  }
}

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

@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: spring-cloud/spring-cloud-skipper

@Test
public void testAccessAboutUrlWithOAuth2AccessToken() throws Exception {
  final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
  resourceDetails.setClientId("myclient");
  resourceDetails.setClientSecret("mysecret");
  resourceDetails.setGrantType("client_credentials");
  resourceDetails
      .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token");
  final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
  final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();
  final String accessTokenAsString = accessToken.getValue();
  localSkipperResource.getMockMvc()
      .perform(get("/api/about").header("Authorization", "bearer " + accessTokenAsString)).andDo(print())
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.versionInfo.server.name", is("Spring Cloud Skipper Server")))
      .andExpect(jsonPath("$.versionInfo.server.version", notNullValue()));
}

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

@Test
public void testAccessRootUrlWithOAuth2AccessToken() throws Exception {
  final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
  resourceDetails.setClientId("myclient");
  resourceDetails.setClientSecret("mysecret");
  resourceDetails.setGrantType("client_credentials");
  resourceDetails
      .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token");
  final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
  final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();
  final String accessTokenAsString = accessToken.getValue();
  localSkipperResource.getMockMvc().perform(get("/api").header("Authorization", "bearer " + accessTokenAsString))
      .andDo(print()).andExpect(status().isOk());
}

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

@Test
public void testAccessRootUrlWithOAuth2AccessToken() throws Exception {
  final ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
  resourceDetails.setClientId("myclient");
  resourceDetails.setClientSecret("mysecret");
  resourceDetails.setGrantType("client_credentials");
  resourceDetails
      .setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token");
  final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
  final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();
  final String accessTokenAsString = accessToken.getValue();
  localDataflowResource.getMockMvc().perform(get("/").header("Authorization", "bearer " + accessTokenAsString))
      .andDo(print()).andExpect(status().isOk());
}

相关文章