developing an ibm smartcloud for social business...

21
Developing an IBM SmartCloud for Social Business application Jason Blakely , Advisory Software Engineer, IBM March 2012 © Copyright International Business Machines Corporation 2012. All rights reserved. Summary: Learn how to develop an application that integrates with IBM SmartCloud for Social Business by authenticating/authorizing via the Open Authorization protocol, calling the SmartCloud for Social Business service APIs to do a useful task, and extending the UI to show an integrated look. A sample Web application is used as the primary tool to illustrate the required steps to integrate with IBM's premier cloud offering. Table of Contents 1 Introduction...............................................................................................................................2 1.1 Sample application.............................................................................................................2 1.2 Prerequisites and overview................................................................................................2 2 Authentication/Authorization.....................................................................................................3 2.1 OAuth Version 1.0a protocol flow scenario........................................................................3 2.2 Detailed steps for OAuth version 1.0a................................................................................4 2.3 OAuth version 2.0 protocol flow scenario.........................................................................11 2.4 Detailed steps for OAuth version 2.0................................................................................11 3 APIs........................................................................................................................................18 4 UI extensions..........................................................................................................................19 5 Conclusion..............................................................................................................................20 6 Resources...............................................................................................................................21 7 Author bio...............................................................................................................................21 1

Upload: others

Post on 09-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

Developing an IBM SmartCloud for Social Business application

Jason Blakely, Advisory Software Engineer, IBM

March 2012

© Copyright International Business Machines Corporation 2012. All rights reserved.

Summary: Learn how to develop an application that integrates with IBM SmartCloud for Social Business by authenticating/authorizing via the Open Authorization protocol, calling the SmartCloud for Social Business service APIs to do a useful task, and extending the UI to show an integrated look. A sample Web application is used as the primary tool to illustrate the required steps to integrate with IBM's premier cloud offering.

Table of Contents1 Introduction...............................................................................................................................2

1.1 Sample application.............................................................................................................21.2 Prerequisites and overview................................................................................................2

2 Authentication/Authorization.....................................................................................................32.1 OAuth Version 1.0a protocol flow scenario........................................................................32.2 Detailed steps for OAuth version 1.0a................................................................................42.3 OAuth version 2.0 protocol flow scenario.........................................................................112.4 Detailed steps for OAuth version 2.0................................................................................11

3 APIs........................................................................................................................................184 UI extensions..........................................................................................................................195 Conclusion..............................................................................................................................206 Resources...............................................................................................................................217 Author bio...............................................................................................................................21

1

Page 2: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

1 IntroductionDo you want to develop an application that integrates with IBM® SmartCloudTM for Social Business but are unfamiliar with the process and requirements to do this? This article can help a developer become familiar with the process and the accompanying sample application provides a good, working example.

Source code is included to addresses a very common developer's request: “Show me the code”. This article follows, shows, and explains how the sample application accomplishes each step in the integration process.

The goal was to make the sample application as straightforward as possible to make it easier to comprehend. Also the sample application can be a good base to start developing your real-world application integrated with SmartCloud for Social Business.

1.1 Sample applicationThe sample application was designed as a teaching tool and we follow closely the application's implementation. Using a working application along with concrete coding examples should enhance the understanding of the concepts; also, the application with source code should help speed development either as a quick prototype or as a foundation for a more advanced application.

The sample Web application first authenticates/authorizes with SmartCloud for Social Business using Open Authorization (OAuth) protocol. The protocol is broken down into individual steps, and each step is displayed as a Web page to highlight and clarify that step. Of course, these visual steps are a teaching aid and would not normally be presented (a switch can hide these steps).

Then a main page is shown that allows the user to try a sampling of integration points, one from each of the major SmartCloud for Social Business component apps. Each point consists of initiating a call to the local server that will invoke a SmartCloud REST API and then display the results back to the client browser. The main page also has non-API integration points like the navigation bar and user interface (UI) extensions that help the integration look and feel.

NOTE: During the writing of this paper, a branding transition from LotusLive to IBM SmartCloud for Social Business was in progress. The URLs referred to in this article and used in the sample application will change in the future. The current URLs will slowly transition to the new URLs, where first they will coexist, and then finally the current URLs will be deprecated. It is advised to keep this in mind when developing an application.

1.2 Prerequisites and overviewThis article is intended for software developers wanting to better understand how to develop an application that integrates with SmartCloud for Social Business. To get the most from this article you should have a good understanding of Java™ programming and familiarity with J2EE technology and Web programming (for example, JavaScript, HTML).

SmartCloud for Social Business uses Open Authorization (OAuth) protocol for authorization, and the service API may return data in JavaScript Object Notation (JSON), XML (CMIS) formats.

2

Page 3: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

The sample application uses Java Servlets and Java Server Pages (JSP) and can run on a Tomcat server for easy deployment and testing. SmartCloud for Social Business offers free trial accounts that can be used as the target for the sample.

NOTE: Tomcat will need some configuration to enable SSL.

Other technologies used by the sample application are:

● Apache Commons HttpClient● Apache Commons Codec● jQuery Core● Twitter Bootstrap

The sample application .zip file contains the following:

● Sample Web app in a deployable WAR file● Source files compatible with Eclipse● Readme file

Overall, the steps in the development process are to:

(1) obtain a free trial account if you do not already have a SmartCloud for Social Business account,

(2) decide which version of the OAuth protocol to use (SmartCloud for Social Business supports both version 1.0a and 2.0),

(3) register the application to obtain the initial OAuth credentials, (4) authenticate/authorize using OAuth, (5) use the authorized tokens to call SmartCloud for Social Business service APIs to do

something useful,(6) extend the UI to make the application have a more integrated look.

All this and more is documented in the IBM Social Development wiki. This white paper and the sample application were developed by following the wiki documentation.

2 Authentication/AuthorizationIBM SmartCloud for Social Business requires applications to have authorization before calling its APIs. SmartCloud for Social Business uses Open Authorization, which is an open protocol that provides a simple and standardized way to perform authorization securely for Web applications.

2.1 OAuth Version 1.0a protocol flow scenarioSuppose a user running a client application on an ISV's server wants to share a file on SmartCloud for Social Business (resource server). The server servicing the client application will need to call a service API on SmartCloud to share that file.

This requires the resource owner to grant authorization to access the file and share it, but the owner does not want to share the resource server's log-in ID and password with the client or the ISV's server.

3

Page 4: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

The OAuth protocol was designed to securely handle this authorization process, whereby the credentials generated by SmartCloud for Social Business when registering an application are used to initiate the protocol flow:

1. The initial request is sent to SmartCloud for Social Business asking for a pair of temporary credentials that will be used to continue the flow; the resource server validates the request data and returns the credentials (request token and request token secret).

2. Next, the client redirects the user agent (browser) to the resource server's authorization URL, using the just-returned temporary credentials, and awaits a callback when the resource owner grants authority (or not).

3. The resource server authorization endpoint asks the resource owner to log in and approve the access to the resource. Note that the client app never sees the resource owner's log-in ID or password.

4. Upon approval, the resource server redirects the user agent to the client's URL with a verifier code. The callback URL was supplied in the client's initial request. The client requests from the resource server a final set of temporary credentials (access token and access token secret).

5. Finally the client calls the resource server's service API to share the file, using the last set of credentials.

2.2 Detailed steps for OAuth version 1.0aIn this section we explain the details involved in the OAuth authorization flow and the following service call steps (see figure 1):

1. Register your application 2. Get a Request token3. Obtain Authorization4. Get the Access token5. Make the service API call

4

Page 5: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

Figure 1. Graphical representation of the V1.0a detailed steps

2.2.1 Register the application The first step is to register the application with SmartCloud for Social Business. The registration provides the consumer key and consumer secret that will be used in the the next step of the process. Note that you must have administrative rights to register an application.

2.2.2 Get the request tokenStep 2 is the initial request to the resource server and is the first real coding step that sends a request for a temporary credential (request token).

Listing 1 shows the code, the highlights of which are: build the Authorization parameter value, call a HTTP Post method (Get method is also acceptable), and save the returned credentials (access token and access token secret).

See the comment block for the format of the Authorization parameter.

NOTE: ". . ." denotes one or more lines that, for brevity, are not listed.

5

Page 6: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

Listing 1. Oauth1Handler.java – step2_getRequestToken( ) /** * Get a Request token from the resource server by sending a HTTP post call * * Http call has the following data format: * POST /manage/oauth/getRequestToken HTTP/1.1 * Host: <lotuslive> * Authorization: OAuth * oauth_consumer_key="<con key>", * oauth_signature="<signature>" * oauth_signature_method="PLAINTEXT", * oauth_timestamp="<timestamp>", * oauth_nonce="<nonce>", * oauth_version="1.0", * oauth_callback="<callback url>". . .public void step2_getRequestToken() throws Exception {. . .int responseCode = HttpStatus.SC_OK;String responseBody = null;try { HttpClient client = new HttpClient(); HttpState initialState = new HttpState(); client.setState(initialState); String url = getServerUrl() + LLProperties.getProperty("RequestTokenUrl_v1"); method = new PostMethod(url); method.setRequestHeader("Content-Type", LLConstants.FORM_URLENCODED); method.setParameter(LLConstants.CONSUMER_KEY, key); method.setParameter(LLConstants.SIGNATURE, buildSignature(secret, "")); method.setParameter(LLConstants.SIGNATURE_METHOD, LLConstants.PLAINTEXT_SIGNATURE); method.setParameter(LLConstants.TIMESTAMP, getTimestamp()); method.setParameter(LLConstants.NONCE, getNonce()); method.setParameter(LLConstants.VERSION, LLConstants.OAUTH_VERSION1); method.setParameter(LLConstants.CALLBACK, callBackUrl); responseCode = client.executeMethod(method); responseBody = method.getResponseBodyAsString();. . .} finally { if (method != null) method.releaseConnection();}. . . requestToken = getToken(responseBody); requestTokenSecret = getTokenSecret(responseBody);. . .

Notice the signature method is plain text because of the secure transport, which makes generating a signature quite simple (see listing 2).

6

Page 7: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

Listing 2. Oauth1Handler.java – buildSignature( ) /** * Generates a PLAINTEXT signature which simply concats the values with * a '&' sandwiched in the middle. * * @param consumerSecret * @param tokenSecret * @return */private static String buildSignature(String consumerSecret, String tokenSecret){

return consumerSecret + "&" + tokenSecret;} 2.2.3 Obtain authorization Step 3 is fairly simple, involving merely redirecting the user agent to the the resource server's authorization endpoint and handling the callback. Remember that the callback URL was part of the data sent in the initial post HTTP call. See listing 3, which uses a JSP to do the redirect, and listing 3b, which uses a Servlet to do the redirect.

Listing 3. Step3_A1_GetAuthorization.jsp . . .<form action='<%=oAuthHandler.getServerUrl() + LLProperties.getProperty("AuthorizeUrl_v1")%>?oauth_token= <=oAuthHandler.getRequestToken()%>' method="post"> <div> <input value="AuthorizeToken" type="submit" class="btn primary" /> </div></form>. . .

Listing 3b. SilentOAuthFlowServlet.java -- doGet( ). . .oAuthHandler.doPreAuthorizationFlow();response.sendRedirect(oAuthHandler.getAuthorizationUrl());. . .

The sample app uses a JSP to display the step before redirecting (part of the visual, step-by- step developer mode) and uses a servlet to do the step in the background. Listing 4 shows the callback Servlet code that handles the returned token (verifier code).

Listing 4. Step3_A1_obtainAuthorizationServlet.java -- doGet( ). . .String requestToken = (String) request.getParameter(LLConstants.OAUTH_TOKEN);String errorCode = (String) request.getParameter(LLConstants.OAUTH_ERROR);HttpSession session = request.getSession();OAuth1Handler oAuthHandler = (Oauth1Handler)request.getSession(). getAttribute(LLConstants.OAUTH_HANDLER);if (oAuthHandler==null || LLConstants.OAUTH_DENIED.equals(errorCode) || !oAuthHandler.isSameRequestToken(requestToken)) { response.sendRedirect("redirect.html"); return;}

7

Page 8: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

oAuthHandler.setVerifierCode((String) request.getParameter(LLConstants.OAUTH_VERIFIER));. . .

Figure 2 shows the Authorization page where the resource owner can grant the access; note the registered application's name (SBTKDeveloperApp, for this example).

Figure 2. Resource server's Authorization grant page

2.3.4 Get the access tokenThe previous steps were about getting authorization to a resource; the server has marked the request token as authorized and associated it with the specific resource, owner, and verification code. Now in Step 4, it's time to get the credential that allows the actual access to the resource, naturally called the access token.

Listing 5 shows the code, the highlights of which are: build the Authorization parameter; call an Http Post method (Get method is also acceptable); and save the returned credentials, access token, and access token secret. Refer to the comment block for the format of the Authorization parameter.

Listing 5. Oauth1Handler.java – step4_getAccessToken( ). . ./** * Get an Access token from the resource server with a HTTP Post call * * Http call has the following format: * * POST /token HTTP/1.1 * Host: lotuslive * Authorization: OAuth * oauth_consumer_key="<con key>", * oauth_token="<request token>", * oauth_signature="<signature>" * oauth_signature_method="PLAINTEXT", * oauth_timestamp="<timestamp>", * oauth_nonce="<nonce>",

8

Page 9: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

* oauth_verifier="<verifier code>", * oauth_version="1.0", . . . int responseCode = HttpStatus.SC_OK; String responseBody = null; try { HttpClient client = new HttpClient(); HttpState initialState = new HttpState(); client.setState(initialState); String url = getServerUrl() + LLProperties.getProperty("RequestTokenUrl_v1"); method = new PostMethod(url); method.setRequestHeader("Content-Type", LLConstants.FORM_URLENCODED); method.setParameter(LLConstants.CONSUMER_KEY, key); method.setParameter(LLConstants.SIGNATURE, buildSignature(secret, "")); method.setParameter(LLConstants.SIGNATURE_METHOD, LLConstants.PLAINTEXT_SIGNATURE); method.setParameter(LLConstants.TIMESTAMP, getTimestamp()); method.setParameter(LLConstants.NONCE, getNonce()); method.setParameter(LLConstants.VERSION, LLConstants.OAUTH_VERSION1); method.setParameter(LLConstants.CALLBACK, callBackUrl); responseCode = client.executeMethod(method); responseBody = method.getResponseBodyAsString(); . . . } finally { if (method != null) method.releaseConnection(); } . . .accessToken = getToken(responseBody);accessTokenSecret = getTokenSecret(responseBody); 2.2.5 Make the API call – get the resource In Step 5 we use the access token to make the service API call. The access token can be used multiple times until the token expires (default is about 8 hours), after which an Unauthorized status code (401) is returned with body text of “oauth_token_expired.” The expiration event requires the entire OAuth flow (steps 2 to 5) to be redone.

Listings 6, 7, and 8 show the code, the highlights of which are: get parameter values from the browser, build the URL, build the Authorization parameter, set up the method to build the CMIS XML data required by the ShareMyFile API, execute an Http Put method, and handle the response

Listing 6. ApiShareMyFiles.java – execute( ). . .fileId = (String) request.getParameter("fid");fileName = (String) request.getParameter("fname");acl = (String) request.getParameter("acl");emails = (String) request.getParameter("emails");summary = (String) request.getParameter("summary");String subId = (String) request.getSession().getAttribute("subscriberId");if (subId == null) { ApiRequest api = new ApiGetUserIdentity();

9

Page 10: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

api.execute(request, response); subId = ApiGetUserIdentity.getSubscriberId(api.getHttpResponse()); request.getSession().setAttribute("subscriberId", subId);}url = oAuthHandler.getServerUrl() + "/files/basic/cmis/repository/p!" + subId + "/acl/snx:file!" + fileId;httpRequest = new HttpPutRequest(url);httpRequest.setOAuthHeader(oAuthHandler.callApiStep_createAuthorizationHeader());setup();httpRequest.execute();setContentType(response);. . .

Listing 7. Oauth1Handler.java -- callApiStep_createAuthorizationHeader( ). . ./** * Step 5: Creates the Authorization header to be used by API call * * Creates the Authorization header - * Authorization: OAuth oauth_consumer_key="<consumer_key>", * oauth_token="<access_token>", * oauth_signature_method="PLAINTEXT", * oauth_signature="<access_token_secret_sig>", * oauth_timestamp="<timestamp>", * oauth_nonce="<nonce>", * oauth_version="1.0" */. . .StringBuilder authHdr = new StringBuilder(1024);authHdr.append("OAuth ");authHdr.append(LLConstants.CONSUMER_KEY).append("=\""). append(percentEncode(key)).append("\",");authHdr.append(LLConstants.OAUTH_TOKEN).append("=\""). append(percentEncode(accessToken)).append("\",");authHdr.append(LLConstants.SIGNATURE_METHOD).append("=\""). append(LLConstants.PLAINTEXT_SIGNATURE).append("\",");authHdr.append(LLConstants.SIGNATURE).append("=\""). append(percentEncode(buildSignature(secret, accessTokenSecret))).append("\",");authHdr.append(LLConstants.TIMESTAMP).append("=\""). append(percentEncode(getTimestamp())).append("\",");authHdr.append(LLConstants.NONCE).append("=\""). append(percentEncode(getNonce())).append("\",");authHdr.append(LLConstants.VERSION).append("=\""). append(LLConstants.OAUTH_VERSION1).append('"');

Listing 8. HttpPutRequest.java -- execute( ). . .HttpClient client;HttpState initialState;client = new HttpClient();initialState = new HttpState();

10

Page 11: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

client.setState(initialState);method.addRequestHeader("Authorization", this.getOAuthHeader());try { int statusCode = client.executeMethod(method); httpResponse.setStatusCode(statusCode); httpResponse.setResponseText(method.getResponseBodyAsString()); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { handleBadStatusCode(); } else { httpResponse.setContentType(method.getResponseHeader(LLConstants.CONTENT_TYPE)); }. . .

2.3 OAuth version 2.0 protocol flow scenarioA user running a client application on an ISV's server wants to share a file on SmartCloud for Social Business (resource server). The server servicing the client application will need to call a service API on SmartCloud to access the file and share it.

This requires the resource owner to grant authorization to access the file, but the owner does not want to share the resource server's log-in ID and password with the client or the ISV's server.

The OAuth protocol was designed to handle this process securely. The credentials generated by SmartCloud for Social Business when registering an application are used to initiate the protocol flow:

1. In the initial step, the client redirects the user agent (browser) to the resource server's authorization endpoint URL (often this is a separate authorization server), using credentials generated at application registration, and expects a callback when the resource owner grants authority (or not).

2. The resource server authorization endpoint validates the supplied parameters and then asks the resource owner to log in and approve the access to the resource. Note that the client app never sees the resource owner's log-in ID or password. The resource server upon approval redirects the user agent to the client's URL with an authorization code.

3. The callback URL was supplied during application registration (also supplied in the initial redirect). The client then requests from the resource server a final set of temporary credentials (access and refresh tokens).

4. Finally, the client calls the resource server's service API to share the file using the access token. The resource server again validates the request and responds to it. If the access token expires, the refresh token can be used to get a new access token. The refresh token is usually much longer lived than the access token, to support this renewal procedure.

2.4 Detailed steps for OAuth version 2.0OAuth version 2.0 was developed to simplify and improve on version 1.0. A few of the enhancements in version 2.0 are:

11

Page 12: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

• No signature is required. The complex cryptographic signature was a source of many failures on the generating client and validating server, and required additional libraries to handle it.

• Secure transport is required when exchanging tokens.• Should scale better with less steps and less state management (only one token for API

calls).• More clearly delineated specs on what parts are implemented by the resource server and

what parts can be implemented by a separate authorization server.

Similarities remain between OAuth 1.0a and 2.0 flows (2.0 is not backward compatible); however, to reduce confusion, the explanation of version 2.0 is kept separate, even though some redundancies arise (key differences are noted).

Here are the detailed steps for the OAuth 2.0 authorization flow and service calls (see figure 3; notice there is no Get request token step):

1. Register your application2. Obtain Authorization3. Get the Access token4. Make the service API call5. Get a new Access token (if expires), using the Refresh token

12

Page 13: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

Figure 3. Graphical representation of the V2.0 detailed steps

2.4.1 Register the applicationStep 1 is to register the application with SmartCloud for Social Business. The registration provides the client id and client consumer secret that will be used in the next step of the process.

A client callback URL is a required input for registration, and the the length of time that a resource grant is valid before it expires is settable. Administrative rights are needed to register an application.

2.4.2 Obtain authorization code Since there is no Get request token step, Step 2 is the first coding step. This step is similar to the V1.0 authorization step and is straightforward, involving merely redirecting the user agent to the the resource server's authorization endpoint (many sites use a separate authorization server) and then handling the callback.

13

Page 14: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

The callback URL is now part of the application registration, and part of the server's validation will ensure these match.

Listing 9 uses a JSP to do the redirect, and listing 9a uses a Servlet to do the redirect. The sample app uses a JSP to display the step of the flow before redirecting (part of the visual, step- by-step developer mode), using a Servlet to perform the step in the background.

NOTE: ". . ." denotes one or more lines that, for brevity, are not listed.

Listing 9. Step2_A2_GetAuthorizationCode.jsp. . .<form action="Step2_A2_obtainAuthorization" method="post"> <div> <input value="Get Auth Code" type="submit" class="btn primary " /> </div></form>. . .

Listing 9a. SilentOAuthFlowServlet.java -- doGet( ). . .oAuthHandler.doPreAuthorizationFlow();response.sendRedirect(oAuthHandler.getAuthorizationUrl());. . .

Listing 10 shows the callback Servlet code that handles the returned authorization code. The authorization page displayed by the authorization endpoint is unchanged from V1.0 (recall figure 2).

Listing 10. Step2_A2_obtainAuthorizationServlet.java -- doGet( ). . .OAuth2Handler oAuthHandler = (OAuth2Handler) session.getAttribute(LLConstants.OAUTH_HANDLER);String errorCode = (String) request.getParameter(LLConstants.OAUTH_ERROR);if (oAuthHandler == null || LLConstants.OAUTH_DENIED.equals(errorCode)) { response.sendRedirect("redirect.html"); return;}oAuthHandler.setAuthorization_code(request.getParameter("code"));. . .

2.4.3 Get the access tokenWith the authorization step done and the resource server saving the authorization state information, in Step 3 it's time to obtain the final set of credentials in the flow, access and refresh tokens. The access token is the credential that allows the actual access to the resource.

Listing 11 shows the code, the highlights of which are: build the Authorization parameter, call an Http Post method (Get method is also acceptable), and save the returned credentials. Refer to the comment block for the format of the Authorization parameter.

14

Page 15: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

Listing 11. Oauth1Handler.java – step4_getAccessToken( ). . ./** * Step 3: Exchange authorization code for access and refresh tokens. * * server URL -- https://apps.lotuslive.com/manage/oauth2/token * Authorization: OAuth * callback_uri="<callback_uri>", * client_secret="<client_secret>", * client_id="<client_id>", * grant_type="authorization_code", * code="<authorization_code>" * * Calls the server URL with Authorization header and gets back following values: * access_token, refresh_token, issued_on expires_in, token_type. . .GetMethod method = null;int responseCode = HttpStatus.SC_OK;String responseBody = null;try { HttpClient client = new HttpClient(); HttpState initialState = new HttpState(); client.setState(initialState); StringBuffer url = new StringBuffer(2048); url.append(getServerUrl()).append(LLProperties.getProperty("AccessTokenUrl_v2")).append("?"); url.append(LLConstants.OAUTH2_CALLBACK_URI).append('=') .append(URLEncoder.encode(client_uri, "UTF-8")); url.append('&'); url.append(LLConstants.OAUTH2_CLIENT_ID).append('=') .append(URLEncoder.encode(client_id, "UTF-8")); url.append('&'); url.append(LLConstants.OAUTH2_CLIENT_SECRET).append('=') .append(URLEncoder.encode(client_secret, "UTF-8")); url.append('&'); url.append(LLConstants.OAUTH2_GRANT_TYPE).append('=') .append(LLConstants.OAUTH2_AUTHORIZATION_CODE); url.append('&'); url.append(LLConstants.OAUTH2_CODE).append('=') .append(URLEncoder.encode(authorization_code, "UTF-8")); method = new GetMethod(url.toString()); responseCode = client.executeMethod(method); responseBody = method.getResponseBodyAsString();. . .} finally { if (method != null) method.releaseConnection();}. . .setOAuthData(responseBody); //save the returned data. . .

15

Page 16: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

2.4.4 Make the API call – get the resourceStep 4 is almost exactly like that in V1.0, which is to use the access token to make the service API call. One difference is that the authorization header requires only one token, versus two tokens in V1.0.

The access token can be used multiple times until the token expires (about 2 hours), at which time an unauthorized status code (401) is returned with body text of “oauth_token_expired.”

Listings 12, 13, and 14 show the code. Listing 12 is the main ShareMyFile class, which calls both the create authorization header and the Http Out request. The highlights of this are to obtain parameter values from the browser, build the URL, build the authorization parameter, build the CMIS XML data required by the ShareMyFile API, and then execute an Http Put method.

Notice how much simpler the authorization header/parameter is compared with V1.0.

Listing 12. ApiShareMyFiles.java – execute( ). . .fileId = (String) request.getParameter("fid");fileName = (String) request.getParameter("fname");acl = (String) request.getParameter("acl");emails = (String) request.getParameter("emails");summary = (String) request.getParameter("summary");String subId = (String) request.getSession().getAttribute("subscriberId");if (subId == null) { ApiRequest api = new ApiGetUserIdentity(); api.execute(request, response); subId = ApiGetUserIdentity.getSubscriberId(api.getHttpResponse()); request.getSession().setAttribute("subscriberId", subId);}url = oAuthHandler.getServerUrl() + "/files/basic/cmis/repository/p!" + subId + "/acl/snx:file!" + fileId;httpRequest = new HttpPutRequest(url);httpRequest.setOAuthHeader(oAuthHandler.callApiStep_createAuthorizationHeader());setup();httpRequest.execute();setContentType(response);. . .

Listing 13. Oauth2Handler.java -- callApiStep_createAuthorizationHeader( ). . ./** * Step 4: Builds the Authorization header used by the API call. * * Authorization: Bearer "<accessToken>" */@Overridepublic String callApiStep_createAuthorizationHeader() { LLUtils.print("Auth Header="+"Bearer "+ accessToken); return "Bearer "+ accessToken;}

16

Page 17: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

Listing 14. HttpPutRequest.java -- execute( ). . .HttpClient client;HttpState initialState;client = new HttpClient();initialState = new HttpState();client.setState(initialState);method.addRequestHeader("Authorization", this.getOAuthHeader());try { int statusCode = client.executeMethod(method); httpResponse.setStatusCode(statusCode); httpResponse.setResponseText(method.getResponseBodyAsString()); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { handleBadStatusCode(); } else { httpResponse.setContentType(method.getResponseHeader(LLConstants.CONTENT_TYPE)); }. . .

2.4.5 Get a new access token using the refresh token V2.0 added the concept of renewing an expired access token without re-authorization. Access tokens are short lived, to enhance security since there is no requirement for encryption of tokens as in V1.0.

When the access token expires, an unauthorized status code (401) is returned with body text of “oauth_token_expired.” The “Get-access-token” step also returned a refresh token, which is the longer lived (time length can be set at application registration), and this token is used to get a new access token repeatedly.

Listing 15 shows the code for Step 5, the highlights of which are: build the Authorization parameter; call an Http Post method (Get method is also acceptable); and save the returned credentials, access token and refresh token. Refer to the comment block for the format of the Authorization parameter.

Listing 15. Oauth2Handler.java – step5_refreshAccessToken( ). . ./** * Step 5: Get a new access token using the refresh token. * * Server URL -- https://apps.lotuslive.com/manage/oauth2/token * Authorization: OAuth * client_secret="<client_secret>", * client_id="<client_id>", * grant_type="refresh_token", * refresh token="<refresh_token>" * * @throws Exception */. . .client = new HttpClient();initialState = new HttpState();

17

Page 18: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

client.setState(initialState);StringBuffer url = new StringBuffer(2048);url.append(getServerUrl()).append(LLProperties.getProperty("AccessTokenUrl_v2")).append('?');url.append(LLConstants.OAUTH2_CLIENT_ID);url.append('=');url.append(URLEncoder.encode(client_id, "UTF-8"));url.append('&');url.append(LLConstants.OAUTH2_CLIENT_SECRET);url.append('=');url.append(URLEncoder.encode(client_secret, "UTF-8"));url.append('&');url.append(LLConstants.OAUTH2_GRANT_TYPE);url.append('=');url.append(LLConstants.OAUTH2_REFRESH_TOKEN);url.append('&');url.append(LLConstants.OAUTH2_REFRESH_TOKEN);url.append('=');url.append(URLEncoder.encode(refreshToken, "UTF-8"));method = new GetMethod(url.toString());responseCode = client.executeMethod(method);responseBody = method.getResponseBodyAsString();. . .} finally { if (method != null) method.releaseConnection();}. . .setOAuthData(method.getResponseBodyAsString());. . .

3 APIsOnce authorization is given, an application can call SmartCloud for Social Business APIs to use its services. The service API allows an application to do something useful and integrate itself with IBM SmartCloud. Although aspects such as authorization are fairly fixed and standard, the service API is where an application's value comes from because innovation, creativity, utility, and how well the application integrates can differentiate it against other applications.

The sample application implements API calls from several service areas: Profiles, Communities, Files, and Meetings. Each API call is contained in individual classes to keep things simple and separate.

Listing 16 shows an example of a simple API call in which only the URL is called, and listing 17 shows a bit more complex example in which a setup method must build an XML Atom entry structure required by the API.

Listing 16. ApiGetMyProfile.java – execute( ). . .oAuthHandler = (OAuthHandler) request.getSession().getAttribute(LLConstants.OAUTH_HANDLER);url = oAuthHandler.getServerUrl() + "/lotuslive-shindig-server/social/rest/people/@me/@self?format=json";try {

18

Page 19: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

httpRequest = new HttpGetRequest(url); httpRequest.setOAuthHeader(oAuthHandler.callApiStep_createAuthorizationHeader()); httpRequest.execute();}. . .

Listing 17. ApiCreateACommunity.java – execute( ). . .oAuthHandler = (OAuthHandler) request.getSession().getAttribute(LLConstants.OAUTH_HANDLER);url = oAuthHandler.getServerUrl() + "/communities/service/atom/communities/my";try { httpRequest = new HttpPostRequest(url); httpRequest.setOAuthHeader(oAuthHandler.callApiStep_createAuthorizationHeader()); setup(); httpRequest.execute(); setContentType(response);}. . .

In both cases, the Http response data is sent back to the browser client after some error checking, and the browser client JavaScript handles and transforms the returned data into a presentable form. Refer to Sections 2.2.5 and 2.4.4 above for more API information in an OAuth context.

A great tool to experiment with IBM SmartCloud for Social Business APIs is the SBTK API Explorer, which lets you try an API call, set its request parameters, view the response, and read the API documentation.

4 UI extensionsYou can integrate your application even more by displaying the SmartCloud for Social Business navigation bar and adding the app to the navigation bar as a menu item. SmartCloud for Social Business allows an organization to extend the user interface (UI) through either a Web page form or by importing a JSON file.

This enhances the user experience by enabling easy navigation between your application and SmartCloud for Social Business. Clicking the new menu item takes you directly to the application. Administrative rights are needed to extend a UI, and the extension only affects that organization.

For more information, refer to the product documentation topic, “Understanding user interface extensions .”

The following code line shows the script tag that adds a SmartCloud for Social Business navigation bar to an application:

19

Page 20: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

< script src = "https://apps.lotuslive.com/manage/navbar /banner2 /partner" > </script>

Listing 18 shows the JSON code that extends the UI by adding an application to the SmartCloud for Social Business App menu (see figure 4). The sample application's main page includes demos of these two topics.

Listing 18. JSON code to extend SmartCloud for Social Business navigation bar[{"enabled":"true","tooltip":"","mime_type":"","extends":"service_menu","icon":"https://localhost:8443/SBTKDeveloperApp/images/box.png","type":"action","id":"1323122869059_28100","description":"","text":"MySocialApp","new_window":"false","url":"https://localhost:8443/SBTKDeveloperApp/MainPage.jsp"}]

Figure 4. MySocialApp added using the above JSON data

5 ConclusionThis article demonstrated how to develop an SmartCloud for Social Business application, in which the integration process is twofold: (1) authenticate/authorize using the Open Authorization protocol and then (2) call the SmartCloud for Social Business service APIs to perform a useful task. In addition, UI extensions can make the application appear more polished and integrated.

Using a working sample application, we drilled into the application's internals, breaking down the integration process into steps and then examining and clarifying each step by presenting graphics and source code listings to aid comprehension. Emphasis was put on describing the details of the Open Authorization protocol, which can be a source of confusion.

The sample application was kept as simple as possible, with plain, straightforward code, and should provide a good basis for developing your application. Of course, many enhancements will be required for a robust, real-world application.

20

Page 21: Developing an IBM SmartCloud for Social Business applicationpublic.dhe.ibm.com/software/dw/lotus/DevelopingSmartCloudApp_Fi… · (1) obtain a free trial account if you do not already

6 Resources• Refer to the IBM SmartCloud for Social Business product wiki.

• Read the product documentation topic, “Application integration for IBM SmartCloud for Social Business.”

• Read the product documentation topic, “Open Authorization.”

• Read the product documentation topic, “IBM Social Business Toolkit.”

• IBM Social Business Toolkit API Explorer.

• Open Authorization Web site .

7 Author bioJason Blakely is a Software Engineer at IBM's Research Triangle Park Lab in Raleigh, North Carolina, working on Partner Integrations for IBM SmartCloud for Social Business. You can reach Jason at [email protected].

Trademarks• IBM and IBM SmartCloud for Social Business are trademarks or registered trademarks of IBM

Corporation in the United States, other countries, or both.

• Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.

21