Represents the client credential that is used in service requests. It contains the client token that represents the service client, the client secret that is associated with the client token used for request signing, and the access token that represents the authorizations the client has for accessing the service.
        public void GetterTest()
        {
            string accessToken = "access-token";
            string clientToken = "client-token";
            string secret = "secret";
            ClientCredential credential = new ClientCredential(clientToken, accessToken, secret);

            Assert.AreEqual(credential.AccessToken, accessToken);
            Assert.AreEqual(credential.ClientToken, clientToken);
            Assert.AreEqual(credential.Secret, secret);
        }
        static void execute(string httpMethod, string apiurl, List<string> headers, string clientToken, string accessToken, string secret, string data, string uploadfile, string outputfile, int? maxBodySize, string contentType, bool verbose = false)
        {
            if (apiurl == null || clientToken == null || accessToken == null || secret == null)
            {
                help();
                return;
            }

            EdgeGridV1Signer signer = new EdgeGridV1Signer(null, maxBodySize);
            ClientCredential credential = new ClientCredential(clientToken, accessToken, secret);

            Stream uploadStream = null;
            if (uploadfile != null)
                uploadStream = new FileInfo(uploadfile).OpenRead();
            else if (data != null)
                uploadStream = new MemoryStream(data.ToByteArray());

            var uri = new Uri(apiurl);
            var request = WebRequest.Create(uri);

            foreach (string header in headers) request.Headers.Add(header);
            request.Method = httpMethod;

            Stream output = Console.OpenStandardOutput();
            if (outputfile != null)
                output = new FileInfo(outputfile).OpenWrite();

            if (verbose)
            {
                signer.Sign(request, credential, uploadStream);
                Console.WriteLine("Authorization: {0}", request.Headers.Get("Authorization"));
                Console.WriteLine();
            }

            using (var result = signer.Execute(request, credential, uploadStream))
            {
                using (output)
                {
                    using (result)
                    {
                        byte[] buffer = new byte[1024*1024];
                        int bytesRead = 0;

                        while ((bytesRead = result.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            output.Write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
        }
Example #3
0
        /// <summary>
        /// Opens the connection to the {OPEN} API, assembles the signing headers and uploads any files.
        /// </summary>
        /// <param name="request">the </param>
        /// <returns> the output stream of the response</returns>
        public Stream Execute(WebRequest request, ClientCredential credential, Stream uploadStream = null)
        {
            //Make sure that this connection will behave nicely with multiple calls in a connection pool.
            ServicePointManager.EnableDnsRoundRobin = true;
            ServicePointManager.SecurityProtocol    = SecurityProtocolType.Tls12;
            request = this.Sign(request, credential, uploadStream);

            if (request.Method == "PUT" || request.Method == "POST" || request.Method == "PATCH")
            {
                //Disable the nastiness of Expect100Continue
                ServicePointManager.Expect100Continue = false;
                if (uploadStream == null)
                {
                    request.ContentLength = 0;
                }
                else if (uploadStream.CanSeek)
                {
                    request.ContentLength = uploadStream.Length;
                }
                else if (request is HttpWebRequest)
                {
                    ((HttpWebRequest)request).SendChunked = true;
                }

                if (uploadStream != null)
                {
                    // avoid internal memory allocation before buffering the output
                    if (request is HttpWebRequest)
                    {
                        ((HttpWebRequest)request).AllowWriteStreamBuffering = false;
                    }

                    if (String.IsNullOrEmpty(request.ContentType))
                    {
                        request.ContentType = "application/json";
                    }

                    using (Stream requestStream = request.GetRequestStream())
                        using (uploadStream)
                            uploadStream.CopyTo(requestStream, 1024 * 1024);
                }
            }

            if (request is HttpWebRequest)
            {
                var httpRequest = (HttpWebRequest)request;
                httpRequest.Accept = "*/*";
                if (String.IsNullOrEmpty(httpRequest.UserAgent))
                {
                    httpRequest.UserAgent = "EdgeGrid.Net/v1";
                }
            }

            WebResponse response = null;

            try
            {
                response = request.GetResponse();
            }
            catch (WebException e)
            {
                // non 200 OK responses throw exceptions.
                // is this because of Time drift? can we re-try?
                using (response = e.Response)
                    Validate(response);
            }

            return(response.GetResponseStream());
        }
 internal string GetAuthorizationHeaderValue(ClientCredential credential, DateTime timestamp, string authData, string requestData)
 {
     string signingKey = timestamp.ToISO8601().ToByteArray().ComputeKeyedHash(credential.Secret, this.SignVersion.Algorithm).ToBase64();
     string authSignature = string.Format("{0}{1}", requestData, authData).ToByteArray().ComputeKeyedHash(signingKey, this.SignVersion.Algorithm).ToBase64();
     return string.Format("{0}signature={1}", authData, authSignature);
 }
        internal string GetAuthDataValue(ClientCredential credential, DateTime timestamp)
        {
            if (timestamp == null)
                throw new ArgumentNullException("timestamp cannot be null");

            Guid nonce = Guid.NewGuid();
            return string.Format("{0} client_token={1};access_token={2};timestamp={3};nonce={4};",
                this.SignVersion.Name,
                credential.ClientToken,
                credential.AccessToken,
                timestamp.ToISO8601(),
                nonce.ToString().ToLower());
        }
        /// <summary>
        /// Signs the given request with the given client credential.
        /// </summary>
        /// <param name="request">The web request to sign</param>
        /// <param name="credential">the credential used in the signing</param>
        /// <returns>the signed request</returns>
        public WebRequest Sign(WebRequest request, ClientCredential credential, Stream uploadStream = null)
        {
            DateTime timestamp = DateTime.UtcNow;

            //already signed?
            if (request.Headers.Get(EdgeGridV1Signer.AuthorizationHeader) != null)
                request.Headers.Remove(EdgeGridV1Signer.AuthorizationHeader);

            string requestData = GetRequestData(request.Method, request.RequestUri, request.Headers, uploadStream);
            string authData = GetAuthDataValue(credential, timestamp);
            string authHeader = GetAuthorizationHeaderValue(credential, timestamp, authData, requestData);
            request.Headers.Add(EdgeGridV1Signer.AuthorizationHeader, authHeader);

            return request;
        }
        /// <summary>
        /// Opens the connection to the {OPEN} API, assembles the signing headers and uploads any files.
        /// </summary>
        /// <param name="request">the </param>
        /// <returns> the output stream of the response</returns>
        public Stream Execute(WebRequest request, ClientCredential credential, Stream uploadStream = null)
        {
            //Make sure that this connection will behave nicely with multiple calls in a connection pool.
            ServicePointManager.EnableDnsRoundRobin = true;
            request = this.Sign(request, credential, uploadStream);

            if (request.Method == "PUT" || request.Method == "POST" || request.Method == "PATCH")
            {
                //Disable the nastiness of Expect100Continue
                ServicePointManager.Expect100Continue = false;
                if (uploadStream == null)
                    request.ContentLength = 0;
                else if (uploadStream.CanSeek)
                    request.ContentLength = uploadStream.Length;
                else if (request is HttpWebRequest)
                    ((HttpWebRequest)request).SendChunked = true;

                if (uploadStream != null)
                {
                    // avoid internal memory allocation before buffering the output
                    if (request is HttpWebRequest)
                        ((HttpWebRequest)request).AllowWriteStreamBuffering = false;

                    if (String.IsNullOrEmpty(request.ContentType))
                        request.ContentType = "application/json";

                    using (Stream requestStream = request.GetRequestStream())
                    using (uploadStream)
                        uploadStream.CopyTo(requestStream, 1024 * 1024);
                }
            }

            if (request is HttpWebRequest)
            {
                var httpRequest = (HttpWebRequest)request;
                httpRequest.Accept = "*/*";
                if (String.IsNullOrEmpty(httpRequest.UserAgent))
                    httpRequest.UserAgent = "EdgeGrid.Net/v1";
            }

            WebResponse response = null;
            try
            {
                response = request.GetResponse();
            }
            catch (WebException e)
            {
                // non 200 OK responses throw exceptions.
                // is this because of Time drift? can we re-try?
                using (response = e.Response)
                    Validate(response);
            }

            return response.GetResponseStream();
        }
 public void ConstructorDefualtTest_NullSecret()
 {
     string accessToken = "access-token";
     string clientToken = "client-token";
     var    credential  = new ClientCredential(clientToken, accessToken, null);
 }
 public void ConstructorDefualtTest_NullAccessToken()
 {
     string clientToken = "client-token";
     string secret      = "secret";
     var    credential  = new ClientCredential(clientToken, null, secret);
 }
 public void ConstructorDefualtTest_NullClientToke()
 {
     string accessToken = "access-token";
     string secret      = "secret";
     var    credential  = new ClientCredential(null, accessToken, secret);
 }
 public void ConstructorDefualtTest_NullSecret()
 {
     string accessToken = "access-token";
     string clientToken = "client-token";
     var credential = new ClientCredential(clientToken, accessToken, null);
 }
 public void ConstructorDefualtTest_NullClientToke()
 {
     string accessToken = "access-token";
     string secret = "secret";
     var credential = new ClientCredential(null, accessToken, secret);
 }
 public void ConstructorDefualtTest_NullAccessToken()
 {
     string clientToken = "client-token";
     string secret = "secret";
     var credential = new ClientCredential(clientToken, null, secret);
 }