示例#1
0
        public override void ExecuteCmdlet()
        {
            if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName))
            {
                string         certName   = null;
                HttpStatusCode statusCode = HttpStatusCode.OK;
                var            webApp     = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, Slot));
                var            location   = webApp.Location;

                var certificate = new Certificate(
                    webApp.Location,
                    type: "Microsoft.Web/certificates",
                    canonicalName: HostName,
                    password: "",
                    serverFarmId: webApp.ServerFarmId);

                PSCertificate createdCertdetails = new PSCertificate(certificate);

                if (this.ShouldProcess(this.WebAppName, string.Format($"Creating an App service managed certificate for Web App '{WebAppName}'")))
                {
                    try
                    {
                        //Default certName is HostName
                        certName           = Name != null ? Name : HostName;
                        createdCertdetails = new PSCertificate(WebsitesClient.CreateCertificate(ResourceGroupName, certName, certificate));
                    }
                    catch (DefaultErrorResponseException e)
                    {
                        statusCode = e.Response.StatusCode;
                        // 'Conflict' exception is thrown when certificate already exists. Let's swallow it and continue.
                        //'Accepted' exception is thrown by default for create cert method.
                        if (e.Response.StatusCode != HttpStatusCode.Conflict &&
                            e.Response.StatusCode != HttpStatusCode.Accepted)
                        {
                            throw;
                        }
                        if (e.Response.StatusCode == HttpStatusCode.Accepted)
                        {
                            var        poll_url = e.Response.Headers["Location"].FirstOrDefault();
                            var        token    = WebsitesClient.GetAccessToken(DefaultContext);
                            HttpClient client   = new HttpClient();
                            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.AccessToken);

                            HttpResponseMessage r;
                            int numChecks = 0;
                            do
                            {
                                Thread.Sleep(TimeSpan.FromSeconds(5));
                                r = client.GetAsync(poll_url).Result;
                                numChecks++;
                            } while (r.StatusCode == HttpStatusCode.Accepted && numChecks < NumStatusChecks);

                            if (r.StatusCode == HttpStatusCode.Accepted && numChecks >= NumStatusChecks)
                            {
                                var rec = new ErrorRecord(new Exception(string.Format($"The creation of the managed certificate '{this.HostName}' is taking longer than expected." +
                                                                                      $" Please re-try the operation '{CreateInputCommand()}'")),
                                                          string.Empty, ErrorCategory.OperationTimeout, null);
                                WriteError(rec);
                            }
                        }
                    }
                    createdCertdetails = new PSCertificate(WebsitesClient.GetCertificate(ResourceGroupName, certName));

                    //Add only when user is opted for Binding
                    if (AddBinding)
                    {
                        WebsitesClient.UpdateHostNameSslState(ResourceGroupName,
                                                              WebAppName,
                                                              Slot,
                                                              webApp.Location,
                                                              HostName, SslState.HasValue ? SslState.Value : Management.WebSites.Models.SslState.SniEnabled,
                                                              createdCertdetails.Thumbprint);
                    }
                    WriteObject(createdCertdetails);
                }
            }
        }
示例#2
0
        protected override void ProcessRecord()
        {
            if (ParameterSetName != ParameterSet1Name &&
                ParameterSetName != ParameterSet2Name &&
                ParameterSetName != ParameterSet3Name &&
                ParameterSetName != ParameterSet4Name)
            {
                throw new ValidationMetadataException("Please input web app and certificate.");
            }

            if (ParameterSetName == ParameterSet3Name ||
                ParameterSetName == ParameterSet4Name)
            {
                CmdletHelpers.ExtractWebAppPropertiesFromWebApp(WebApp, out resourceGroupName, out webAppName, out slot);
            }
            else
            {
                resourceGroupName = ResourceGroupName;
                webAppName        = WebAppName;
                slot = Slot;
            }

            string thumbPrint = null;
            var    webapp     = WebsitesClient.GetWebApp(resourceGroupName, webAppName, slot);

            switch (ParameterSetName)
            {
            case ParameterSet1Name:
            case ParameterSet3Name:
                var certificateBytes   = File.ReadAllBytes(CertificateFilePath);
                var certificateDetails = new X509Certificate2(certificateBytes, CertificatePassword);

                var certificateName = GenerateCertName(certificateDetails.Thumbprint, webapp.HostingEnvironmentProfile != null ? webapp.HostingEnvironmentProfile.Name : null, webapp.Location, resourceGroupName);
                var certificate     = new Certificate
                {
                    PfxBlob  = Convert.ToBase64String(certificateBytes),
                    Password = CertificatePassword,
                    Location = webapp.Location
                };

                if (webapp.HostingEnvironmentProfile != null)
                {
                    certificate.HostingEnvironmentProfile = webapp.HostingEnvironmentProfile;
                }

                var certificateResourceGroup = CmdletHelpers.GetResourceGroupFromResourceId(webapp.ServerFarmId);
                try
                {
                    WebsitesClient.CreateCertificate(certificateResourceGroup, certificateName, certificate);
                }
                catch (CloudException e)
                {
                    // This exception is thrown when certificate already exists. Let's swallow it and continue.
                    if (e.Response.StatusCode != HttpStatusCode.Conflict)
                    {
                        throw;
                    }
                }

                thumbPrint = certificateDetails.Thumbprint;
                break;

            case ParameterSet2Name:
            case ParameterSet4Name:
                thumbPrint = Thumbprint;
                break;
            }

            WriteObject(CmdletHelpers.GetHostNameSslStatesFromSiteResponse(
                            WebsitesClient.UpdateHostNameSslState(
                                resourceGroupName,
                                webAppName,
                                slot,
                                webapp.Location,
                                Name,
                                SslState.HasValue ? SslState.Value : Management.WebSites.Models.SslState.SniEnabled,
                                thumbPrint),
                            Name));
        }
示例#3
0
        public override void ExecuteCmdlet()
        {
            if (!string.IsNullOrWhiteSpace(ResourceGroupName) && !string.IsNullOrWhiteSpace(WebAppName))
            {
                string kvId = string.Empty, kvRgName = string.Empty, kvSubscriptionId = string.Empty;
                var    webApp            = new PSSite(WebsitesClient.GetWebApp(ResourceGroupName, WebAppName, Slot));
                var    location          = webApp.Location;
                var    serverFarmId      = webApp.ServerFarmId;
                var    keyvaultResources = this.ResourcesClient.ResourceManagementClient.FilterResources(new FilterResourcesOptions
                {
                    ResourceType = "Microsoft.KeyVault/Vaults"
                }).ToArray();

                foreach (var kv in keyvaultResources)
                {
                    if (kv.Name == KeyVaultName)
                    {
                        kvId     = kv.Id;
                        kvRgName = kv.ResourceGroupName;
                        break;
                    }
                }
                if (string.IsNullOrEmpty(kvId))
                {
                    kvId = KeyVaultName;
                    if (CmdletHelpers.IsValidAKVResourceId(kvId))
                    {
                        var details = CmdletHelpers.GetResourceDetailsFromResourceId(kvId);
                        kvRgName         = details.ResourceGroupName;
                        KeyVaultName     = details.ResourceName;
                        kvSubscriptionId = details.Subscription;
                    }
                    else //default to AppService RG
                    {
                        kvRgName = ResourceGroupName;
                    }
                }
                var kvpermission = CmdletHelpers.CheckServicePrincipalPermissions(this.ResourcesClient, this.KeyvaultClient, kvRgName, KeyVaultName, kvSubscriptionId);
                var lnk          = "https://azure.github.io/AppService/2016/05/24/Deploying-Azure-Web-App-Certificate-through-Key-Vault.html";
                if (kvpermission.ToLower() != "get")
                {
                    WriteWarning("Unable to verify Key Vault permissions.");
                    WriteWarning("You may need to grant Microsoft.Azure.WebSites service principal the Secret:Get permission");
                    WriteWarning(string.Format("Find more details here: '{0}'", lnk));
                }

                Certificate kvc         = null;
                var         certificate = new Certificate(
                    location: location,
                    keyVaultId: kvId,
                    password: "",
                    keyVaultSecretName: CertName,
                    serverFarmId: serverFarmId
                    );

                if (this.ShouldProcess(this.WebAppName, string.Format($"Importing keyvault certificate for Web App '{WebAppName}'")))
                {
                    try
                    {
                        kvc = WebsitesClient.CreateCertificate(ResourceGroupName, CertName, certificate);
                    }
                    catch (DefaultErrorResponseException e)
                    {
                        if (e.Response.StatusCode != HttpStatusCode.Conflict)
                        {
                            throw e;
                        }
                    }
                }
                WriteObject(kvc);
            }
        }