Difference between revisions of "Java client example using OAuth2"
From DarkWiki
(→Maven pom.xml) |
(→Java client) |
||
| (11 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
This example shows how to make a RESTful call using OAuth2 from Spring. | This example shows how to make a RESTful call using OAuth2 from Spring. | ||
| − | |||
| − | |||
==The code== | ==The code== | ||
| Line 24: | Line 22: | ||
<artifactId>spring-security-oauth2</artifactId> | <artifactId>spring-security-oauth2</artifactId> | ||
<version>2.0.9.RELEASE</version> | <version>2.0.9.RELEASE</version> | ||
| + | </dependency> | ||
| + | |||
| + | <dependency> | ||
| + | <groupId>org.springframework</groupId> | ||
| + | <artifactId>spring-web</artifactId> | ||
| + | <version>4.2.5.RELEASE</version> | ||
| + | </dependency> | ||
| + | |||
| + | <dependency> | ||
| + | <groupId>com.fasterxml.jackson.core</groupId> | ||
| + | <artifactId>jackson-databind</artifactId> | ||
| + | <version>2.7.3</version> | ||
</dependency> | </dependency> | ||
| Line 41: | Line 51: | ||
package org.darkmine.demo.oauth; | package org.darkmine.demo.oauth; | ||
| + | import org.springframework.http.HttpStatus; | ||
import org.springframework.http.ResponseEntity; | import org.springframework.http.ResponseEntity; | ||
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; | import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; | ||
| Line 58: | Line 69: | ||
String clientId = "CLIENT_ID"; | String clientId = "CLIENT_ID"; | ||
String clientSecret = "<SUPER_SECRET_CODE>"; | String clientSecret = "<SUPER_SECRET_CODE>"; | ||
| − | |||
// Prepare the credentials resource. | // Prepare the credentials resource. | ||
| Line 66: | Line 76: | ||
resourceDetails.setClientId(clientId); | resourceDetails.setClientId(clientId); | ||
resourceDetails.setGrantType( "client_credentials" ); | resourceDetails.setGrantType( "client_credentials" ); | ||
| − | resourceDetails.setAccessTokenUri( url | + | resourceDetails.setAccessTokenUri( "https://www.myprogram.url/oauth"); |
// Prepare our template and context (although the context isn't really needed in this example). | // Prepare our template and context (although the context isn't really needed in this example). | ||
| Line 74: | Line 84: | ||
oAuthRestTemplate.setAuthenticator( new BearerAuthenticator() ); | oAuthRestTemplate.setAuthenticator( new BearerAuthenticator() ); | ||
| − | // | + | // Pre-fetch an access token. This isn't strictly necessary as the RestTemplate handles it for us (along with refreshing after token expiry). |
System.out.println( "AccessToken: " + oAuthRestTemplate.getAccessToken() ); | System.out.println( "AccessToken: " + oAuthRestTemplate.getAccessToken() ); | ||
| Line 80: | Line 90: | ||
// Prepare our RESTful URL | // Prepare our RESTful URL | ||
| − | UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( url | + | UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( "https://www.myprogram.url/people"); |
builder.queryParam( "countrycode" , "GBR" ); | builder.queryParam( "countrycode" , "GBR" ); | ||
// Make our API call. | // Make our API call. | ||
| − | ResponseEntity<Person[]> | + | ResponseEntity<Person[]> callResponse = oAuthRestTemplate.getForEntity( builder.build().toUri() , Person[].class ); |
| + | |||
| + | // Do something with the results | ||
| + | if( callResponse.getStatusCode() == HttpStatus.OK ) { | ||
| + | for( Person person : callResponse.getBody() { | ||
| + | System.out.println( person.toString() ); | ||
| + | } | ||
| + | } else { | ||
| + | System.err.println( "Failed!" ); | ||
| + | } | ||
} | } | ||
| Line 92: | Line 111: | ||
</source> | </source> | ||
| − | This second class is used to get around a bug with some servers where the server said it supported a token_type of "bearer", but actually only supported "Bearer". Therefore we implement our own OAuth2RequestAuthenticator. | + | This second class is used to get around a bug with some servers where the server said it supported a <code>token_type</code> of "bearer", but actually only supported "Bearer". Therefore we implement our own <code>OAuth2RequestAuthenticator</code>. Lastly, setting the content-type here is not strictly necessary. |
| − | |||
| − | Lastly, setting the content-type here is not strictly necessary. | ||
<source lang="java"> | <source lang="java"> | ||
| Line 110: | Line 127: | ||
public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext,ClientHttpRequest request) { | public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext,ClientHttpRequest request) { | ||
request.getHeaders().set( "Authorization" , "Bearer " + clientContext.getAccessToken() ); | request.getHeaders().set( "Authorization" , "Bearer " + clientContext.getAccessToken() ); | ||
| − | |||
} | } | ||
} | } | ||
</source> | </source> | ||
Latest revision as of 11:36, 12 April 2016
This example shows how to make a RESTful call using OAuth2 from Spring.
The code
Maven pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>darkmine</groupId>
<artifactId>darkmine-oauth2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
...
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.3</version>
</dependency>
...
</dependencies>
</project>
Java client
Main program.
package org.darkmine.demo.oauth;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.web.util.UriComponentsBuilder;
import org.darkmine.demo.oauth.dto.Person;
import org.darkmine.demo.oauth.BearerAuthenticator;
public class OAuth2Demo {
public static void main(String[] args) {
// Setup
String clientId = "CLIENT_ID";
String clientSecret = "<SUPER_SECRET_CODE>";
// Prepare the credentials resource.
ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
resourceDetails.setClientSecret(clientSecret);
resourceDetails.setClientId(clientId);
resourceDetails.setGrantType( "client_credentials" );
resourceDetails.setAccessTokenUri( "https://www.myprogram.url/oauth");
// Prepare our template and context (although the context isn't really needed in this example).
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
OAuth2RestTemplate oAuthRestTemplate = new OAuth2RestTemplate(resourceDetails,clientContext);
oAuthRestTemplate.setAuthenticator( new BearerAuthenticator() );
// Pre-fetch an access token. This isn't strictly necessary as the RestTemplate handles it for us (along with refreshing after token expiry).
System.out.println( "AccessToken: " + oAuthRestTemplate.getAccessToken() );
// Prepare our RESTful URL
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( "https://www.myprogram.url/people");
builder.queryParam( "countrycode" , "GBR" );
// Make our API call.
ResponseEntity<Person[]> callResponse = oAuthRestTemplate.getForEntity( builder.build().toUri() , Person[].class );
// Do something with the results
if( callResponse.getStatusCode() == HttpStatus.OK ) {
for( Person person : callResponse.getBody() {
System.out.println( person.toString() );
}
} else {
System.err.println( "Failed!" );
}
}
}
This second class is used to get around a bug with some servers where the server said it supported a token_type of "bearer", but actually only supported "Bearer". Therefore we implement our own OAuth2RequestAuthenticator. Lastly, setting the content-type here is not strictly necessary.
package org.darkmine.demo.oauth;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RequestAuthenticator;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
public class BearerAuthenticator implements OAuth2RequestAuthenticator {
@Override
public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext,ClientHttpRequest request) {
request.getHeaders().set( "Authorization" , "Bearer " + clientContext.getAccessToken() );
}
}