Note: For up-to-date product documentation, see the IBM MobileFirst Foundation Developer Center.

Java™ custom resource-request implementation sample

This sample demonstrates how to get data from a protected resource by using a custom HttpRequest object and the MobileFirst AuthorizationManager API.

The sample implements a standard OAuth flow: first, a resource request is sent without an access token. This request is expected to fail with an authorization error. Then, WLAuthorizationManager is used to obtain an access token for the resource's protecting scope, and the request is sent again with the obtained access token as an authorization header. The resource request is created by using a standard HttpURLConnection object.

package com.sample.oauthdemoandroid;

import android.os.AsyncTask;

import com.worklight.wlclient.api.WLAccessTokenListener;
import com.worklight.wlclient.api.WLAuthorizationManager;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.auth.AccessToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class CustomRequestAsyncTask extends AsyncTask<Object, Void, Void> {

    public static final String HEADER_AUTHORIZATION = "Authorization";
    private Object[] params;

    @Override
    protected Void doInBackground(Object[] params) {
        android.os.Debug.waitForDebugger();  // for debugging
        this.params = params;
        sendRequest(null);
        return null;
    }

    private void sendRequest(AccessToken accessToken) {
        HttpURLConnection urlConnection = null;
        try {
            // Create the request to access the resource URL
            URL url = new URL(WLClient.getInstance().getServerUrl().toString() + params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            if (accessToken != null) {
                // Add an access token to the request
                urlConnection.setRequestProperty(HEADER_AUTHORIZATION, accessToken.getAsAuthorizationRequestHeader());
            }

            // Send the request
            Map<String, List<String>> headerFields = urlConnection.getHeaderFields();

            // Check whether the request succeeded
            int responseCode = urlConnection.getResponseCode();
            if (200 <= responseCode && responseCode <= 299) {
                customRequestSuccess(urlConnection);
            } else {
                // Check whether access to the resource requires authorization
                WLAuthorizationManager wlAuthorizationManager = WLAuthorizationManager.getInstance();
                if (wlAuthorizationManager.isAuthorizationRequired(responseCode, headerFields)) {
                    switch (responseCode) {
                        case 409: // Server-conflict error
                            // Resend the request
                            sendRequest(accessToken);
                            break;
                        case 401: // Invalid access token, or no access token
                            // Clear the access token (if exists)
                            if (accessToken != null) {
                                wlAuthorizationManager.clearAccessToken(accessToken);
                            }
                            // Obtain a valid access token and resend the request
                            resendWithAccessToken(headerFields);
                            break;
                        case 403: // Insufficient-scope error
                            // Get the resource scope from the response and resend the request
                            resendWithAccessToken(headerFields);
                            break;
                        default: // Unexpected error
                            customRequestFailure(urlConnection);
                    }

                } else {
                    customRequestFailure(urlConnection);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

    private void customRequestSuccess(HttpURLConnection urlConnection) throws IOException {
        // TODO: Implement the method.
    }

    private void customRequestFailure(HttpURLConnection urlConnection) throws IOException {
        // TODO: Implement the method.
    }

    private void resendWithAccessToken(Map<String, List<String>> headerFields) {
        WLAuthorizationManager wlAuthorizationManager = WLAuthorizationManager.getInstance();
        // Get the resource request from the response
        String scope = wlAuthorizationManager.getResourceScope(headerFields);
        // Obtain an access token and resend the request
        CustomRequestObtainAccessTokenListener customRequestObtainAccessTokenListener = new CustomRequestObtainAccessTokenListener();
        wlAuthorizationManager.obtainAccessToken(scope, customRequestObtainAccessTokenListener);
    }

    private class CustomRequestObtainAccessTokenListener implements WLAccessTokenListener {

        @Override
        public void onSuccess(AccessToken accessToken) {
            sendRequest(accessToken);
        }

        @Override
        public void onFailure(WLFailResponse response) {
            // TODO: Implement the method.
        }
    }
}