Integration test

We will now update our integration test to provide the OAuth 2 credentials. The following test highlights the important details:

    @Test
public void retrieveTodos() throws Exception {
String expected = "["
+ "{id:1,user:Jack,desc:"Learn Spring MVC",done:false}" + ","
+"{id:2,user:Jack,desc:"Learn Struts",done:false}" + "]";
String uri = "/users/Jack/todos";
ResourceOwnerPasswordResourceDetails resource =
new ResourceOwnerPasswordResourceDetails();
resource.setUsername("user-name");
resource.setPassword("user-password");
resource.setAccessTokenUri(createUrl("/oauth/token"));
resource.setClientId("clientId");
resource.setClientSecret("clientSecret");
resource.setGrantType("password");
OAuth2RestTemplate oauthTemplate = new
OAuth2RestTemplate(resource,new
DefaultOAuth2ClientContext());
ResponseEntity<String> response =
oauthTemplate.getForEntity(createUrl(uri), String.class);
JSONAssert.assertEquals(expected, response.getBody(), false);
}

Some important things to note are as follows:

  • ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails(): We set up ResourceOwnerPasswordResourceDetails with the user credentials and the client credentials
  • resource.setAccessTokenUri(createUrl("/oauth/token")): Configures the URL of the authentication server
  • OAuth2RestTemplate oauthTemplate = new OAuth2RestTemplate(resource,new DefaultOAuth2ClientContext()): OAuth2RestTemplate is an extension of RestTemplate, which supports the OAuth 2 protocol

In this section, we looked at how to enable OAuth 2 authentication in our resources.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset