13.3 Authentication REST API

If you want to use the Reporting REST API to write custom reporting applications, you need to use the Authentication Service to authenticate before making reporting API calls. This section provides an overview of the authentication process, as well as details on using the Authentication API. For more information on the reporting API, see Section 13.4, Reporting REST API.

The Authentication Service is a standalone Java Web application that provides the following functions through REST:

13.3.1 POST auth/tokens

Performs a client login in to the Authentication Service. This operation creates an authentication token. It returns a different token each time it is called.

Format JSON, XML

URL Parameters

None.

Request Headers

This operation uses the Authorization request header to specify these values:

  • BASIC

  • <credential>

    The <credential> must provide a valid user name and password for authentication.

The Authorization request header must, therefore, look like this:

Authorization: BASIC <credential>

Return Codes

A successful login operation returns 200, along with the token (specified by the JSON or XML key of Token).

Here is an example JSON payload:

{"Token":"3f597a4d311a3e00..."}

Response Headers

None.

Error Codes

If this operation is unsuccessful, it may return one of the following error codes:

  • 401 Invalid credentials

  • 500 InternalError: Server problem (Receiver)

13.3.2 DELETE auth/tokens{token}

Performs a client logout from the Authentication Service.

Format JSON, XML

URL Parameters

None.

Request Headers

None.

Return Codes

A successful logout operation returns 200.

Response Headers

None.

Error Codes

If this operation is unsuccessful, it may return one of the following error codes:

  • 410 Does not exist (occurs if the token has expired, the user has already logged out, or the token never existed)

  • 500 InternalError: Server problem (Receiver)

13.3.3 Example

The following Java code example shows you might use the REST APIs to login and logout of the reporting application. In this example, the login operation is followed immediately by a logout operation. You would need to modify this code for your own application:

package com.netiq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class LoginSample
{
    private static final String BASIC_AUTH = "BASIC";
    private static final String TOKEN_JSON_KEY = "Token";

    public static void main (String args[])
    {

        System.out.println("\n\n\n\n============================================\n\n");
        try {
            doLogin("badmin", "test", "http://localhost:8081/IDMRPT-AUTH/auth/tokens");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void doLogin(String user, String pwd, String tsUrl)
        throws IOException, JSONException
    {
        System.out.println("Making login request for " + user + " to server " + tsUrl);
        
        HttpClient httpclient = new DefaultHttpClient();
        
        URL url = new URL(tsUrl);
        
        HttpPost httppost = new HttpPost(tsUrl);

        httppost.setHeader("Accept", "application/json");
        httppost.setHeader("Accept-Charset", "UTF-8");

        httppost.setHeader("Authorization", BASIC_AUTH + " " +
                           new String(Base64.encodeBase64(new String(user + ":" + pwd).getBytes("UTF-8"))));

        // Execute the request
        HttpResponse authResponse = httpclient.execute(httppost);

        int status = authResponse.getStatusLine().getStatusCode();
        System.out.println("The server responded with status code: " + status);

        HttpEntity entity = authResponse.getEntity();

        StringBuffer response = new StringBuffer();

        // If the response does not enclose an entity, there is no need
        // to worry about connection release
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(instream));
                String line = null;

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            } catch (RuntimeException ex) {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection and release it back to the connection manager.
                httppost.abort();
                throw ex;
            } finally {
                // Closing the input stream will trigger connection release
                if (reader != null) {
                    reader.close();
                }
            }

            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }

        JSONObject obj = new JSONObject(response.toString());
        String token = obj.getString(TOKEN_JSON_KEY);

        System.out.println("The login completed successfully and the server generated the following token\n\n\t" + token);

        doLogout(token, tsUrl);
    }

    private static void doLogout(String token, String tsUrl)
        throws IOException
    {
        System.out.println("\n\nMaking logout request for " + token + " to server " + tsUrl);

        HttpClient httpclient = new DefaultHttpClient();
        
        URL url = new URL(tsUrl);

        HttpDelete httpdel = new HttpDelete(tsUrl + "/" + URLEncoder.encode(token, "UTF-8"));

        httpdel.setHeader("Accept", "application/json");
        httpdel.setHeader("Accept-Charset", "UTF-8");
        //httpdel.setHeader("Authorization", request.getHeader("Authorization"));


        // Execute the request
        HttpResponse authResponse = httpclient.execute(httpdel);

        int status = authResponse.getStatusLine().getStatusCode();

        System.out.println("The server responded with status code: " + status);

        // Get hold of the response entity
        HttpEntity entity = authResponse.getEntity();

        StringBuffer authResponseData = new StringBuffer();

        // If the response does not enclose an entity, there is no need
        // to worry about connection release
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(instream));

                String line = null;

                while ((line = reader.readLine()) != null) {
                    authResponseData.append(line);
                }
            } catch (RuntimeException ex) {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection and release it back to the connection manager.
                httpdel.abort();
                throw ex;
            } finally {
                // Closing the input stream will trigger connection release
                if (reader != null) {
                    reader.close();
                }
            }

            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }


        System.out.println("The logout was successful and the server responded with\n\n\t" + authResponseData.toString());

        System.out.println("\n\n============================================\n\n\n\n");
    }
}