Updating the integration test

We will now update our integration test in order to provide the OAuth2 credentials. The following test highlights the important changes:

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;
}

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 OAuth2 protocol.

The following code shows the updated test using the getOAuthTemplate method:

@Test
public void welcome() throws Exception {
ResponseEntity < String > response = getOAuthTemplate()
.getForEntity(createURL("/welcome"), String.class);
// ResponseEntity<String> response = template.getForEntity("/welcome",
// String.class);
assertThat(response.getBody(), equalTo("Hello World"));
}

Similar changes are needed in all other tests.

Spring Boot and Spring Security make it easy to implement OAuth2. In this quick section, we enabled our users to grant access to their Todo data to third-party applications, by implementing OAuth2 with Spring Boot and Spring Security.

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

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