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

The following examples show how to use org.springframework.security.oauth2.client.OAuth2RestTemplate. 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: Spring-Security-Third-Edition   Source File: OAuth2ClientTest.java    License: MIT License 6 votes vote down vote up
public void testConnectDirectlyToResourceServer() throws Exception {
    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
    resource.setAccessTokenUri(tokenUrl);
    resource.setId("microservice-test");
    resource.setClientId("oauthClient1");
    resource.setClientSecret("oauthClient1Password");

    resource.setGrantType("password");

    resource.setScope(Arrays.asList("openid"));

    resource.setUsername("[email protected]");
    resource.setPassword("user1");
    OAuth2RestTemplate template = new OAuth2RestTemplate(resource);
    logger.info(" CALLING: " + baseUrl+"/api");

    String result = template.getForObject(baseUrl+"/api", String.class);

    System.err.println(result);
    assertEquals("Hello, Trusted User marissa", result);
}
 
Example 2
@Test
public void testOAuthService() {	
       ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
       resource.setUsername("guest");
       resource.setPassword("guest123");
       resource.setAccessTokenUri("http://localhost:8080/oauth/token");
       resource.setClientId("trustedclient");
       resource.setClientSecret("trustedclient123");
       resource.setGrantType("password");
       resource.setScope(Arrays.asList(new String[]{"read","write","trust"}));
 
       DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
       OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource, clientContext);

       Greet greet = restTemplate.getForObject("http://localhost:8080", Greet.class);

       Assert.assertEquals("Hello World!", greet.getMessage());
}
 
Example 3
@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ProtectedResourceDetails details) {
  OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(details);

  LOG.debug("Begin OAuth2RestTemplate: getAccessToken");
  /* To validate if required configurations are in place during startup */
  oAuth2RestTemplate.getAccessToken();
  LOG.debug("End OAuth2RestTemplate: getAccessToken");
  return oAuth2RestTemplate;
}
 
Example 4
Source Project: spring-boot   Source File: Oauth2ClientRestTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClientCredentialsRestTemplate() throws Exception {

    ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
     details.setId("4");
    details.setClientId(client_id);
    details.setClientSecret(client_secret);
    details.setAccessTokenUri(access_token_uri);
   // details.setScope(Arrays.asList("read write"));
    OAuth2RestTemplate operations = new OAuth2RestTemplate(details,new DefaultOAuth2ClientContext());
   // OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
    operations.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider());

  //  OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails(),oAuth2ClientContext());
    DefaultOAuth2AccessToken token=(DefaultOAuth2AccessToken)operations.getAccessToken();
    token.setTokenType("Bearer");

    System.out.println("client_id : " + client_id);
    System.out.println("source_url : " + source_url);

  //  OAuth2RestOperations operations = restTemplate.clientCredentialsRestTemplate(client_id, client_secret, access_token_uri, scopes);  // getForObject 发送 get 方法
    System.out.println(JSON.toJSONString(operations.getForObject(source_url, JsonNode.class)));  // getForObject 发送 get 方法

}
 
Example 5
Source Project: spring-boot   Source File: Oauth2ClientRestTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 该方式没有实验成功,设置为 Deprecated!
 * <p>
 * 演示 grant_type=implicit 时,获取资源的方法
 *
 * @param client_id
 * @param client_secret     取决于 AuthorizationServer 设置,如果 client 设置了secret,则此项参数为必需,否则可以没有
 * @param authorization_uri
 * @param access_token_uri
 * @param scope
 * @return
 */
@Deprecated
public OAuth2RestOperations implicitResourceRestTemplate(String client_id, String client_secret, String authorization_uri, String access_token_uri, String... scope) {

    // 防止 url 写错
    if (!authorization_uri.contains("authorize"))
        throw new RuntimeException("uri is wrong :  authorization_uri" + authorization_uri);

    ImplicitResourceDetails details = new ImplicitResourceDetails();
    details.setId("2");
    details.setClientId(client_id);
    if (client_secret != null && !client_secret.isEmpty())
        details.setClientSecret(client_secret);
    details.setAccessTokenUri(authorization_uri);
    details.setClientAuthenticationScheme(AuthenticationScheme.header);
    details.setUseCurrentUri(true);
    details.setScope(Arrays.asList(scope));
    // return restTemplate;
    return new OAuth2RestTemplate(details, oAuth2ClientContext);
}
 
Example 6
@Test
public void usingUserWithViewRoles() throws Exception {

	final ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
	resourceDetails.setClientId("myclient");
	resourceDetails.setClientSecret("mysecret");
	resourceDetails.setUsername("bob");
	resourceDetails.setPassword("bobspassword");
	resourceDetails
			.setAccessTokenUri("http://localhost:" + oAuth2ServerResource.getOauth2ServerPort() + "/oauth/token");

	final OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
	final OAuth2AccessToken accessToken = oAuth2RestTemplate.getAccessToken();

	System.setProperty("accessTokenAsString", accessToken.getValue());

	context = new AnnotationConfigApplicationContext(TestApplication.class);

	final DataFlowOperations dataFlowOperations = context.getBean(DataFlowOperations.class);
	final AboutResource about = dataFlowOperations.aboutOperation().get();

	assertNotNull(about);
	assertEquals("bob", about.getSecurityInfo().getUsername());
	assertEquals(1, about.getSecurityInfo().getRoles().size());
}
 
Example 7
@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;
}
 
Example 8
@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());
}
 
Example 9
Source Project: Spring-Security-Third-Edition   Source File: JavaConfig.java    License: MIT License 6 votes vote down vote up
@Bean
    public OAuth2RestOperations oAuth2RestOperations() {

        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
        resource.setAccessTokenUri(tokenUrl);
        resource.setId(resourceId);
        resource.setClientId(resourceClientId);
        resource.setClientSecret(resourceClientSecret);

        resource.setGrantType("password");

        resource.setScope(Arrays.asList("openid"));

        resource.setUsername("[email protected]");
        resource.setPassword("user1");

        OAuth2RestTemplate template = new OAuth2RestTemplate(resource);
//        template.setRequestFactory(requestFactory);
        return template;
    }
 
Example 10
Source Project: crnk-example   Source File: SpringSecurityConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
private OAuth2ClientAuthenticationProcessingFilter ssoFilter(ClientResources client, String path) {
	OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);

	UserInfoTokenServices tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(),
			client.getClient().getClientId());
	tokenServices.setRestTemplate(oAuth2RestTemplate);

	OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter =
			new OAuth2ClientAuthenticationProcessingFilter(path);
	oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate);
	oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices);
	oAuth2ClientAuthenticationFilter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler() {
		@Override
		public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
				Authentication authentication) throws IOException, ServletException {
			// TODO switch to tokens or find a way to return to last page on client
			this.setDefaultTargetUrl("/");
			super.onAuthenticationSuccess(request, response, authentication);
		}
	});

	return oAuth2ClientAuthenticationFilter;
}
 
Example 11
@Test
public void testOAuthService() {	
       ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
       resource.setUsername("guest");
       resource.setPassword("guest123");
       resource.setAccessTokenUri("http://localhost:8080/oauth/token");
       resource.setClientId("trustedclient");
       resource.setClientSecret("trustedclient123");
       resource.setGrantType("password");
 
       DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
       OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource, clientContext);

       Greet greet = restTemplate.getForObject("http://localhost:8080", Greet.class);

       Assert.assertEquals("Hello World!", greet.getMessage());
}
 
Example 12
Source Project: spring-boot   Source File: Oauth2ClientRestTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 演示 grant_type=password 时,获取资源的方法
 * 用的场景还不知道,@Deprecated
 *
 * @param client_id
 * @param client_secret    取决于 AuthorizationServer 设置,如果 client 设置了secret,则此项参数为必需,否则可以没有
 * @param access_token_uri
 * @param username
 * @param password
 * @param scope
 * @return
 */
@Deprecated
public OAuth2RestOperations resourceOwnerPasswordRestTemplate(String client_id, String client_secret, String access_token_uri, String username, String password, String... scope) {

    // 防止 url 写错
    if (!access_token_uri.contains("token"))
        throw new RuntimeException("uri is wrong :  access_token_uri = " + access_token_uri);

    // 防止 client_secret 写错
    if (username == null || password == null || username.isEmpty() || password.isEmpty())
        throw new RuntimeException("username or password  is wrong :  username or password is a required parameter");

    ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails();
    details.setId("3");
    details.setClientId(client_id);
    if (client_secret != null && !client_secret.isEmpty())
        details.setClientSecret(client_secret);
    details.setAccessTokenUri(access_token_uri);
    details.setUsername(username);
    details.setPassword(password);
    details.setScope(Arrays.asList(scope));
    return new OAuth2RestTemplate(details, oAuth2ClientContext);


}
 
Example 13
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 14
Source Project: spring-boot   Source File: Oauth2ClientRestTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 演示 grant_type=client_credentials 时,获取资源的方法
 *
 * @param client_id
 * @param client_secret    取决于 AuthorizationServer 设置,如果 client 设置了secret,则此项参数为必需,否则可以没有
 * @param access_token_uri
 * @param scope
 * @return
 */
public OAuth2RestOperations clientCredentialsRestTemplate(String client_id, String client_secret, String access_token_uri, String... scope) {

    // 防止 url 写错
    if (!access_token_uri.contains("token"))
        throw new RuntimeException("uri is wrong :  access_token_uri = " + access_token_uri);

    ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
    details.setId("4");
    details.setClientId(client_id);
    if (client_secret != null && !client_secret.isEmpty())
        details.setClientSecret(client_secret);
    details.setAccessTokenUri(access_token_uri);
    details.setScope(Arrays.asList(scope));
    return new OAuth2RestTemplate(details, oAuth2ClientContext);
}
 
Example 15
@Test
public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() {
    ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write"));
    OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);

    OAuth2AccessToken accessToken = restTemplate.getAccessToken();

    assertNotNull(accessToken);
}
 
Example 16
Source Project: open-cloud   Source File: OpenRestTemplate.java    License: MIT License 5 votes vote down vote up
/**
 * 构建网关Oauth2 password方式请求
 *
 * @param clientId
 * @param clientSecret
 * @param accessTokenUri
 * @param username
 * @param password
 * @return
 */
public OAuth2RestTemplate buildOAuth2PasswordRequest(String clientId, String clientSecret, String accessTokenUri, String username, String password) {
    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
    resource.setUsername(username);
    resource.setPassword(password);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setAccessTokenUri(accessTokenUri);
    resource.setAuthenticationScheme(AuthenticationScheme.form);
    resource.setGrantType("password");
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource);
    return restTemplate;
}
 
Example 17
Source Project: Mastering-Spring-5.1   Source File: TodoControllerIT.java    License: MIT License 5 votes vote down vote up
private OAuth2RestTemplate getOAuthTemplate() {
	ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
	resource.setUsername("user2");
	resource.setPassword("user2-password");
	resource.setAccessTokenUri(createUrl("/oauth/token"));
	resource.setClientId("YourClientID");
	resource.setClientSecret("TopSecretClientPassword");
	resource.setGrantType("password");
	OAuth2RestTemplate oauthTemplate = new OAuth2RestTemplate(resource, new DefaultOAuth2ClientContext());
	return oauthTemplate;
}
 
Example 18
Source Project: cola   Source File: SsoAuthClient.java    License: MIT License 5 votes vote down vote up
/**
 * 登录
 *
 * @param username
 * @param password
 * @return
 */
public OAuth2AccessToken login(String username, String password) {
	ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails();
	details.setUsername(username);
	details.setPassword(password);
	details.setAccessTokenUri(this.properties.getAccessTokenUri());
	details.setClientId(this.properties.getClientId());
	details.setClientSecret(this.properties.getClientSecret());
	OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(details);
	auth2RestTemplate.setAccessTokenProvider(new ResourceOwnerPasswordAccessTokenProvider());
	return auth2RestTemplate.getAccessToken();
}
 
Example 19
Source Project: cola   Source File: SsoAuthClient.java    License: MIT License 5 votes vote down vote up
/**
 * openId登录
 *
 * @param openId   openid
 * @param provider 供应商
 * @return
 */
public OAuth2AccessToken loginByOpenId(String openId, String provider) {
	OpenIdResourceDetails details = new OpenIdResourceDetails();
	details.setOpenId(openId);
	details.setProvider(provider);
	details.setAccessTokenUri(this.properties.getAccessTokenUri());
	details.setClientId(this.properties.getClientId());
	details.setClientSecret(this.properties.getClientSecret());
	OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(details);
	auth2RestTemplate.setAccessTokenProvider(new OpenIdAccessTokenProvider());
	return auth2RestTemplate.getAccessToken();
}
 
Example 20
Source Project: cola   Source File: SsoAuthClient.java    License: MIT License 5 votes vote down vote up
/**
 * 短信登录
 *
 * @param phoneNumber 手机号码
 * @param credential  验证码
 * @return
 */
public OAuth2AccessToken loginBySms(String phoneNumber, String credential) {
	SmsResourceDetails details = new SmsResourceDetails();
	details.setPhoneNumber(phoneNumber);
	details.setCredential(credential);
	details.setAccessTokenUri(this.properties.getAccessTokenUri());
	details.setClientId(this.properties.getClientId());
	details.setClientSecret(this.properties.getClientSecret());
	OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(details);
	auth2RestTemplate.setAccessTokenProvider(new SmsAccessTokenProvider());
	return auth2RestTemplate.getAccessToken();
}
 
Example 21
@Bean
public UserInfoRestTemplateCustomizer retryLoadBalancedUserInfoRestTemplateCustomizer(
		final RetryLoadBalancerInterceptor loadBalancerInterceptor) {
	return new UserInfoRestTemplateCustomizer() {
		@Override
		public void customize(OAuth2RestTemplate restTemplate) {
			List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
					restTemplate.getInterceptors());
			interceptors.add(loadBalancerInterceptor);
			restTemplate.setInterceptors(interceptors);
		}
	};
}
 
Example 22
@Autowired
public VaultTokenRenewalAutoConfiguration(
		ConfigClientOAuth2ResourceDetails configClientOAuth2ResourceDetails,
		ConfigClientProperties configClientProps,
		@Value("${spring.cloud.config.token}") String vaultToken,
		@Value("${vault.token.ttl:300000}") long renewTTL) { // <-- Default to a 300 second (5 minute) TTL
	this.rest = new OAuth2RestTemplate(configClientOAuth2ResourceDetails);
	this.refreshUri = configClientProps.getUri()[0] + "/vault/v1/auth/token/renew-self";
	long renewTTLInMS = renewTTL / 1000; // convert to seconds, since that's what Vault wants
	this.request = buildTokenRenewRequest(vaultToken, renewTTLInMS);
	this.obscuredToken = vaultToken.substring(0, 4) + "[*]" + vaultToken.substring(vaultToken.length() - 4);
	this.renewTTL = renewTTL;
}
 
Example 23
Source Project: spring-cloud-shop   Source File: ExecuteHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void execute(final String jobName, final String jobGroup) {

    // 1. 获取数据库执行的job任务
    JobInfoMapper jobInfoMapper = ShopSpringContext.getBean(JobInfoMapper.class);
    JobInfo jobInfo = new JobInfo();
    jobInfo.setJobName(jobName);
    jobInfo.setJobStatus(JobStatusEnums.NORMAL.getCode());
    JobInfo selectJobInfo = jobInfoMapper.selectOne(new QueryWrapper<>(jobInfo));
    // 访问的资源请求地址
    if (Objects.nonNull(selectJobInfo)) {
        Map<String, String> paramMap = new ConcurrentHashMap<>();
        String url = "http://" + selectJobInfo.getServiceName() + selectJobInfo.getServiceMethod();
        if (!StringUtils.isEmpty(selectJobInfo.getParams())) {
            paramMap.putAll(JSON.parseObject(selectJobInfo.getParams(), Map.class));
        }
        OAuth2RestTemplate template = ShopSpringContext.getBean(OAuth2RestTemplate.class);
        // 得到服务鉴权访问token
        OAuth2AccessToken accessToken = template.getAccessToken();
        // 设置请求消息头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setBearerAuth(accessToken.toString());
        // 得到 RestTemplate 访问的负载均衡对象
        RestTemplate restTemplate = ShopSpringContext.getBean("restTemplate", RestTemplate.class);
        ResponseEntity<Object> responseEntity = restTemplate.postForEntity(url, new HttpEntity<>(paramMap, headers), Object.class);
        log.info("执行服务调用结束,返回结果 result = {}", JSON.toJSONString(responseEntity));
    } else {
        log.error("未找到执行的定时任务 jobName = {}, jobGroup = {}", jobName, jobGroup);
    }
}
 
Example 24
@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 25
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 26
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 27
@Test
public void testAccessSecurityInfoUrlWithOAuth2AccessTokenPasswordGrant2Times() throws Exception {

	final ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
	resourceDetails.setClientId("myclient");
	resourceDetails.setClientSecret("mysecret");
	resourceDetails.setUsername("user");
	resourceDetails.setPassword("secret10");
	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("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print())
			.andExpect(status().isOk())
			.andExpect(jsonPath("$.authenticated", is(Boolean.TRUE)))
			.andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE)))
			.andExpect(jsonPath("$.roles", hasSize(7)));

	localDataflowResource.getMockMvc()
			.perform(get("/security/info").header("Authorization", "bearer " + accessTokenAsString)).andDo(print())
			.andExpect(status().isOk())
			.andExpect(jsonPath("$.authenticated", is(Boolean.TRUE)))
			.andExpect(jsonPath("$.authenticationEnabled", is(Boolean.TRUE)))
			.andExpect(jsonPath("$.roles", hasSize(7)));
}
 
Example 28
public OAuth2AccessToken load(TokenRequestDto requestDto) {
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource);
    restTemplate.setAccessTokenProvider(tokenProvider);
    if (requestDto.getCode() != null) {
        AccessTokenRequest tokenRequest = restTemplate.getOAuth2ClientContext().getAccessTokenRequest();
        tokenRequest.setCurrentUri(requestDto.getRedirectUri());
        tokenRequest.setAuthorizationCode(requestDto.getCode());
    }
    try {
        return restTemplate.getAccessToken();
    } catch (OAuth2Exception e) {
        throw new BadCredentialsException("Could not obtain access token", e);
    }
}
 
Example 29
@Test
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
    ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
    OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);

    OAuth2AccessToken accessToken = restTemplate.getAccessToken();

    assertNotNull(accessToken);
}
 
Example 30
@Autowired
public OrderServiceV1(OrderRepository orderRepository,
                      OrderEventRepository orderEventRepository,
                      @LoadBalanced OAuth2RestTemplate oAuth2RestTemplate) {
    this.orderRepository = orderRepository;
    this.orderEventRepository = orderEventRepository;
    this.oAuth2RestTemplate = oAuth2RestTemplate;
}