コード例 #1
0
        private string GetUrl(PSRequestOptions requestOption)
        {
            var        result = string.Empty;
            UriBuilder uri    = new UriBuilder(requestOption.BasePath);
            var        path   = requestOption.Path;

            foreach (var item in requestOption.PathParameters)
            {
                var tempPath = path.Replace(item.Key, "0");
                path = string.Format(tempPath, item.Value);
            }

            uri.Path = path;
            var queryString = string.Empty;

            if (requestOption.QueryParameters.Count > 0)
            {
                var queryParam = HttpUtility.ParseQueryString(string.Empty);
                foreach (var item in requestOption.QueryParameters)
                {
                    queryParam.Add(HttpUtility.UrlEncode(item.Key), item.Value);
                }
                uri.Query = queryParam.ToString().Replace("+", "%20");
            }
            return(uri.Uri.ToString());
        }
コード例 #2
0
        protected override void ProcessRecord()
        {
            //Check the objectType in MoBaseMo.ObjectTypeEnum if it belongs to that enum
            //fetch the display name.
            //this is done to work with specific Get cmdlets.
            // Get-IntersightNtpPoicy -Name xxxx | Remove-IntersightManagedObject
            var result = PSUtils.GetObjectTypeDisplayName(ObjectType);

            if (!string.IsNullOrEmpty(result))
            {
                ObjectType = result;
            }

            var psClient = new PSHttpClient(CmdletBase.Config);
            PSRequestOptions psRequestOption = new PSRequestOptions
            {
                BasePath = CmdletBase.Config.BasePath,
                Path     = string.Format("/api/v1/{0}/{{Moid}}", PSUtils.GetPath(ObjectType)),
                Method   = "Delete",
            };

            psRequestOption.PathParameters.Add(PSUtils.Moid, Moid);
            var response = psClient.Execute(psRequestOption);

            WriteObject(response);
        }
コード例 #3
0
        public string Execute(PSRequestOptions requestOption)
        {
            try
            {
                string responseBody   = string.Empty;
                var    httpWebRequest = (HttpWebRequest)WebRequest.Create(GetUrl(requestOption));
                httpWebRequest.Method      = requestOption.Method;
                httpWebRequest.ContentType = requestOption.ContentType;

                var signedHeaders = HttpSigningAuthConfig.GetHttpSignedHeader(requestOption);
                foreach (var item in signedHeaders)
                {
                    httpWebRequest.Headers.Add(item.Key, item.Value);
                }

                if (!string.IsNullOrEmpty(requestOption.RequestData))
                {
                    var bytes = GetBytes(requestOption.RequestData);
                    httpWebRequest.ContentLength = bytes.Length;
                    Stream stream = httpWebRequest.GetRequestStream();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                }

                HttpWebResponse webResponse    = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream          responseStream = webResponse.GetResponseStream();
                StreamReader    reader         = new StreamReader(responseStream, Encoding.UTF8);
                responseBody = reader.ReadToEnd();

                if (!((webResponse.StatusCode == HttpStatusCode.OK) ||
                      (webResponse.StatusCode == HttpStatusCode.Created) ||
                      (webResponse.StatusCode == HttpStatusCode.Accepted) ||
                      (webResponse.StatusCode == HttpStatusCode.NoContent) ||
                      (webResponse.StatusCode == HttpStatusCode.AlreadyReported) ||
                      (webResponse.StatusCode == HttpStatusCode.NonAuthoritativeInformation) ||
                      (webResponse.StatusCode == HttpStatusCode.PartialContent) ||
                      (webResponse.StatusCode == HttpStatusCode.ResetContent)))
                {
                    throw new Exception(string.Format("{0} : {1}", webResponse.StatusCode, responseBody));
                }

                return(responseBody);
            }
            catch (Exception ex)
            {
                WebException webExp = ex as WebException;
                if (webExp != null)
                {
                    string reqStr = string.Empty;
                    using (StreamReader sr = new StreamReader(webExp.Response.GetResponseStream()))
                    {
                        reqStr = sr.ReadToEnd();
                        throw new Exception(string.Format("{0}\n{1}", ex.Message, reqStr));
                    }
                }
                throw ex;
            }
        }
コード例 #4
0
        protected override void ProcessRecord()
        {
            //Check the objectType in MoBaseMo.ObjectTypeEnum if it belongs to that enum
            //fetch the display name.
            //this is done to work with specific Get cmdlets.
            // Get-IntersightNtpPoicy -Name xxxx | Set-IntersightManagedObject
            var result = PSUtils.GetObjectTypeDisplayName(ObjectType);

            if (!string.IsNullOrEmpty(result))
            {
                ObjectType = result;
            }

            var psClient = new PSHttpClient(CmdletBase.Config);
            PSRequestOptions psRequestOption = new PSRequestOptions
            {
                BasePath = CmdletBase.Config.BasePath,
                Method   = "POST",
            };

            if (ParameterSetName == PSUtils.CmdletParam)
            {
                psRequestOption.RequestData = JsonConvert.SerializeObject(AdditionalProperties, Formatting.Indented);
            }
            else
            {
                var tempHashTable = JsonConvert.DeserializeObject <Hashtable>(JsonRequestBody);
                if (tempHashTable.ContainsKey(PSUtils.ObjectType))
                {
                    ObjectType = tempHashTable[PSUtils.ObjectType].ToString();
                }
                else
                {
                    throw new Exception(string.Format("Property {0} is missing in JsonRequestBody", PSUtils.ObjectType));
                }

                if (tempHashTable.ContainsKey(PSUtils.Moid))
                {
                    Moid = tempHashTable[PSUtils.Moid].ToString();
                }
                else
                {
                    throw new Exception(string.Format("Property {0} is missing in JsonRequestBody", PSUtils.Moid));
                }

                psRequestOption.RequestData = JsonRequestBody;
            }

            psRequestOption.PathParameters.Add(PSUtils.Moid, Moid);
            psRequestOption.Path = string.Format("/api/v1/{0}/{{Moid}}", PSUtils.GetPath(ObjectType));
            var response = psClient.Execute(psRequestOption);

            WriteObject(response);
        }
コード例 #5
0
        protected override void ProcessRecord()
        {
            //Check the objectType in MoBaseMo.ObjectTypeEnum if it belongs to that enum
            //fetch the display name.
            //this is done to work with specific Get cmdlets.
            // Get-IntersightNtpPoicy -Name xxxx | Set-IntersightManagedObject
            var result = PSUtils.GetObjectTypeDisplayName(ObjectType);

            if (!string.IsNullOrEmpty(result))
            {
                ObjectType = result;
            }

            var psClient = new PSHttpClient(CmdletBase.Config);
            PSRequestOptions psRequestOption = new PSRequestOptions
            {
                BasePath    = CmdletBase.Config.BasePath,
                Method      = "PATCH",
                ContentType = "application/json-patch+json"
            };

            if (ParameterSetName == PSUtils.CmdletParam)
            {
                psRequestOption.RequestData = JsonConvert.SerializeObject(PatchDocument, Formatting.Indented);
            }
            else
            {
                var tempHashTable = JsonConvert.DeserializeObject <List <PatchDocument> >(JsonPatchDocument);
                psRequestOption.RequestData = JsonPatchDocument;
            }

            psRequestOption.PathParameters.Add(PSUtils.Moid, Moid);
            psRequestOption.Path = string.Format("/api/v1/{0}/{{Moid}}", PSUtils.GetPath(ObjectType));
            var response = psClient.Execute(psRequestOption);

            WriteObject(response);
        }
コード例 #6
0
        /// <summary>
        /// Gets the Headers for HttpSigning
        /// </summary>
        /// <param name="basePath">Base path</param>
        /// <param name="method">HTTP method</param>
        /// <param name="path">Path</param>
        /// <param name="requestOptions">Request options</param>
        /// <returns></returns>
        internal Dictionary <string, string> GetHttpSignedHeader(PSRequestOptions requestOptions)
        {
            const string HEADER_REQUEST_TARGET = "(request-target)";
            //The time when the HTTP signature expires. The API server should reject HTTP requests
            //that have expired.
            const string HEADER_EXPIRES = "(expires)";
            //The 'Date' header.
            const string HEADER_DATE = "Date";
            //The 'Host' header.
            const string HEADER_HOST = "Host";
            //The time when the HTTP signature was generated.
            const string HEADER_CREATED = "(created)";
            //When the 'Digest' header is included in the HTTP signature, the client automatically
            //computes the digest of the HTTP request body, per RFC 3230.
            const string HEADER_DIGEST = "Digest";
            //The 'Authorization' header is automatically generated by the client. It includes
            //the list of signed headers and a base64-encoded signature.
            const string HEADER_AUTHORIZATION = "Authorization";

            //Hash table to store singed headers
            var HttpSignedRequestHeader = new Dictionary <string, string>();
            var HttpSignatureHeader     = new Dictionary <string, string>();

            if (HttpSigningHeader.Count == 0)
            {
                HttpSigningHeader.Add("(created)");
            }

            if (requestOptions != null && requestOptions.PathParameters != null)
            {
                foreach (var pathParam in requestOptions.PathParameters)
                {
                    var tempPath = requestOptions.Path.Replace(pathParam.Key, "0");
                    requestOptions.Path = string.Format(tempPath, pathParam.Value);
                }
            }

            var httpValues = HttpUtility.ParseQueryString(string.Empty);

            if (requestOptions != null)
            {
                foreach (var parameter in requestOptions.QueryParameters)
                {
#if (NETCOREAPP)
                    httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value);

                    /* if (parameter.Value.Count > 1)
                     * { // array
                     *   foreach (var value in parameter.Value)
                     *   {
                     *       httpValues.Add(HttpUtility.UrlEncode(parameter.Key) + "[]", value);
                     *   }
                     * }
                     * else
                     * {
                     *   httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]);
                     * }*/
#else
                    httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value);

                    /*  if (parameter.Value.Count > 1)
                     * { // array
                     *    foreach (var value in parameter.Value)
                     *    {
                     *        httpValues.Add(parameter.Key + "[]", value);
                     *    }
                     * }
                     * else
                     * {
                     *    httpValues.Add(parameter.Key, parameter.Value[0]);
                     * }
                     */
#endif
                }
            }
            var uriBuilder = new UriBuilder(string.Concat(requestOptions.BasePath, requestOptions.Path));
            uriBuilder.Query = httpValues.ToString().Replace("+", "%20");

            var    dateTime = DateTime.Now;
            string Digest   = string.Empty;

            //get the body
            string requestBody = string.Empty;

            /*   if (requestOptions.RequestBody != null)
             * {
             *     var serializerSettings = new JsonSerializerSettings();
             *     requestBody = JsonConvert.SerializeObject(requestOptions.RequestBody,Formatting.Indented ,serializerSettings);
             * }
             */

            requestBody = requestOptions.RequestData;

            if (HashAlgorithm == HashAlgorithmName.SHA256)
            {
                var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody);
                Digest = string.Format("SHA-256={0}", Convert.ToBase64String(bodyDigest));
            }
            else if (HashAlgorithm == HashAlgorithmName.SHA512)
            {
                var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody);
                Digest = string.Format("SHA-512={0}", Convert.ToBase64String(bodyDigest));
            }
            else
            {
                throw new Exception(string.Format("{0} not supported", HashAlgorithm));
            }


            foreach (var header in HttpSigningHeader)
            {
                if (header.Equals(HEADER_REQUEST_TARGET))
                {
                    var targetUrl = string.Format("{0} {1}{2}", requestOptions.Method.ToLower(), uriBuilder.Path, uriBuilder.Query);
                    HttpSignatureHeader.Add(header.ToLower(), targetUrl);
                }
                else if (header.Equals(HEADER_EXPIRES))
                {
                    var expireDateTime = dateTime.AddSeconds(SignatureValidityPeriod);
                    HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(expireDateTime).ToString());
                }
                else if (header.Equals(HEADER_DATE))
                {
                    var utcDateTime = dateTime.ToUniversalTime().ToString("r");
                    HttpSignatureHeader.Add(header.ToLower(), utcDateTime);
                    HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime);
                }
                else if (header.Equals(HEADER_HOST))
                {
                    HttpSignatureHeader.Add(header.ToLower(), uriBuilder.Host);
                    HttpSignedRequestHeader.Add(HEADER_HOST, uriBuilder.Host);
                }
                else if (header.Equals(HEADER_CREATED))
                {
                    HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(dateTime).ToString());
                }
                else if (header.Equals(HEADER_DIGEST))
                {
                    HttpSignedRequestHeader.Add(HEADER_DIGEST, Digest);
                    HttpSignatureHeader.Add(header.ToLower(), Digest);
                }
                else
                {
                    bool isHeaderFound = false;
                    foreach (var item in requestOptions.HeaderParameters)
                    {
                        if (string.Equals(item.Key, header, StringComparison.OrdinalIgnoreCase))
                        {
                            HttpSignatureHeader.Add(header.ToLower(), item.Value.ToString());
                            isHeaderFound = true;
                            break;
                        }
                    }
                    if (!isHeaderFound)
                    {
                        throw new Exception(string.Format("Cannot sign HTTP request.Request does not contain the {0} header.", header));
                    }
                }
            }
            var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys);
            var headerValuesList  = new List <string>();

            foreach (var keyVal in HttpSignatureHeader)
            {
                headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value));
            }
            //Concatinate headers value separated by new line
            var    headerValuesString  = string.Join("\n", headerValuesList);
            var    signatureStringHash = GetStringHash(HashAlgorithm.ToString(), headerValuesString);
            string headerSignatureStr  = null;
            var    keyType             = GetKeyType(KeyFilePath);

            if (keyType == PrivateKeyType.RSA)
            {
                headerSignatureStr = GetRSASignature(signatureStringHash);
            }
            else if (keyType == PrivateKeyType.ECDSA)
            {
                headerSignatureStr = GetECDSASignature(signatureStringHash);
            }
            var cryptographicScheme      = "hs2019";
            var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"",
                                                         KeyId, cryptographicScheme);

            if (HttpSignatureHeader.ContainsKey(HEADER_CREATED))
            {
                authorizationHeaderValue += string.Format(",created={0}", HttpSignatureHeader[HEADER_CREATED]);
            }

            if (HttpSignatureHeader.ContainsKey(HEADER_EXPIRES))
            {
                authorizationHeaderValue += string.Format(",expires={0}", HttpSignatureHeader[HEADER_EXPIRES]);
            }

            authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"",
                                                      headersKeysString, headerSignatureStr);

            HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue);

            return(HttpSignedRequestHeader);
        }
コード例 #7
0
        protected override void ProcessRecord()
        {
            // ExecuteRequestAsync(string.Format("/api/v1/{0}",ObjectType));

            //Check the objectType in MoBaseMo.ObjectTypeEnum if it belongs to that enum
            //fetch the display name.
            //this is done to work with specific Get cmdlets.
            // Get-IntersightNtpPoicy -Name xxxx | Get-IntersightManagedObject
            var result = PSUtils.GetObjectTypeDisplayName(ObjectType);

            if (!string.IsNullOrEmpty(result))
            {
                ObjectType = result;
            }

            var psClient = new PSHttpClient(CmdletBase.Config);
            PSRequestOptions psRequestOption = new PSRequestOptions
            {
                BasePath = CmdletBase.Config.BasePath,
                Path     = string.Format("/api/v1/{0}", PSUtils.GetPath(ObjectType)),
                Method   = "Get",
            };

            if (ParameterSetName == "CmdletParam")
            {
                string queryStr = string.Empty;
                var    index    = 0;
                foreach (var item in this.MyInvocation.BoundParameters)
                {
                    if (item.Key == "ObjectType")
                    {
                        continue;
                    }
                    if (index != 0)
                    {
                        queryStr += " and ";
                    }
                    queryStr += string.Format("{0} eq \'{1}\'", item.Key, item.Value);
                    index++;
                }

                if (!string.IsNullOrEmpty(queryStr))
                {
                    psRequestOption.QueryParameters.Add("$filter", queryStr);
                }
            }
            else if (ParameterSetName == "QueryParam")
            {
                foreach (var item in this.MyInvocation.BoundParameters)
                {
                    if (item.Key == "ObjectType")
                    {
                        continue;
                    }

                    psRequestOption.QueryParameters.Add(string.Concat("$", item.Key.ToLower()), item.Value.ToString());
                }
            }

            var response = psClient.Execute(psRequestOption);

            if (!string.IsNullOrEmpty(response))
            {
                Dictionary <string, object> responseData = JsonConvert.DeserializeObject <Dictionary <string, object> >(response);
                if (ParameterSetName == "CmdletParam" && responseData.ContainsKey("Results"))
                {
                    var moList = JsonConvert.SerializeObject(responseData["Results"], Formatting.Indented);
                    WriteObject(moList);
                }
                else
                {
                    WriteObject(response);
                }
            }
        }