Wednesday, December 18, 2013

[Code Snippet] Exchange SAML2 Token to an OAuth Token via HTTPClient & parse JWT using Gson


...

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import com.google.gson.Gson;

...

private String exchangeSAMLTokenToOAuthToken(HttpServletRequest request, HttpServletResponse response) throws IOException{
  
 String clientId = properties.getProperty("OAuth.client.id");
 String clientSecret = properties.getProperty("OAuth.client.secret");
 String oauthTokenEndpoint = properties.getProperty("OAuth.token.endpoint");

 HttpClient httpclient = new HttpClient();
 httpclient.getParams().setAuthenticationPreemptive(true);
 Credentials defaultcreds = new UsernamePasswordCredentials(clientId, clientSecret);
 httpclient.getState().setCredentials(AuthScope.ANY, defaultcreds);

 PostMethod post = new PostMethod(oauthTokenEndpoint);
 post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
 post.addParameter("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer");
 post.addParameter("assertion", samlAssertion);
  
 try {
  httpclient.executeMethod(post);
  System.out.println("Response from OAuth Token endpoint: ");
  System.out.println(post.getResponseBodyAsString());
  Map jsonJavaRootObject = new Gson().fromJson(post.getResponseBodyAsString(), Map.class);
  return (String)jsonJavaRootObject.get("access_token");
 } catch (Exception e) {
  e.printStackTrace();
 } finally {
  post.releaseConnection();
 }

 return null;
}

No comments: