Skip to content

Instantly share code, notes, and snippets.

@santoshmanya
Created March 6, 2017 23:35
Show Gist options
  • Save santoshmanya/81fde19906e6510cf6dffc02191aa42b to your computer and use it in GitHub Desktop.
Save santoshmanya/81fde19906e6510cf6dffc02191aa42b to your computer and use it in GitHub Desktop.
Oauth2RestTemplate example - this goes with the spring boot rest oauth example project (https://github.com/royclarkson/spring-rest-service-oauth) but the Greeting class needs to have setters and a default constructor.
package hello;
public class Greeting {
private long id;
private String content;
public Greeting(){}
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
public void setId(long id) {
this.id = id;
}
public void setContent(String content) {
this.content = content;
}
}
package hello;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static java.lang.String.format;
import static java.util.Arrays.asList;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class RestTemplateTest {
@Value("${local.server.port}")
protected int port;
@Test
public void clientAccess() {
ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setUsername("roy");
resourceDetails.setPassword("spring");
resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port));
resourceDetails.setClientId("clientapp");
resourceDetails.setClientSecret("123456");
resourceDetails.setGrantType("password");
resourceDetails.setScope(asList("read", "write"));
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);
restTemplate.setMessageConverters(asList(new MappingJackson2HttpMessageConverter()));
final Greeting greeting = restTemplate.getForObject(format("http://localhost:%d/greeting", port), Greeting.class);
System.out.println(greeting);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment