Clarity Service Management

Expand all | Collapse all

C Sharp Rest Authentication

Jump to Best Answer
  • 1.  C Sharp Rest Authentication

    Posted 03-29-2017 01:20 PM

    I'm trying to use C Sharp to call the SD Rest API. I figured out how to generate the documentation for the API and how to use Soap UI to request a access key using the rest_access "method". Now I'm trying to figure out how to accomplish the same thing using C Sharp. I'm familiar with the SOAP WSDL but being new to both C Sharp and Rest  is making this challenging and time consuming. Has some else accomplished this type of integration before or do you have any ideas or code samples to share?



  • 2.  Re: C Sharp Rest Authentication
    Best Answer

    Posted 03-30-2017 04:42 PM
      |   view attached

    Hi Elwynn,

     

    SDM currently only provides Java samples under the $NX_Root\samples\sdk\rest\java directory on the Service Desk server. I did take a quick stab at this in C# and came up with something that works. Please see the code example below and let us know if it works for you:

     

    static void Main(string[] args)
    {
    string sdmBaseRESTURL = @"http://<hostname>:<port>/caisd-rest"; //SDM REST URL
    string sdmUser = @"username"; //SDM Username
    string sdmUserPass = @"password"; //SDM Username's Password

    string accessKey = GetAccessKeyFromSDM(sdmBaseRESTURL, sdmUser, sdmUserPass);

    Console.WriteLine(accessKey);
    Console.ReadLine();
    }

    /// <summary>Post call to get access key from SDM.</summary>
    /// <param name="sdmURL">URL for server (Format: http://hostname:port/caisd-rest</param>
    /// <param name="username">Username of the SDM user.</param>
    /// <param name="password">Password of the SDM user.</param>
    /// <returns>Access Key to be passed as X-AccessKey header value in subsequent calls </returns>
    ///
    private static string GetAccessKeyFromSDM(string sdmRESTURL, string username, string password)
    {
    string postBody = @"<rest_access/>";
    byte[] dataByte = Encoding.ASCII.GetBytes(postBody);

    HttpWebRequest POSTRequest = (HttpWebRequest)WebRequest.Create(sdmRESTURL + @"/rest_access");
    //Method type
    POSTRequest.Method = "POST";
    // Data type - message body coming in xml
    POSTRequest.ContentType = "application/xml";
    POSTRequest.Accept = "application/json";
    POSTRequest.KeepAlive = false;
    POSTRequest.Timeout = 5000;

    //Encodes Username and Password to Base64
    string credentials = String.Format("{0}:{1}", username, password);
    byte[] bytes = Encoding.ASCII.GetBytes(credentials);
    string base64 = Convert.ToBase64String(bytes);
    string authorization = String.Concat("Basic ", base64);
    POSTRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);

    //Content length of message body
    POSTRequest.ContentLength = dataByte.Length;

    // Get the request stream
    Stream POSTstream = POSTRequest.GetRequestStream();
    // Write the data bytes in the request stream
    POSTstream.Write(dataByte, 0, dataByte.Length);

    //Get response from server
    try
    {
    HttpWebResponse POSTResponse = (HttpWebResponse)POSTRequest.GetResponse();
    StreamReader reader = new StreamReader(POSTResponse.GetResponseStream(), Encoding.UTF8);

    //responseString is the full responseString
    string responseString = reader.ReadToEnd().ToString();

    dynamic authResponse = JsonConvert.DeserializeObject(responseString);

    //accessKey is to be passed as X-AccessKey header value in subsequent calls
    string accessKey = authResponse.rest_access.access_key;

    return accessKey;
    }
    //Catch HTTP Error Codes
    catch (WebException ex)
    {
    HttpWebResponse response = (HttpWebResponse)ex.Response;
    return "HTTP Error " + (int)response.StatusCode + ": " + response.StatusCode;
    }
    //Catch All Other Errors
    catch
    {
    return "Unexpected Error";
    }
    }

     

    I have also attached the .cs file for easier consumption.

     

    Thanks,

    Anthony

     

    Edit:

     

    Added exception handling for HTTP Errors, 401, 404, etc.

    Also changed the method so you provide the base REST URL instead of full rest_access URL.

     

    Note: This method uses the JSON.net library so you would have to use NuGet to install the package. It is used for JsonConvert.DeserializeObject() to parse the JSON response and grab the access_key.

    Run in NuGet: Install-Package Newtonsoft.Json

    Attachment(s)

    zip
    Program.cs.zip   1K 1 version


  • 3.  Re: C Sharp Rest Authentication

    Posted 04-03-2017 09:05 AM

    Anthony,

     

    Thank you for all your time and effort in helping me unravel this one! 

    Your code is very helpful, you've shown me how to solve some of the most difficult aspects of logging into REST.

     

    Thanks to your help I only have one challenge remaining, we use SSL so I need to figure out how to pass in a cert at the time I POST the rest_access request. Can I do this by adding a line below the one that sets the timeout that is something like:

    POSTRequest.ClientCertificates = ..... ?

     

    I'm still researching and trying to figure out how to integrate SSL into your example, i'm hoping your knowledge of C Sharp sheds some light on how to best go about it?

     

    Thank you again!

     

    Elwynn.



  • 4.  Re: C Sharp Rest Authentication

    Posted 04-03-2017 10:34 AM

    As long as the SSL Server certificate is 'recognized' by the IE, then you shouldn't have any problems, you just need to change the URLs you call in your code.

    If the SSL Server certificate is something that it's self-signed or signed 'in-house', then you could add, in addition to changing the URLs to use https, in your code:

     System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

    This will disable the SSL validation of the cert, for your program  - not recommended in Production though.



  • 5.  Re: C Sharp Rest Authentication

    Posted 04-03-2017 12:05 PM

    Thanks Cristi,

     

    I figured out where to put the line of code and I can now retrieve access keys in dev!

     

    Now I just need to figure out the cert validation so I can move projects into production when I complete them.

     

    Elwynn.



  • 6.  Re: C Sharp Rest Authentication

    Posted 04-03-2017 12:58 PM

    Hi Elwynn,

     

    Please see the following link to StackOverflow:

     

    c# - Using a self-signed certificate with .NET's HttpWebRequest/Response - Stack Overflow 

     

    Essentially it boils down to you overriding the built in validation with one that checks for the specific HASH of your own self-signed certificate or just outright disabling it.

     

    The preferred methods however are to either get a trusted certificate or import your self-signed certificate to the local trust store of the computer running the REST application.