IBM Support

API Authentication to IBM Cognos Analytics Cartridge on Cloud Pak for Data

API Authentication to IBM Cloud Pak for Data Cognos Analytics Cartridge

IBM Cognos Analytics Cartridge now is a part of IBM Cloud Pak for Data.  It allows customers to modernize to a cloud-native application at their own pace, access features, available only via CA cartridge, enable new services quickly using the power of an Integrated Data & AI Platform.

Many customers use IBM Cognos Analytics Software Development Kit or the new Cognos Analytics REST APIs for integration with Cognos Analytics and enhancement or customization of their users experience.

How can an existing on premises Cognos SDK application connect to the Cognos Analytics Cartridge?

The first step is authentication.  The process of logging on to the Cognos Cartridge includes two steps:

1) generating a CP4D authorization token
2) logging on to the Cognos Cartridge namespace with the authorization token via the Cognos SDK contentManager service

There are two ways of obtaining an authorization token: with a CP4D API-key or with the user's basic CP4D logon credential - username and password which were assigned to the user by a CP4D administrator.
 

Obtaining a CP4D authorization token

To generate an authorization token send a POST request to the CP4D authorize URL: /icp4d-api/v1/authorize.

Sample Java code:


        URL url;
	HttpsURLConnection conn;
	try {
		url = new URL(authorizeURL);
		String bodyStr = "{\"username\":\"" + username + "\", \"password\":\"" + password + "\"}";
		byte[] body = bodyStr.getBytes(StandardCharsets.UTF_8);

		conn = (HttpsURLConnection) url.openConnection();
		
		conn.setDoOutput(true);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/json");
		conn.getOutputStream().write(body);
		
		
		final String output = getFullResponse(conn.getInputStream());
		System.out.println("output: " + output);
		token = getJsonString("token", output);
		final String code = getJsonString("_messageCode_", output);
		if( token != null) {
			System.out.println("_messageCode_: " + code);
			System.out.println("token: " + token);
		}else{
			System.out.println("Token not found. Response: " + output);
			System.exit(-1);
		}
	} catch (MalformedURLException e1) {
	    System.out.println(e1.getMessage());
	} catch (IOException e) {
	    System.out.println(e.getMessage());
	};           
      . . .            
}

 

Log on to the Cognos Cartridge with an authorization token

After the authorization token is generated, set it as the Authorization header and a Header Cookie on the Cognos SDK contentManager service.
Below is a sample Java code for setting the token in the Cognos biBusHeader:


        ContentManagerService_PortType cms = null;
	ContentManagerService_ServiceLocator service = new ContentManagerService_ServiceLocator();
	try {
		cms = service.getcontentManagerService(endPointUrl);
	} catch (ServiceException e) {
		System.out.println(e.getMessage());
	}	
        ((Stub) cms)._setProperty("javax.xml.rpc.session.maintain", Boolean.TRUE); 
        String bearerToken = "Bearer "+token;
	String bearerCoookie ="ibm-private-cloud-session=" + token;
	((Stub) cms)._setProperty(HTTPConstants.HEADER_AUTHORIZATION, bearerToken);
	((Stub) cms)._setProperty(HTTPConstants.HEADER_COOKIE, bearerCoookie);

	((Stub)cms).setHeader("http://developer.cognos.com/schemas/bibus/3/", "biBusHeader", bibus);
		
	BaseClass[] results;
	try {
			
		results = cms.query(
		         new SearchPathMultipleObject("~"),
		         properties,
		         sortBy,
				 options);
	} catch (RemoteException e) {
		System.out.println(e.getMessage());
	}
  
}
  
 

Where:

  • endPointURL is the Cognos Analytics SOAP URL: bi/api/soap

  • Note: To take care of SSL connections, you will need to obtain the CP4D certificates (root/signer) and import them into your Java keystore.

Sample C# code:


							
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Services.Protocols;
using cognosdotnet_10_2;

namespace logonCP4D 
{
	// To use JsonConverter 
	// install Microsoft NuGet package for Json - Newtonsoft.Json
	// Add Microsoft.CSharp Reference
	// Add Newtonsoft.Json  Reference

    public class CustomContentManagerService : contentManagerService1
    {
        private string token;
        private CookieContainer cookies;

        public string Token { get => token; set => token = value; }
        public CookieContainer Cookies { get => cookies; set => cookies = value; }

        protected override WebRequest GetWebRequest(Uri uri)
        {
            WebRequest req = base.GetWebRequest(uri);
            req.Headers.Add("Authorization", Token);
            ((HttpWebRequest)req).CookieContainer = Cookies;
            return req;
        }
    }

    class LogonCP4D
    {
        [STAThread]
        static void Main(string[] args)
        {
            CustomContentManagerService cBICMS = null;
            cBICMS = new CustomContentManagerService();

            string bodyStr = "{\"username\":\"" + username + "\", \"password\":\"" + password + "\"}";
            //CP4D authorize URL
            String url = "https:///icp4d-api/v1/authorize";

            // ignore certificates - for testing purposes only
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
            | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = "POST";

            var data = Encoding.ASCII.GetBytes(bodyStr);

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.ContentLength = data.Length;
 
            HttpWebResponse httpWebResponse = (HttpWebResponse)null;
            Exception inner = (Exception)null;
            try
            {
                using (var stream = httpWebRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
 
                    httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                }
            catch (WebException ex)
            {
                inner = (Exception)ex;
                return;
            }
            catch (Exception ex)
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("Failed initial resource request.");
                stringBuilder.AppendLine(ex.Message);
                stringBuilder.AppendLine(ex.StackTrace);
                return;

            }

            if (httpWebResponse == null)
            {
                Console.Write("Web Response is null");
                return;
            }

            var responseString = new StreamReader(httpWebResponse.GetResponseStream()).ReadToEnd();
            dynamic stuff = Newtonsoft.Json.JsonConvert.DeserializeObject(responseString);

            cBICMS.Token = "Bearer " + stuff.token;
            string messageCode = stuff._messageCode_;
            CookieContainer cookieContainer = new CookieContainer();
            cookieContainer.Add(new Cookie("ibm-private-cloud-session", (string)stuff.token, "/", "cloud.ibm.com"));
            cBICMS.Cookies = cookieContainer;

            //CP4D Cognos cartridge soap URL
            string cognosURL = "https:///cognosanalytics/bi/api/soap";

            cBICMS.Url = cognosURL;

            // Search properties: we need the defaultName and the searchPath.
            propEnum[] properties =
                { propEnum.defaultName, propEnum.searchPath };

            // Sort options: ascending sort on the defaultName property.
            sort[] sortBy = { new sort() };
            sortBy[0].order = orderEnum.ascending;
            sortBy[0].propName = propEnum.defaultName;

            // Query options; use the defaults.
            queryOptions options = new queryOptions();

            searchPathMultipleObject qPath = new searchPathMultipleObject();
            qPath.Value = "~";

            // Make the query.
            baseClass[] results =
                cBICMS.query(qPath, properties, sortBy, options);

            // Display the results.
            string output = "Results:\n\n";
            for (int i = 0; i < results.GetLength(0); i++)
            {
                tokenProp theDefaultName = results[i].defaultName;
                stringProp theSearchPath = results[i].searchPath;

                output += "\t" + theDefaultName.value + "\t" + theSearchPath.value + "\n";
            }

            Console.WriteLine("\n");
            Console.WriteLine(output);
            Console.WriteLine("\n");
        }
 
} 							


IBM Cognos Analytics guidance and SDK/API samples are provided through Expertise Connect. For more information contact your sales representative.