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

The following examples show how to use org.springframework.security.oauth2.client.OAuth2RestTemplate. 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: DataFlowClientAutoConfigurationAgaintstServerTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: OAuth2Util.java    From DAFramework with 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 #3
Source File: Oauth2ClientRestTemplate.java    From spring-boot with 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 #4
Source File: Oauth2ClientRestTemplate.java    From spring-boot with 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 #5
Source File: ApplicationTests.java    From Microservices-Building-Scalable-Software with MIT License 6 votes vote down vote up
@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 #6
Source File: ApplicationTests.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@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 #7
Source File: SpringSecurityConfiguration.java    From crnk-example with 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 #8
Source File: LocalServerSecurityWithOAuth2Tests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@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 File: OAuth2RestTemplateConfigurer.java    From spring-oauth2-keycloak-connector with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: Oauth2ClientRestTemplateTest.java    From spring-boot with 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 #11
Source File: Oauth2ClientRestTemplate.java    From spring-boot with 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 #12
Source File: JavaConfig.java    From Spring-Security-Third-Edition with 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 #13
Source File: DefaultUserInfoRestTemplateFactory.java    From spring-security-oauth2-boot with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: OAuth2ClientTest.java    From Spring-Security-Third-Edition with 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 #15
Source File: TestControllerTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
@DisplayName("ROLE_ADMIN 角色测试")
void testAdminRoleSucceedAndTestRoleFailedWhenPassed() {
    OAuth2RestTemplate template = oauth2RestTemplate("admin", "123456", Collections.singletonList("READ"));
    ResponseEntity<String> response = template.exchange(URL + "/admin", GET, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("ADMIN", response.getBody());
    assertThrows(OAuth2AccessDeniedException.class,
        () -> template.exchange(URL + "/test", GET, null, String.class));
}
 
Example #16
Source File: FacebookConfiguration.java    From OAuth-2.0-Cookbook with 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 #17
Source File: OAuth2ClientTest.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
public void execute_post_to_tokenUrl()
        throws ClientProtocolException, IOException {

    OAuth2RestTemplate template = template();

    ResponseEntity<String> response = template.exchange(
            tokenUrl,
            HttpMethod.POST,
            null,
            String.class);

    assertThat(response.getStatusCode().value(), equalTo(200));
}
 
Example #18
Source File: GoogleConfiguration.java    From OAuth-2.0-Cookbook with 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 #19
Source File: OAuth2TokenRequestFilter.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
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 #20
Source File: CustomConfigAuthorizationServerIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
    ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
    OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);

    OAuth2AccessToken accessToken = restTemplate.getAccessToken();

    assertNotNull(accessToken);
}
 
Example #21
Source File: OrderServiceV1.java    From spring-cloud-event-sourcing-example with GNU General Public License v3.0 5 votes vote down vote up
@Autowired
public OrderServiceV1(OrderRepository orderRepository,
                      OrderEventRepository orderEventRepository,
                      @LoadBalanced OAuth2RestTemplate oAuth2RestTemplate) {
    this.orderRepository = orderRepository;
    this.orderEventRepository = orderEventRepository;
    this.oAuth2RestTemplate = oAuth2RestTemplate;
}
 
Example #22
Source File: LocalServerSecurityWithOAuth2Tests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@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 #23
Source File: TestControllerTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
@DisplayName("SCOPE_WRITE 授权域测试")
void testScopeWriteWhenPassed() {
    OAuth2RestTemplate template = oauth2RestTemplate("admin", "123456", Collections.singletonList("WRITE"));
    ResponseEntity<String> response = template.exchange(URL + "/write", GET, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("WRITE", response.getBody());
    assertThrows(OAuth2AccessDeniedException.class,
        () -> template.exchange(URL + "/read", GET, null, String.class));
}
 
Example #24
Source File: TestControllerTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
@DisplayName("SCOPE 测试")
void testScopeWhenPassed() {
    OAuth2RestTemplate template = oauth2RestTemplate("admin", "123456", Arrays.asList("READ", "WRITE"));
    ResponseEntity<String> writeResponse = template.exchange(URL + "/write", GET, null, String.class);
    assertEquals(HttpStatus.OK, writeResponse.getStatusCode());
    assertEquals("WRITE", writeResponse.getBody());
    ResponseEntity<String> readResponse = template.exchange(URL + "/read", GET, null, String.class);
    assertEquals(HttpStatus.OK, readResponse.getStatusCode());
    assertEquals("READ", readResponse.getBody());
}
 
Example #25
Source File: ShoppingCartServiceV1.java    From spring-cloud-event-sourcing-example with GNU General Public License v3.0 5 votes vote down vote up
@Autowired
public ShoppingCartServiceV1(CartEventRepository cartEventRepository,
                             @LoadBalanced OAuth2RestTemplate oAuth2RestTemplate,
                             @LoadBalanced RestTemplate normalRestTemplate) {
    this.cartEventRepository = cartEventRepository;
    this.oAuth2RestTemplate = oAuth2RestTemplate;
    this.restTemplate = normalRestTemplate;
}
 
Example #26
Source File: UserInfoTokenServicesRefreshTokenTests.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: OAuth2LoadBalancerClientAutoConfiguration.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Bean
public UserInfoRestTemplateCustomizer loadBalancedUserInfoRestTemplateCustomizer(
		final LoadBalancerInterceptor loadBalancerInterceptor) {
	return new UserInfoRestTemplateCustomizer() {
		@Override
		public void customize(OAuth2RestTemplate restTemplate) {
			List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
					restTemplate.getInterceptors());
			interceptors.add(loadBalancerInterceptor);
			restTemplate.setInterceptors(interceptors);
		}
	};
}
 
Example #28
Source File: CustomConfigAuthorizationServerIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = OAuth2AccessDeniedException.class)
public void givenOAuth2Context_whenAccessTokenIsRequestedWithInvalidException_ThenExceptionIsThrown() {
    ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("write"));
    OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);

    restTemplate.getAccessToken();
}
 
Example #29
Source File: CustomConfigAuthorizationServerIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() {
    ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write"));
    OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);

    OAuth2AccessToken accessToken = restTemplate.getAccessToken();

    assertNotNull(accessToken);
}
 
Example #30
Source File: TestControllerTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
@DisplayName("SCOPE_READ 授权域测试")
void testScopeReadWhenPassed() {
    OAuth2RestTemplate template = oauth2RestTemplate("admin", "123456", Collections.singletonList("READ"));
    ResponseEntity<String> response = template.exchange(URL + "/read", GET, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("READ", response.getBody());
    assertThrows(OAuth2AccessDeniedException.class,
        () -> template.exchange(URL + "/write", GET, null, String.class));
}