{"restSchemaVersion":"1.0","name":"common","version":"1.0","title":"NetProfiler Common REST API","description":"<h2>Overview<\/h2>\n\n<p>\nThe documentation pages in this section describe\nthe RESTful APIs included with NetProfiler\nproducts. It is assumed that the reader has practical knowledge of\nRESTful APIs, so the documentation does not go into detail about what\nREST is and how to use it. Instead the documentation focuses on what\ndata can be accessed and how to access it.\n<\/p>\n\n<p>\nThe primary focus of the current version of the API is on providing\naccess to common data. The following information can be accessed\nvia the API:\n<\/p>\n<ul>\n  <li>System information (serial number, model, etc.)<\/li>\n  <li>Information and resources for authenticating (login, logout, oauth 2.0, etc.)<\/li>\n<\/ul>\n\n<p>\nDetails about REST resources can be found in the <b>Resources<\/b>\nsection. \n<\/p>\n<h2>SSL<\/h2>\n\n<p>All communication to the profiler is SSL encrypted on Port 443.  There is no support for access to the profiler on the standard HTTP port 80.<\/p>\n\n<h3>Ciphers<\/h3>\n\n<p>The ciphers supported by the Profiler may change, depending on security setting (e.g., FIPS mode).  Any client when initiating a request must include one or more ciphers available in the Profiler's configured list.  Otherwise, the client will receive an SSL error indicating that there is no cipher overlap, and will be unable to connect.<\/p>\n\n<h3>Certificate<\/h3>\n\n<p>The profiler by default uses a self-signed certificate for SSL communication.  The client should be able to handle this, by permitting self-signed certificates.<\/p>\n\n<h3>Examples<\/h3>\n\n<p>Using the 'curl' command line client to request the services resource on a non-FIPS box.  The -k switch is used to allow the self-signed certificate, and a cipher suite (SSL v3) is provided.<\/p>\n\n<pre class=\"code\">curl -k -3 https:\/\/hostname:443\/api\/common\/1.0\/services<\/pre>\n\n<p>Using the 'curl' command line client to request the services resource on a FIPS box.  An explicit cipher is selected.<\/p>\n\n<pre class=\"code\">curl --ciphers rsa_aes_256_sha -k https:\/\/hostname:443\/api\/common\/1.0\/services<\/pre>\n\n<h3>Known Issues<\/h3>\n\n<p>Some clients, such as Curl (both as a library and a command line executable), do not support both an explicit cipher list, and a cipher suite.  The following command will fail on a FIPS Profiler:<\/p>\n\n<pre class=\"code\">curl --ciphers rsa_aes_256_sha -3 -k https:\/\/hostname:443\/api\/common\/1.0\/services<\/pre>\n\n<p>This is because the cipher suite (-3) overrides the --ciphers argument.  Clients with this issue will receive a 'no cipher overlap' error, even if they have explicitly provided a cipher that is known to be FIPS compliant.<\/p>\n<h2>BASIC Authentication<\/h2>\n\n<p>For BASIC authentication the request header \"Authorization\" must be set to a base64-encoded string of username:password.<\/p>\n\n<p>\nIf the \"Authorization\" header is not provided, the \"WWW-Authenticate\" response header is returned.\nBasic authentication has a built-in support in various tools. Refer to the coding examples.\n<\/p>\n\n<p>Example of client request to protected resource using Basic Authentication:<\/p>\n\n<pre class=\"code\">\nPOST \/api\/profiler\/1.0\/ping\nHost: 127.0.0.1\nAccept: application\/json\nAuthorization: Basic YWRtaW46YWRtaW4=\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">HTTP\/1.1 204 OK<\/pre>\n<h2>Sample PHP script for BASIC authentication<\/h2>\n\n<p>Use the Ping resource to demonstrate BASIC authentication.<\/p>\n\n    \n    <?php\n    \n    define('HOST', '127.0.0.1'); \/\/ IP address of Profiler\n    define('BASIC_AUTH', 'admin:admin');\n    \n    \/\/ HTTP GET\n    function do_GET($url, &$info) {\n      $curl = curl_init();\n      curl_setopt($curl, CURLOPT_URL, $url);\n      curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;\n      curl_setopt($curl, CURLOPT_USERPWD, BASIC_AUTH);\n      curl_setopt($curl, CURLOPT_SSLVERSION,3);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);\n      curl_setopt($curl, CURLOPT_HEADER, true);\n      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\n      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application\/json'));\n      curl_setopt($curl, CURLOPT_HTTPGET, true);\n      $output = curl_exec($curl);\n      $info   = curl_getinfo($curl);\n      curl_close($curl);\n        \n      $headers = substr($output, 0, $info['header_size']);\n      $headers = explode(\"\\n\", $headers);\n      $info['headers'] = $headers;\n      $body = substr($output, $info['header_size']);\n      return $body;\n    }\n    \n    \/\/ Ping to test basic authentication\n    $url = 'https:\/\/' . HOST . '\/api\/profiler\/1.0\/ping';\n    echo \"GET {$url}\\n\";\n    \n    $info = array();\n    $output = do_GET($url, $info);\n    \n    if ($info['http_code'] == 204) {\n      echo \"Ping is successful!\\n\";   \n    } else {\n      echo \"Ping failed!\\n\";\n      echo $output;\n    }\n    \n    ?>\n\n<h2>Sample Python script for BASIC authentication<\/h2>\n\n<p>Use the Ping resource to demonstrate BASIC authentication.<\/p>\n\n    \n    from urlparse import urlparse\n    import base64\n    import logging\n    import httplib\n    import json\n    import time\n    import sys\n    \n    HOST       = '127.0.0.1'\n    BASIC_AUTH = 'admin:admin'\n    \n    # Lib functions\n    \n    def do_GET(url):\n        '''HTTP GET'''\n        \n        conn = httplib.HTTPSConnection(HOST, 443)\n                \n        headers = {\"Authorization\"  : \"Basic %s\" % base64.b64encode(BASIC_AUTH),\n                   \"Content-Length\" : 0,\n                   \"Accept\"         : \"application\/json\"}\n        \n        conn.request('GET', url, body=\"\", headers=headers)\n    \n        res = conn.getresponse()\n        \n        info = {\"status\"  : res.status,\n                \"headers\" : res.getheaders()}\n        \n        data = res.read()\n        conn.close()\n        return data, info\n    \n    # Ping to test basic authentication\n    \n    url = \"https:\/\/%s\/api\/profiler\/1.0\/ping\" % HOST\n    print \"GET %s\" % url\n    \n    output, info = do_GET(url)\n    \n    if (info['status'] == 204):\n      print \"Ping is successful!\"\n    else:\n      print \"Ping failed!\"\n      print output;\n    \n\n<h2>Sample Perl script for BASIC authentication<\/h2>\n\n<p>Use the Ping resource to demonstrate BASIC authentication.<\/p>\n\n    \n    #!\/usr\/bin\/perl\n    use strict;\n    use warnings;\n    \n    use LWP::UserAgent;\n    use HTTP::Request;\n    use List::MoreUtils qw(firstidx);\n    use JSON qw( encode_json decode_json );\n    \n    use constant HOST     => '127.0.0.1';\n    use constant LOGIN    => 'admin';\n    use constant PASSWORD => 'admin';\n    \n    our $ua = LWP::UserAgent->new;\n    $ua->agent(\"ProfilerScript\/0.1\");\n    \n    our $API_BASE = \"https:\/\/127.0.0.1\";\n    \n    sub _request($) \n    {\n      my $req = shift;\n    \n      $req->header('Accept' => 'application\/json');\n      $req->authorization_basic(LOGIN, PASSWORD);\n    \n      my $res = $ua->request($req);\n    \n      return {\n        code    => $res->code,\n        status  => $res->status_line,\n        headers => $res->headers(),\n        data    => $res->content\n      };\n    }\n    \n    sub GET($) \n    {\n      my $req = HTTP::Request->new(GET => $API_BASE . shift);\n      return _request($req);\n    }\n    \n    # Ping to test basic authentication\n    \n    print \"GET \/api\/profiler\/1.0\/ping\\n\";\n    my $response = GET('\/api\/profiler\/1.0\/ping');\n    \n    if ($response->{code} == 204) {\n      print \"Ping is successful!\\n\";\n    } else {\n      print \"Ping failed!\\n\";\n      print $response->{data};\n    }\n\n<h2>Sample .Net\/C# script for BASIC authentication<\/h2>\n\n<p>Use the Ping resource to demonstrate BASIC authentication.<\/p>\n\n    \n    using System;\n    using System.Collections.Generic;\n    using System.Net;\n    using System.Text;\n    using System.IO;\n    using System.Net.Security;\n    using System.Security.Cryptography.X509Certificates;\n    \n    namespace CascadeRestClient\n    {\n        class Program\n        {\n            static string BASIC_AUTH = \"admin:admin\";\n    \n            \/\/ callback used to validate the self-gen certificate in an SSL conversation\n            private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)\n            {\n                return true;\n                \/*\n                X509Certificate2 certv2 = new X509Certificate2(cert);\n                if (certv2.GetNameInfo(X509NameType.SimpleName,true) == \"www.riverbed.com\")\n                    return true;\n    \n                return false;\n                 *\/\n            }\n    \n            private static string Base64Encode(string toEncode)\n            {\n                byte[] toEncodeAsBytes\n                = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);\n                return System.Convert.ToBase64String(toEncodeAsBytes);\n            }\n    \n            static void Main(string[] args)\n            {\n                if (args.Length == 0 || string.IsNullOrWhiteSpace(args[0]))\n                {\n                    Console.WriteLine(\"Usage: CascadeRestClient hostname\");\n                    return;\n                }\n                try\n                {\n                    \/\/Code to allow run with self-signed certificates\n                    \/\/ validate cert by calling a function\n                    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);\n    \n                    \/\/Starting to run rest \n                    string rootUrl = \"https:\/\/\" + args[0];\n                    string requestUrl = rootUrl + \"\/api\/profiler\/1.0\/ping\";\n    \n                    \/\/ Ping to test beaic authentication\n                    Console.WriteLine(\"GET \" + requestUrl);\n    \n                    \/\/ Post to run the report\n                    HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;\n                    request.Headers.Add(\"Authorization: Basic \" + Base64Encode(BASIC_AUTH));\n                    request.ContentType = \"application\/json\";\n                    request.Method = WebRequestMethods.Http.Get;\n                    request.ContentLength = 0;\n                    using (var response = request.GetResponse() as HttpWebResponse)\n                    {\n                        if (response.StatusCode == HttpStatusCode.NoContent)\n                        {\n                            Console.WriteLine(\"Ping is successful!\");\n                        }\n                        else\n                        {\n                            Console.WriteLine(\"Ping failed!\");\n                            using (Stream stream = response.GetResponseStream())\n                            {\n                                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))\n                                {\n                                    String responseString = reader.ReadToEnd();\n                                    Console.WriteLine(responseString);\n                                }\n                            }\n    \n                        }\n                    }\n                }\n                catch (Exception e)\n                {\n                    Console.WriteLine(e.Message);\n                }\n            }\n        }\n    }\n\n<h2>Sample CURL command (BASIC authentication)<\/h2>\n\n<p>Use the Ping resource to demonstrate BASIC authentication.<\/p>\n\n<pre class=\"code\">\n% curl --user username:password https:\/\/{host}\/api\/profiler\/1.0\/ping -k \n<\/pre>\n<h2>Sample WGET command (BASIC authentication)<\/h2>\n\n<p>Use the Ping resource to demonstrate BASIC authentication.<\/p>\n\n<pre class=\"code\">\n% wget --http-user username --http-password password https:\/\/{host}\/api\/profiler\/1.0\/ping --no-check-certificate \n<\/pre>\n<h2>SESSION (Cookie) authentication<\/h2>\n\n<p>In order to use the SESSION (Cookie) authentication, a session ID must be generated. The session ID can then be used to access protected resources. To generate a session ID the client must send a POST request with username, password and optionally purpose. The API supports three different methods of input: x-www-form-urlencoded, JSON and XML<\/p>\n\n<p>Client request using x-www-form-urlencoded input:<\/p>\n\n<pre class=\"code\">\nPOST \/api\/common\/1.0\/login\nHost: 127.0.0.1\nContent-Type: application\/x-www-form-urlencoded\nAccept: application\/json\n\nusername=username&amp;password=password&amp;purpose=script XYZ\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">\nHTTP\/1.1 200 OK\nSet-Cookie: SESSID=bfe3c2fd7b53053eecdd54b08c01d6a8d447aa6c15ed8f7523032c5814221ee7\n\n{\n  \"session_key\": \"SESSID\",\n  \"session_id\": \"bfe3c2fd7b53053eecdd54b08c01d6a8d447aa6c15ed8f7523032c5814221ee7\"\n}\n<\/pre>\n\n<p>Client request using JSON input: <\/p>\n\n<pre class=\"code\">\nPOST \/api\/common\/1.0\/login\nHost: 127.0.0.1\nContent-Type: application\/json\nAccept: application\/json\n\n{\n  \"username\" : \"username\", \n  \"password\" : \"password\",\n  \"purpose\"  : \"script XYZ\"\n}\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">\nHTTP\/1.1 200 OK\nSet-Cookie: SESSID=bfe3c2fd7b53053eecdd54b08c01d6a8d447aa6c15ed8f7523032c5814221ee7\n\n{\n  \"session_key\": \"SESSID\",\n  \"session_id\": \"bfe3c2fd7b53053eecdd54b08c01d6a8d447aa6c15ed8f7523032c5814221ee7\"\n}\n<\/pre>\n\n<p>Client request using XML input: <\/p>\n\n<pre class=\"code\">\nPOST \/api\/common\/1.0\/login\nHost: 127.0.0.1\nContent-Type: text\/xml\nAccept: text\/xml\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">\nHTTP\/1.1 200 OK\nSet-Cookie: SESSID=bfe3c2fd7b53053eecdd54b08c01d6a8d447aa6c15ed8f7523032c5814221ee7\n\n&lt;login \"username\"=\"user\"  \"password\"=\"pass\"  \"purpose\"=\"UI login\" \/&gt;\n<\/pre>\n\n<p>The client must include the Cookie header when accessing authenticated resources. The session (cookie) expiration rules are the same as the ones used in the GUI of the product. The rules can be changed from the <a href=\"https:\/\/{device}\/index.php?page=password_settings\" target=\"_blank\">Log-in Settings page<\/a>.<\/p>\n\n<p>Client request to protected resource using the session ID:<\/p>\n\n<pre class=\"code\">\nPOST \/api\/profiler\/1.0\/ping\nHost: 127.0.0.1\nAccept: application\/json\nCookie: SESSID=bfe3c2fd7b53053eecdd54b08c01d6a8d447aa6c15ed8f7523032c5814221ee7\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">HTTP\/1.1 204 OK<\/pre>\n\n<p>Client request to protected resource using expired\/invalid session ID:<\/p>\n\n<pre class=\"code\">\nPOST \/api\/profiler\/1.0\/ping\nHost: 127.0.0.1\nAccept: application\/json\nCookie: SESSID=bfe3c2fd7b53053eecdd54b08c01d6a8d447aa6c15ed8f7523032c5814221ee7\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">\nHTTP\/1.1 401 AUTH_INVALID_SESSION\nContent-Type: application\/json\n\n{\n  \"error_id\": \"AUTH_INVALID_SESSION\",\n  \"error_text\": \"Session ID is invalid\"\n}\n<\/pre>\n\n<p>To end a previously started session, the client sends a GET request to \/logout including a Cookie header with the session ID.<\/p>\n<p>Client request to end a previously started session:<\/p>\n\n<pre class=\"code\">\nGET \/api\/common\/1.0\/logout\nHost: 127.0.0.1\nAccept: application\/json\nCookie: SESSID=bfe3c2fd7b53053eecdd54b08c01d6a8d447aa6c15ed8f7523032c5814221ee7\n<\/pre>\n\n<p>Server response:<\/p>\n \n<pre class=\"code\">HTTP\/1.1 204<\/pre>\n<h2>Sample PHP script for SESSION (Cookie) authentication<\/h2>\n\n<p>Use the Ping resource to demonstrate SESSION (Cookie) authentication.<\/p>\n\n    \n    <?php\n    \n    define('HOST', '127.0.0.1'); \/\/ IP address of Profiler\n    \n    \/\/ HTTP POST\n    function do_POST($url, $string, &$info) {\n      $curl = curl_init();\n      curl_setopt($curl, CURLOPT_URL, $url);\n      curl_setopt($curl, CURLOPT_SSLVERSION,3);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);\n      curl_setopt($curl, CURLOPT_HEADER, true);\n      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\n      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application\/json',\n                                                   'Accept: application\/json'));\n      curl_setopt($curl, CURLOPT_POST,           1);\n      curl_setopt($curl, CURLOPT_POSTFIELDS,     $string);\n      $output = curl_exec($curl);\n      $info   = curl_getinfo($curl);\n      curl_close($curl);\n      \n      $headers = substr($output, 0, $info['header_size']);\n      $headers = explode(\"\\n\", $headers);\n      $info['headers'] = $headers;\n      $body = substr($output, $info['header_size']);\n      return $body;\n    }\n    \n    \/\/ HTTP GET\n    function do_GET($url, $session_key, $session_id, &$info) {\n      $curl = curl_init();\n      curl_setopt($curl, CURLOPT_URL, $url);\n      curl_setopt($curl, CURLOPT_SSLVERSION,3);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);\n      curl_setopt($curl, CURLOPT_HEADER, true);\n      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\n      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application\/json',\n                                                   \"Cookie: {$session_key}={$session_id}\"));\n      curl_setopt($curl, CURLOPT_HTTPGET, true);\n      $output = curl_exec($curl);\n      $info   = curl_getinfo($curl);\n      curl_close($curl);\n        \n      $headers = substr($output, 0, $info['header_size']);\n      $headers = explode(\"\\n\", $headers);\n      $info['headers'] = $headers;\n      $body = substr($output, $info['header_size']);\n      return $body;\n    }\n    \n    \/\/ Post to create session id\n    \n    $login_data = array('username' => 'admin',\n                        'password' => 'admin',\n                        'purpose'  => 'demonstrate SESSION authentication');\n    $url = 'https:\/\/' . HOST . '\/api\/common\/1.0\/login';\n    $output = do_POST($url, json_encode($login_data), $info);\n    \n    if ($info['http_code'] != 200) {\n      echo \"Login Failed!\\n\";\n      echo $output;\n      exit(1);\n    } \n    \n    $data = json_decode($output, 1);\n    $session_key = $data['session_key'];\n    $session_id  = $data['session_id'];\n    \n    echo \"Login successful, {$session_key}={$session_id}\\n\";\n    \n    \/\/ Ping to test session authentication\n    $url = 'https:\/\/' . HOST . '\/api\/profiler\/1.0\/ping';\n    echo \"GET {$url}\\n\";\n    \n    $info = array();\n    $output = do_GET($url, $session_key, $session_id, $info);\n    \n    if ($info['http_code'] == 204) {\n      echo \"Ping is successful!\\n\";   \n    } else {\n      echo \"Ping failed!\\n\";\n      echo $output;\n    }\n    \n    ?>\n\n<h2>Sample Python script for SESSION (Cookie) authentication<\/h2>\n\n<p>Use the Ping resource to demonstrate SESSION (Cookie) authentication.<\/p>\n\n    \n    from urlparse import urlparse\n    import base64\n    import logging\n    import httplib\n    import json\n    import time\n    import sys\n    \n    HOST = '127.0.0.1'\n    \n    # Lib functions\n    \n    def do_POST(url, string):\n        '''HTTP POST'''\n        \n        conn = httplib.HTTPSConnection(HOST, 443)\n                \n        headers = {\"Content-Length\" : str(len(string)),\n                   \"Content-Type\"   : \"application\/json\",\n                   \"Accept\"         : \"application\/json\"}\n        \n        conn.request('POST', url, body=string, headers=headers)\n    \n        res = conn.getresponse()\n        \n        info = {\"status\"  : res.status,\n                \"headers\" : res.getheaders()}\n        \n        data = res.read()\n        conn.close()\n        return data, info\n    \n    def do_GET(url, session_key, session_id):\n        '''HTTP GET'''\n        \n        conn = httplib.HTTPSConnection(HOST, 443)\n                \n        headers = {\"Content-Length\" : 0,\n                   \"Content-Type\"   : \"application\/json\",\n                   \"Accept\"         : \"application\/json\",\n                   \"Cookie\"         : \"%s=%s\" % (session_key, session_id)}\n        \n        conn.request('GET', url, body=\"\", headers=headers)\n    \n        res = conn.getresponse()\n        \n        info = {\"status\"  : res.status,\n                \"headers\" : res.getheaders()}\n        \n        data = res.read()\n        conn.close()\n        return data, info\n    \n    # Post to create session id\n    \n    login_data = {\n        \"username\" : \"admin\",\n        \"password\" : \"admin\",\n        \"purpose\"  : \"demonstrate SESSION authentication\"\n    }\n    \n    url = \"https:\/\/%s\/api\/common\/1.0\/login\" % HOST\n    \n    output, info = do_POST(url, json.dumps(login_data))\n    if (info['status'] is not 200):\n      print \"Login Failed!\"\n      print output\n      sys.exit(1)\n    \n    data = json.loads(output)\n    session_key = data[\"session_key\"]\n    session_id  = data[\"session_id\"]\n    \n    print \"Login successful, %s=%s\" % (session_key, session_id)\n    \n    url = \"https:\/\/%s\/api\/profiler\/1.0\/ping\" % HOST\n    \n    # Ping to test session authentication\n    output, info = do_GET(url, session_key, session_id)\n    \n    if (info['status'] is 204):\n      print \"Ping is successful!\"\n    else:\n      print \"Ping failed!\"\n      print output\n\n<h2>Sample Perl script for SESSION (Cookie) authentication<\/h2>\n\n<p>Use the Ping resource to demonstrate SESSION (Cookie) authentication.<\/p>\n\n    \n    #!\/usr\/bin\/perl\n    use strict;\n    use warnings;\n    \n    use LWP::UserAgent;\n    use HTTP::Request;\n    use List::MoreUtils qw(firstidx);\n    use JSON qw( encode_json decode_json );\n    \n    our $ua = LWP::UserAgent->new;\n    $ua->agent(\"ProfilerScript\/0.1\");\n    \n    our $API_BASE = \"https:\/\/127.0.0.1\";\n    \n    sub GET($$$) \n    {\n      my $req = HTTP::Request->new(GET => $API_BASE . shift);\n      $req->header('Accept' => 'application\/json');\n    \n      my $session_key = shift;\n      my $session_id = shift;\n      $req->header('Cookie' => \"$session_key=$session_id\");\n      \n      my $res = $ua->request($req);\n    \n      return {\n        code    => $res->code,\n        status  => $res->status_line,\n        headers => $res->headers(),\n        data    => $res->content\n      };\n    }\n    \n    sub POST($$) \n    {\n      my $req = HTTP::Request->new(POST => $API_BASE . shift);\n      $req->content_type('application\/json');\n      $req->content(encode_json(shift));\n    \n      $req->header('Accept' => 'application\/json');\n      \n      my $res = $ua->request($req);\n    \n      return {\n        code    => $res->code,\n        status  => $res->status_line,\n        headers => $res->headers(),\n        data    => $res->content\n      };\n    }\n    \n    # Post to create session id\n    \n    my $login_data = { \n      username => 'admin',\n      password => 'admin',\n      purpose  => 'demonstrate SESSION authentication'};\n    \n    my $response = POST('\/api\/common\/1.0\/login', $login_data);\n    \n    die \"Login Failed.\\n$response->{data}\\n\" unless $response->{code} == 200;\n    \n    my $data = decode_json($response->{data});\n    my $session_key = $data->{session_key};\n    my $session_id = $data->{session_id};\n    print \"Login successful, $session_key=$session_id\\n\";\n    \n    # Ping to test session authentication\n    $response = GET('\/api\/profiler\/1.0\/ping', $session_key, $session_id);\n    \n    if ($response->{code} == 204) {\n      print \"Ping is successful!\\n\";\n    } else {\n      print \"Ping failed!\\n\";\n      print $response->{data};\n    }\n\n<h2>Sample .Net\/C# script for SESSION (Cookie) authentication<\/h2>\n\n<p>Use the Ping resource to demonstrate SESSION (Cookie) authentication.<\/p>\n\n    \n    using System;\n    using System.Collections.Generic;\n    using System.Net;\n    using System.Runtime.Serialization.Json;\n    using System.Text;\n    using System.IO;\n    using System.Net.Security;\n    using System.Security.Cryptography.X509Certificates;\n    using System.Web.Script.Serialization;\n    \n    namespace CascadeRestClient\n    {\n        public class AuthResult\n        {\n            public string session_key { get; set; }\n            public string session_id { get; set; }\n        }\n    \n        class Program\n        {\n            \/\/ callback used to validate the self-gen certificate in an SSL conversation\n            private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)\n            {\n                return true;\n            }\n    \n            static void Main(string[] args)\n            {\n                if (args.Length == 0 || string.IsNullOrWhiteSpace(args[0]))\n                {\n                    Console.WriteLine(\"Usage: CascadeRestClient hostname\");\n                    return;\n                }\n                try\n                {\n                    \/\/Code to allow run with self-signed certificates\n                    \/\/ validate cert by calling a function\n                    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);\n    \n                    \/\/Starting to run rest \n                    string rootUrl = \"https:\/\/\" + args[0];\n                    string requestUrl = rootUrl + \"\/api\/common\/1.0\/login.json\";\n    \n                    var jsondata = new\n                    {\n                        username = \"admin\",\n                        password = \"admin\",\n                        purpose = \"demonstrate SESSION authentication\"\n                    };\n    \n                    \/\/Serialize anomymous type to json\n                    JavaScriptSerializer serializer = new JavaScriptSerializer();\n                    string postData = serializer.Serialize(jsondata);\n    \n                    \/\/ Login\n                    AuthResult r;\n                    using (var response = MakeRequest(requestUrl, WebRequestMethods.Http.Post, null, postData))\n                    {\n                        if (response.StatusCode != HttpStatusCode.OK)\n                        {\n                            Console.WriteLine(\"Login Failed!\");\n                            LogResponse(response);\n                            return;\n                        }\n    \n                        r = ReadResponse<AuthResult>(response);\n                    }\n                    Console.WriteLine(string.Format(\"Login successful, {0}={1}\", r.session_key, r.session_id));\n    \n                    \/\/ Ping to test session authentication\n                    requestUrl = rootUrl + \"\/api\/profiler\/1.0\/ping\";\n                    Console.WriteLine(\"GET \" + requestUrl);\n    \n                    using (var response = MakeRequest(requestUrl, WebRequestMethods.Http.Get, string.Format(\"Cookie: {0}={1}\", r.session_key, r.session_id)))\n                    {\n                        if (response.StatusCode == HttpStatusCode.NoContent)\n                        {\n                            Console.WriteLine(\"Ping is successful!\");\n                        }\n                        else\n                        {\n                            Console.WriteLine(\"Ping failed!\");\n                            LogResponse(response);\n                        }\n                    }\n                }\n                catch (Exception e)\n                {\n                    Console.WriteLine(e.Message);\n                }\n            }\n    \n            private static void LogResponse(HttpWebResponse response)\n            {\n                using (Stream stream = response.GetResponseStream())\n                {\n                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))\n                    {\n                        String responseString = reader.ReadToEnd();\n                        Console.WriteLine(responseString);\n                    }\n                }\n            }\n    \n            private static T ReadResponse<T>(HttpWebResponse response) where T : class\n            {\n                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));\n                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());\n                return objResponse as T;\n            }\n    \n            \/\/\/ <summary>\n            \/\/\/ Make request\n            \/\/\/ <\/summary>\n            \/\/\/ <typeparam name=\"T\">return type<\/typeparam>\n            \/\/\/ <param name=\"requestUrl\">url for request<\/param>\n            \/\/\/ <param name=\"action\">Http Verb, Get, Post etc<\/param>\n            \/\/\/ <param name=\"header\">additional header except accept and content type <\/param>\n            \/\/\/ <param name=\"requestData\">Data posted<\/param>\n            \/\/\/ <returns><\/returns>\n            private static HttpWebResponse MakeRequest(string requestUrl, string action, string header, string requestData = null)\n            {\n                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;\n                if (!string.IsNullOrWhiteSpace(header))\n                    request.Headers.Add(header);\n                request.ContentType = \"application\/json\";\n                request.Accept = \"application\/json\";\n                request.Method = action;\n                if (requestData == null)\n                {\n                    request.ContentLength = 0;\n                }\n                else\n                {\n                    ASCIIEncoding encoding = new ASCIIEncoding();\n                    byte[] byte1 = encoding.GetBytes(requestData);\n                    request.ContentLength = byte1.Length;\n                    using (Stream newStream = request.GetRequestStream())\n                    {\n                        newStream.Write(byte1, 0, byte1.Length);\n                    }\n                }\n    \n                return request.GetResponse() as HttpWebResponse;\n            }\n        }\n    }\n\n<h2>OAuth 2.0 authentication<\/h2>\n\n<p>In order to use the OAuth 2.0 authentication an access code needs to be generated. To generate the code:<\/p>\n\n <ul>\n   <li>Go to the <a href=\"https:\/\/{device}\/index.php?page=oauth_access\" target=\"_blank\">Configuration =&gt; Account management =&gt; OAuth Access<\/a> page.<\/li>\n   <li>Click the \"Generate new\" button.<\/li>\n   <li>Enter a description for the access code. The description is used for auditing purposes.<\/li>\n   <li>The system generates an access code. Use this in your script.<\/li>\n <\/ul>\n\n<p>All access to protected resources requires a valid access token. To get an access token, the client must send a POST request with the access code. The server will issue an access token that is valid for the next 1 hour and return it in the body of the POST. If the client script runs for more than 1 hour, then it will need to generate another access token when the one that it has expires. An expired token results into an error with HTTP code 401 and error_id AUTH_EXPIRED_TOKEN.<\/p>\n\n<p>Client request to generate an OAuth 2.0 access token:<\/p>\n\n<pre class=\"code\">\nPOST \/api\/common\/1.0\/oauth\/token\nHost: 127.0.0.1\nContent-Type: application\/x-www-form-urlencoded\nAccept: application\/json\n\ngrant_type=access_code&amp;assertion={access code here}\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">\nHTTP\/1.1 200 OK\nContent-Type: application\/json\n\n{\n  \"access_token\": \"ewoJIm5vbmNlIjogImY0MmJhZmIiLAoJImF1ZCI6ICJod...\"\n  \"token_type\": \"bearer\",\n  \"expires_in\": 3600\n}\n<\/pre>\n\n<p>Client request to protected resource using the OAuth 2.0 access token:<\/p>\n\n<pre class=\"code\">\nPOST \/api\/profiler\/1.0\/ping\nHost: 127.0.0.1\nAccept: application\/json\nAuthorization: Bearer ewoJIm5vbmNlIjogImY0MmJhZmIiLAoJImF1ZCI6ICJod...\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">HTTP\/1.1 204 OK<\/pre>\n\n<p>Client request to protected resource using expired OAuth 2.0 access token:<\/p>\n\n<pre class=\"code\">\nPOST \/api\/profiler\/1.0\/ping\nHost: 127.0.0.1\nAccept: application\/json\nAuthorization: Bearer ewoJIm5vbmNlIjogImY0MmJhZmIiLAoJImF1ZCI6ICJod...\n<\/pre>\n\n<p>Server response:<\/p>\n\n<pre class=\"code\">\nHTTP\/1.1 401 AUTH_EXPIRED_TOKEN\nContent-Type: application\/json\n\n{\n  \"error_id\": \"AUTH_EXPIRED_TOKEN\",\n  \"error_text\": \"OAuth access token is expired\"\n}\n<\/pre>\n<h2>Sample PHP script for OAuth 2.0 authentication<\/h2>\n\n<p>In order to use the OAuth 2.0 authentication an access code needs to be generated. To generate the code:<\/p>\n\n <ul>\n   <li>Go to the <a href=\"https:\/\/{device}\/index.php?page=oauth_access\" target=\"_blank\">Configuration =&gt; Account management =&gt; OAuth Access<\/a> page.<\/li>\n   <li>Click the \"Generate new\" button.<\/li>\n   <li>Enter a description for the access code. The description is used for auditing purposes.<\/li>\n   <li>The system generates an access code. Use this in your script.<\/li>\n <\/ul>\n\n<p>All access to protected resources requires a valid access token. To get an access token, the client must send a POST request with the access code. The server will issue an access token that is valid for the next 1 hour and return it in the body of the POST. If the client script runs for more than 1 hour, then it will need to generate another access token when the one that it has expires. An expired token results into an error with HTTP code 401 and error_id AUTH_EXPIRED_TOKEN.<\/p>\n\n    \n    <?php\n    \n    define('OAUTH_CODE', 'ewoJIm5vbmNlIjogImFmNTBlOTkxIiwKCSJhdWQiOiAiaHR0cHM6Ly9kZXNvLTEvYXBpL2NvbW1vbi8xLjAvb2F1dGgvdG9rZW4iLAoJImlzcyI6ICJodHRwczovL2Rlc28tMSIsCgkicHJuIjogImFkbWluIiwKCSJqdGkiOiAiMSIsCgkiZXhwIjogIjEzNTY1NTM5NDkiLAoJImlhdCI6ICIxMzUzOTYxOTQ5Igp9');\n    \n    define('HOST', '127.0.0.1'); \/\/ IP address of Profiler\n    \n    \/\/ HTTP POST\n    function do_POST($url, $string, &$info) {\n      $curl = curl_init();\n      curl_setopt($curl, CURLOPT_URL, $url);\n      curl_setopt($curl, CURLOPT_SSLVERSION,3);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);\n      curl_setopt($curl, CURLOPT_HEADER, true);\n      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\n      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application\/x-www-form-urlencoded',\n                                                   'Accept: application\/json'));\n      curl_setopt($curl, CURLOPT_POST,           1);\n      curl_setopt($curl, CURLOPT_POSTFIELDS,     $string);\n      $output = curl_exec($curl);\n      $info   = curl_getinfo($curl);\n      curl_close($curl);\n      \n      $headers = substr($output, 0, $info['header_size']);\n      $headers = explode(\"\\n\", $headers);\n      $info['headers'] = $headers;\n      $body = substr($output, $info['header_size']);\n      return $body;\n    }\n    \n    \/\/ HTTP GET\n    function do_GET($url, $access_token, &$info) {\n      $curl = curl_init();\n      curl_setopt($curl, CURLOPT_URL, $url);\n      curl_setopt($curl, CURLOPT_SSLVERSION,3);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);\n      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);\n      curl_setopt($curl, CURLOPT_HEADER, true);\n      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);\n      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application\/json',\n                                                   \"Authorization: Bearer {$access_token}\"));\n      curl_setopt($curl, CURLOPT_HTTPGET, true);\n      $output = curl_exec($curl);\n      $info   = curl_getinfo($curl);\n      curl_close($curl);\n        \n      $headers = substr($output, 0, $info['header_size']);\n      $headers = explode(\"\\n\", $headers);\n      $info['headers'] = $headers;\n      $body = substr($output, $info['header_size']);\n      return $body;\n    }\n    \n    \/\/ Post to get access token based on the access code\n    \n    $url = 'https:\/\/' . HOST . '\/api\/common\/1.0\/oauth\/token';\n    $output = do_POST($url, 'grant_type=access_code&assertion=' . OAUTH_CODE, $info);\n    \n    if ($info['http_code'] != 200) {\n      echo \"Post to get access token failed!\\n\";\n      echo $output;\n      exit(1);\n    } \n    \n    $data = json_decode($output, 1);\n    $access_token = $data['access_token'];\n    $expires_in   = $data['expires_in'];\n    echo \"Post to get token id is successful\\nToken: {$access_token}\\n\";\n    echo \"The token will expire in {$expires_in} seconds\\n\";\n    \n    \/\/ Ping to test OAuth 2.0 authentication\n    $url = 'https:\/\/' . HOST . '\/api\/profiler\/1.0\/ping';\n    echo \"GET {$url}\\n\";\n    \n    $info = array();\n    $output = do_GET($url, $access_token, $info);\n    \n    if ($info['http_code'] == 204) {\n      echo \"OAuth 2.0 authentication is successful!\\n\";   \n    } else {\n      echo \"OAuth 2.0 authentication failed!\\n\";\n      echo $output;\n    }\n    \n    ?>\n\n<h2>Sample Python script for OAuth 2.0 authentication<\/h2>\n\n<p>In order to use the OAuth 2.0 authentication an access code needs to be generated. To generate the code:<\/p>\n\n <ul>\n   <li>Go to the <a href=\"https:\/\/{device}\/index.php?page=oauth_access\" target=\"_blank\">Configuration =&gt; Account management =&gt; OAuth Access<\/a> page.<\/li>\n   <li>Click the \"Generate new\" button.<\/li>\n   <li>Enter a description for the access code. The description is used for auditing purposes.<\/li>\n   <li>The system generates an access code. Use this in your script.<\/li>\n <\/ul>\n\n<p>All access to protected resources requires a valid access token. To get an access token, the client must send a POST request with the access code. The server will issue an access token that is valid for the next 1 hour and return it in the body of the POST. If the client script runs for more than 1 hour, then it will need to generate another access token when the one that it has expires. An expired token results into an error with HTTP code 401 and error_id AUTH_EXPIRED_TOKEN.<\/p>\n\n    \n    from urlparse import urlparse\n    import base64\n    import logging\n    import httplib\n    import json\n    import time\n    import sys\n    \n    OAUTH_CODE = 'ewoJIm5vbmNlIjogImFmNTBlOTkxIiwKCSJhdWQiOiAiaHR0cHM6Ly9kZXNvLTEvYXBpL2NvbW1vbi8xLjAvb2F1dGgvdG9rZW4iLAoJImlzcyI6ICJodHRwczovL2Rlc28tMSIsCgkicHJuIjogImFkbWluIiwKCSJqdGkiOiAiMSIsCgkiZXhwIjogIjEzNTY1NTM5NDkiLAoJImlhdCI6ICIxMzUzOTYxOTQ5Igp9'\n    \n    HOST = '127.0.0.1'\n    \n    # Lib functions\n    \n    def do_POST(url, string):\n        '''HTTP POST'''\n        \n        conn = httplib.HTTPSConnection(HOST, 443)\n                \n        headers = {\"Content-Length\" : str(len(string)),\n                   \"Content-Type\"   : \"application\/x-www-form-urlencoded\",\n                   \"Accept\"         : \"application\/json\"}\n        \n        conn.request('POST', url, body=string, headers=headers)\n    \n        res = conn.getresponse()\n        \n        info = {\"status\"  : res.status,\n                \"headers\" : res.getheaders()}\n        \n        data = res.read()\n        conn.close()\n        return data, info\n    \n    def do_GET(url, access_token):\n        '''HTTP GET'''\n        \n        conn = httplib.HTTPSConnection(HOST, 443)\n                \n        headers = {\"Content-Length\" : 0,\n                   \"Content-Type\"   : \"application\/json\",\n                   \"Accept\"         : \"application\/json\",\n                   \"Authorization\"  : \"Bearer %s\" % access_token}\n        \n        conn.request('GET', url, body=\"\", headers=headers)\n    \n        res = conn.getresponse()\n        \n        info = {\"status\"  : res.status,\n                \"headers\" : res.getheaders()}\n        \n        data = res.read()\n        conn.close()\n        return data, info\n    \n    # Post to get access token based on the access code\n    \n    url = \"https:\/\/%s\/api\/common\/1.0\/oauth\/token\" % HOST\n    \n    output, info = do_POST(url, \"grant_type=access_code&assertion=%s\" % OAUTH_CODE)\n    if (info['status'] is not 200):\n      print \"Post to get access token failed!\"\n      print output\n      sys.exit(1)\n    \n    data = json.loads(output)\n    access_token = data[\"access_token\"]\n    expires_in   = data[\"expires_in\"]\n    \n    print \"Post to get token id is successful\"\n    print \"Token: %s\" % access_token\n    print \"The token will expire in %s seconds\" % expires_in\n    \n    # Ping to test OAuth 2.0 authentication\n    url = \"https:\/\/%s\/api\/profiler\/1.0\/ping\" % HOST\n    output, info = do_GET(url, access_token)\n    \n    if (info['status'] is 204):\n      print \"OAuth 2.0 authentication is successful!\"\n    else:\n      print \"OAuth 2.0 authentication failed!\"\n      print output\n\n<h2>Sample Perl script for OAuth 2.0 authentication<\/h2>\n\n<p>In order to use the OAuth 2.0 authentication an access code needs to be generated. To generate the code:<\/p>\n\n <ul>\n   <li>Go to the <a href=\"https:\/\/{device}\/index.php?page=oauth_access\" target=\"_blank\">Configuration =&gt; Account management =&gt; OAuth Access<\/a> page.<\/li>\n   <li>Click the \"Generate new\" button.<\/li>\n   <li>Enter a description for the access code. The description is used for auditing purposes.<\/li>\n   <li>The system generates an access code. Use this in your script.<\/li>\n <\/ul>\n\n<p>All access to protected resources requires a valid access token. To get an access token, the client must send a POST request with the access code. The server will issue an access token that is valid for the next 1 hour and return it in the body of the POST. If the client script runs for more than 1 hour, then it will need to generate another access token when the one that it has expires. An expired token results into an error with HTTP code 401 and error_id AUTH_EXPIRED_TOKEN.<\/p>\n\n    \n    #!\/usr\/bin\/perl\n    use strict;\n    use warnings;\n    \n    use LWP::UserAgent;\n    use HTTP::Request;\n    use List::MoreUtils qw(firstidx);\n    use JSON qw( encode_json decode_json );\n    \n    our $ua = LWP::UserAgent->new;\n    $ua->agent(\"ProfilerScript\/0.1\");\n    \n    our $OAUTH_CODE = \"ewoJIm5vbmNlIjogImFmNTBlOTkxIiwKCSJhdWQiOiAiaHR0cHM6Ly9kZXNvLTEvYXBpL2NvbW1vbi8xLjAvb2F1dGgvdG9rZW4iLAoJImlzcyI6ICJodHRwczovL2Rlc28tMSIsCgkicHJuIjogImFkbWluIiwKCSJqdGkiOiAiMSIsCgkiZXhwIjogIjEzNTY1NTM5NDkiLAoJImlhdCI6ICIxMzUzOTYxOTQ5Igp9\";\n    \n    our $API_BASE = \"https:\/\/127.0.0.1\";\n    \n    sub GET($$) \n    {\n      my $req = HTTP::Request->new(GET => $API_BASE . shift);\n      $req->header('Accept' => 'application\/json');\n    \n      my $access_token = shift;\n      $req->header('Authorization' => \"Bearer $access_token\");\n      \n      my $res = $ua->request($req);\n    \n      return {\n        code    => $res->code,\n        status  => $res->status_line,\n        headers => $res->headers(),\n        data    => $res->content\n      };\n    }\n    \n    sub POST($$) \n    {\n      my $req = HTTP::Request->new(POST => $API_BASE . shift);\n      $req->content_type('application\/json');\n      $req->content(shift);\n    \n      $req->header('Accept'       => 'application\/json');\n      $req->header('Content-Type' => 'application\/x-www-form-urlencoded');\n      \n      my $res = $ua->request($req);\n    \n      return {\n        code    => $res->code,\n        status  => $res->status_line,\n        headers => $res->headers(),\n        data    => $res->content\n      };\n    }\n    \n    # Post to get access token based on the access code\n    \n    my $url = '\/api\/common\/1.0\/oauth\/token';\n    my $response = POST($url, \"grant_type=access_code&assertion=$OAUTH_CODE\");\n    \n    die \"Post to get access token failed!\\n$response->{data}\\n\" \n      unless $response->{code} == 200;\n    \n    my $data = decode_json($response->{data});\n    my $access_token = $data->{access_token};\n    my $expires_in   = $data->{expires_in};\n    print \"Post to get token id is successful\\nToken: $access_token\\n\";\n    print \"The token will expire in $expires_in seconds\\n\";\n    \n    # Ping to test OAuth 2.0 authentication\n    $response = GET('\/api\/profiler\/1.0\/ping', $access_token);\n    \n    if ($response->{code} == 204) {\n      print \"OAuth 2.0 authentication is successful!\\n\";\n    } else {\n      print \"OAuth 2.0 authentication failed!\\n\";\n      print $response->{data};\n    }\n\n<h2>Sample .Net\/C# script for OAuth 2.0 authentication<\/h2>\n\n<p>In order to use the OAuth 2.0 authentication an access code needs to be generated. To generate the code:<\/p>\n\n <ul>\n   <li>Go to the <a href=\"https:\/\/{device}\/index.php?page=oauth_access\" target=\"_blank\">Configuration =&gt; Account management =&gt; OAuth Access<\/a> page.<\/li>\n   <li>Click the \"Generate new\" button.<\/li>\n   <li>Enter a description for the access code. The description is used for auditing purposes.<\/li>\n   <li>The system generates an access code. Use this in your script.<\/li>\n <\/ul>\n\n<p>All access to protected resources requires a valid access token. To get an access token, the client must send a POST request with the access code. The server will issue an access token that is valid for the next 1 hour and return it in the body of the POST. If the client script runs for more than 1 hour, then it will need to generate another access token when the one that it has expires. An expired token results into an error with HTTP code 401 and error_id AUTH_EXPIRED_TOKEN.<\/p>\n\n    \n    using System;\n    using System.Collections.Generic;\n    using System.Net;\n    using System.Runtime.Serialization.Json;\n    using System.Text;\n    using System.IO;\n    using System.Net.Security;\n    using System.Security.Cryptography.X509Certificates;\n    \n    namespace CascadeRestClient\n    {\n        public class OAuthResult\n        {\n            public string access_token { get; set; }\n            public string expires_in { get; set; }\n        }\n    \n        class Program\n        {\n            \/\/ callback used to validate the self-gen certificate in an SSL conversation\n            private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)\n            {\n                return true;\n            }\n    \n            static void Main(string[] args)\n            {\n                if (args.Length == 0 || string.IsNullOrWhiteSpace(args[0]))\n                {\n                    Console.WriteLine(\"Usage: CascadeRestClient hostname\");\n                    return;\n                }\n                try\n                {\n                    \/\/Code to allow run with self-signed certificates\n                    \/\/ validate cert by calling a function\n                    ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);\n    \n                    \/\/Starting to run rest \n                    string rootUrl = \"https:\/\/\" + args[0];\n                    string OAUTH_CODE = \"ewoJIm5vbmNlIjogIjUyZGFhMzZjIiwKCSJhdWQiOiAiaHR0cHM6Ly9jc2MtcGVyZjE3LmxhYi5uYnR0ZWNoLmNvbS9hcGkvY29tbW9uLzEuMC9vYXV0aC90b2tlbiIsCgkiaXNzIjogImh0dHBzOi8vY3NjLXBlcmYxNy5sYWIubmJ0dGVjaC5jb20iLAoJInBybiI6ICJhZG1pbiIsCgkianRpIjogIjEiLAoJImV4cCI6ICIxMzU2NjMwNjA3IiwKCSJpYXQiOiAiMTM1NDAzODYwNyIKfQ==\";\n                    string requestUrl = rootUrl + \"\/api\/common\/1.0\/oauth\/token\";\n    \n                    string postData = \"grant_type=access_code&assertion=\" + OAUTH_CODE;\n                    OAuthResult r;\n                    \n                    \/\/ Login\n                    using (var response = MakeRequest(requestUrl, WebRequestMethods.Http.Post,\"application\/x-www-form-urlencoded\", null, postData))\n                    {\n                        if (response.StatusCode != HttpStatusCode.OK)\n                        {\n                            Console.WriteLine(\"Login Failed!\");\n                            LogResponse(response);\n                            Console.Read();\n                            return;\n                        }\n    \n                        r = ReadResponse<OAuthResult>(response);\n                    }\n                    Console.WriteLine(\"Post to get token id is successful\\nToken:\" + r.access_token);\n                    Console.WriteLine(string.Format(\"The token will expire in {0} seconds\",r.expires_in));\n                    \n                    \/\/ Ping to test session authentication\n                    requestUrl = rootUrl + \"\/api\/profiler\/1.0\/ping\";\n                    Console.WriteLine(\"GET \" + requestUrl);\n    \n                    using (var response = MakeRequest(requestUrl, WebRequestMethods.Http.Get,\"application\/json\", string.Format(\"Authorization: Bearer {0}\", r.access_token)))\n                    {\n                        if (response.StatusCode == HttpStatusCode.NoContent)\n                        {\n                            Console.WriteLine(\"OAuth 2.0 authentication is successful!\");\n                        }\n                        else\n                        {\n                            Console.WriteLine(\"OAuth 2.0 authentication failed!\");\n                            LogResponse(response);\n                        }\n                    }\n                }\n                catch (Exception e)\n                {\n                    Console.WriteLine(e.Message);\n                }\n                Console.Read();\n            }\n    \n            private static void LogResponse(HttpWebResponse response)\n            {\n                using (Stream stream = response.GetResponseStream())\n                {\n                    using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))\n                    {\n                        String responseString = reader.ReadToEnd();\n                        Console.WriteLine(responseString);\n                    }\n                }\n            }\n    \n            private static T ReadResponse<T>(HttpWebResponse response) where T : class\n            {\n    \n                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));\n                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());\n                return objResponse as T;\n            }\n    \n            \/\/\/ <summary>\n            \/\/\/ Make request\n            \/\/\/ <\/summary>\n            \/\/\/ <param name=\"requestUrl\">url for request<\/param>\n            \/\/\/ <param name=\"action\">Http Verb, Get, Post etc<\/param>\n            \/\/\/ <param name=\"requestData\">Data posted<\/param>\n            \/\/\/ <returns><\/returns>\n            private static HttpWebResponse MakeRequest(string requestUrl, string action, string contenttype, string header, string requestData = null) \n            {\n                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;\n                try\n                {\n                    if (!string.IsNullOrWhiteSpace(header))\n                        request.Headers.Add(header);\n                    request.ContentType = contenttype;\n                    request.Accept = \"application\/json\";\n                    request.Method = action;\n                    if (requestData == null)\n                    {\n                        request.ContentLength = 0;\n                    }\n                    else\n                    {\n                        ASCIIEncoding encoding = new ASCIIEncoding();\n                        byte[] byte1 = encoding.GetBytes(requestData);\n                        request.ContentLength = byte1.Length;\n                        using (Stream newStream = request.GetRequestStream())\n                        {\n                            newStream.Write(byte1, 0, byte1.Length);\n                        }\n                    }\n    \n                    var response = request.GetResponse() as HttpWebResponse;\n                    return response;\n                }\n                catch (Exception)\n                {\n                    request.Abort();\n                    throw;\n                }\n                \n            }\n        }\n    }\n\n","defaultAuthorization":"required","servicePath":"\/api\/common\/1.0","schemas":[],"resources":{"Services":{"methods":{"List services":{"httpmethod":"GET","description":"Get information for supported API namespaces.","path":"services","response":{"type":"array","id":"services","description":"List of namespaces and versions supported by the system.","items":{"properties":{"id":{"description":"ID of the service, such as profiler.","required":true,"type":"string","id":"id"},"versions":{"type":"array","id":"versions","description":"List of versions for a given service.","items":{"description":"Version of the service.","required":false,"type":"string","id":"version"}}},"type":"object","id":"service","description":"Object representing an API service."},"example":[{"id":"common","versions":["1.0"]},{"id":"profiler","versions":["1.0"]}]}}}},"Auth_info":{"methods":{"Get authentication info":{"httpmethod":"GET","description":"Get information for supported authentication methods.","path":"auth_info","response":{"properties":{"login_banner":{"description":"Login banner that a client should display before user's login.","required":true,"type":"string","id":"login_banner"},"specify_purpose":{"description":"Flag describing if the login purpose should be specified.","required":true,"type":"boolean","id":"specify_purpose"},"supported_methods":{"type":"array","id":"supported_methods","description":"List of supported authentication methods.","items":{"description":"One method from the list of supported authentication methods.","required":false,"type":"string","id":"method","enum":["BASIC","COOKIE","OAUTH_2_0"]}}},"type":"object","id":"auth_info","description":"Common authentication information.","example":{"supported_methods":["BASIC","COOKIE","OAUTH_2_0"],"specify_purpose":true,"login_banner":"A free-form text string that should be displayed to the user prior to logging in"}}}}},"Login":{"methods":{"Login":{"httpmethod":"POST","description":"Start cookie based authentication session.","path":"login","parameters":{"username":{"type":"string","description":"User name that identifies the user to the system.","required":false},"password":{"type":"string","description":"User account password.","required":false},"purpose":{"type":"string","description":"Login purpose describing why the user logs in to the system.","required":false}},"response":{"properties":{"session_id":{"description":"Value of the session cookie.","required":true,"type":"string","id":"session_id"},"session_key":{"description":"Name of the session cookie that should be stored by the client and presented on subsequent requests.","required":true,"type":"string","id":"session_key"}},"type":"object","id":"login","description":"Response for login request.","example":{"session_key":"SESSID","session_id":"164c38b379c7cff47fa8503a28743e5c8648d97dcbd0154f597673d9031a1c63"}},"request":{"properties":{"password":{"description":"Password.","required":true,"type":"string","id":"password"},"purpose":{"description":"Login purpose describing why the user logs in to the system.","required":false,"type":"string","id":"purpose"},"username":{"description":"User name that identifies the user to the system.","required":true,"type":"string","id":"username"}},"type":"object","id":"login","description":"Specification for request to log in.","example":{"username":"username","password":"password","purpose":"Purpose for loging in"}}}}},"Oauth":{"methods":{"Get OAuth token":{"httpmethod":"POST","description":"Get a OAuth token based on OAuth code.","path":"oauth\/token","parameters":{"grant_type":{"type":"string","description":"The type of authorization method used to grant this token. The value must be access_code.","required":true},"assertion":{"type":"string","description":"The access code generated by the system on the OAuth Access page.","required":true},"state":{"type":"string","description":"Optional client-provided value that will be echoed back in the response.","required":false}},"response":{"properties":{"access_token":{"description":"The generated access token that can be used to access protected resources.","required":true,"type":"string","id":"access_token"},"allowed_signature_types":{"type":"array","id":"allowed_signature_types","description":"Array of allowed signature methods.","items":{"description":"Allowed signature method.","required":false,"type":"string","id":"value"}},"expires_in":{"description":"How long this token is valid for.","required":true,"type":"number","id":"expires_in"},"state":{"description":"Included if the state parameter was passed in the token request.","required":false,"type":"string","id":"state"},"token_type":{"description":"The token type. Only \"bearer\" is currently supported.","required":true,"type":"string","id":"token_type"}},"type":"object","id":"token_response","description":"TokenResponse object.","example":{"access_token":"eyJhbGciOiJub25lIn0K.ew0KICAiaXNzIjogImh0dHBzOi8vcHJvZmlsZXIubGFiLm5idHRlY2guY29tIiwNCiAgImp0aSI6ICI3MjM1IiwNCiAgInBybiI6ICJjd2hpdGUiLA0KICAiYXVkIjogImh0dHBzOi8vcHJvZmlsZXIubGFiLm5idHRlY2guY29tL3Rva2VuIiwNCiAgImlhdCI6IDEzNDAwMjIwMTEsDQogICJleHAiOiAxMzQwMDI1NjExDQp9DQo=","token_type":"bearer","allowed_signature_types":["none"],"expires_in":3600,"state":"a34rfFas"}}},"Get Oauth code\/implicit token":{"httpmethod":"GET","description":"Get Oauth code\/implicit token for the current user.","path":"oauth\/authorize","parameters":{"client_id":{"type":"string","description":"Client identifier.","required":false},"response_type":{"type":"string","description":"The value must be 'code' for requesting an access code and 'token' for an access token.","required":true},"desc":{"type":"string","description":"Description of the use of this code. Used in audit trail logs.","required":false},"state":{"type":"string","description":"Included if the state parameter was passed in the token request.","required":false},"redirect_uri":{"type":"string","description":"URI that will be used for redirect.","required":false}}}}},"Ping":{"methods":{"Ping":{"httpmethod":"GET","description":"Simple test of service availability.","path":"ping"}}},"Logout":{"methods":{"Logout":{"httpmethod":"POST","description":"End cookie based authentication session.","path":"logout","parameters":{"banner_disagree":{"type":"string","description":"Used when the session is being ended due to the user not agreeing to the login banner conditions.","required":false}}}}},"Info":{"methods":{"Get info":{"httpmethod":"GET","description":"Get appliance info.","path":"info","response":{"properties":{"device_name":{"description":"Name of the device that the API is running on.","required":false,"type":"string","id":"device_name"},"hw_version":{"description":"Unsupported.","required":false,"type":"string","id":"hw_version"},"mgmt_addresses":{"type":"array","id":"mgmt_addresses","description":"List of IP addresses.","items":{"description":"IP address.","required":false,"type":"string","id":"ip"}},"model":{"description":"Model of the device.","required":false,"type":"string","id":"model"},"serial":{"description":"Serial number of the device.","required":false,"type":"string","id":"serial"},"sw_version":{"description":"Version of the software that is running on the device.","required":false,"type":"string","id":"sw_version"}},"type":"object","id":"info","description":"Information about the system.","example":{"sw_version":"10.0 (release 20121106_2000)","device_name":"cam-redfin2","mgmt_addresses":["10.38.9.106"],"serial":"FB8RS00035E98","model":"02260"}}}}}},"errors":[{"error_id":"INTERNAL_ERROR","description":"Internal server error.","http_status":"500"},{"error_id":"AUTH_REQUIRED","description":"The requested resource requires authentication.","http_status":"401"},{"error_id":"AUTH_INVALID_CREDENTIALS","description":"Invalid username and\/or password.","http_status":"401"},{"error_id":"AUTH_INVALID_SESSION","description":"Session ID is invalid.","http_status":"401"},{"error_id":"AUTH_EXPIRED_PASSWORD","description":"The password must be changed. Access only to password change resources.","http_status":"403"},{"error_id":"AUTH_DISABLED_ACCOUNT","description":"Account is either temporarily or permanently disabled.","http_status":"403"},{"error_id":"AUTH_FORBIDDEN","description":"User is not authorized to access the requested resource.","http_status":"403"},{"error_id":"AUTH_INVALID_TOKEN","description":"OAuth access token is invalid.","http_status":"401"},{"error_id":"AUTH_EXPIRED_TOKEN","description":"OAuth access token is expired.","http_status":"401"},{"error_id":"AUTH_INVALID_CODE","description":"OAuth access code is invalid.","http_status":"401"},{"error_id":"AUTH_EXPIRED_CODE","description":"OAuth access code is expired.","http_status":"401"},{"error_id":"RESOURCE_NOT_FOUND","description":"Requested resource was not found.","http_status":"404"},{"error_id":"HTTP_INVALID_METHOD","description":"Requested method is not available for this resource.","http_status":"405"},{"error_id":"HTTP_INVALID_HEADER","description":"An HTTP header was malformed.","http_status":"400"},{"error_id":"REQUEST_INVALID_INPUT","description":"Malformed input structure.","http_status":"400"},{"error_id":"URI_INVALID_PARAMETER","description":"URI parameter is not supported or malformed.","http_status":"400"},{"error_id":"URI_MISSING_PARAMETER","description":"Missing required parameter.","http_status":"400"}]}
