How to Sign ASP.NET Core PDF Document using Azure Key Vault?
Syncfusion Essential® PDF is ASP.NET Core PDF used to create, read, and edit PDF documents. Using this library, you can sign a PDF document with the Azure Key Vault.
Steps to sign a PDF document using the Azure Key Vault:
- Create an Azure Active Directory Application.
1.1.Open the Azure Portal and sign in.
1.2.Search the Azure Active Directory.
1.3.Select the App registrations and choose New registration.
1.4.Name the application and choose Register.
1.5.Now, it generates the Application and Directory ID as follows, you need to copy the Application ID and backup it (requires later).
1.6.Select -> API permissions -> Add permission and choose the Azure Key Vault.
1.7.Provide full access to the Azure Key Vault service and click the Add permissions.
1.8.Select -> Certificates and secrets and choose New client secret. Now, copy the secret value and backup it (requires for later).
- Create an Azure Key Vault.
2.1In the Azure Portal search -> Key vaults and choose to Create key vault.
2.2Choose the subscription, create or select a Resource group and name the Key vault, select the Region, Pricing tier, and click next to the Access policy.
2.3In the Access policy, choose -> Add Access Policy and select the Principal as your Azure AD application (created in the first step).
2.4Choose Review and Create.
2.5Now the Key vault is added under your account.
- Upload a certificate file as a secret.
3.1Open -> Windows PowerShell in Administrator mode.
3.2Login your Azure account using the following PowerShell comment.
PS C:\> Login-AzureRmAccount
Account : msdnxxxxxxxxxx@xxxxxx.com
SubscriptionName : Microsoft Azure Enterprise
SubscriptionId : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TenantId : xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Environment : AzureCloud
3.3Add the following PowerShell comment to upload your certificate as a secret.
PS C:\> $certificateFilePath = 'D:\PDF.pfx'
PS C:\> $password = "password123"
PS C:\> $flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
PS C:\> $x509Collection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
PS C:\> $x509Collection.Import($certificateFilePath, $password, $flag)
PS C:\> $contentType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12
PS C:\> $data = $x509Collection.Export($contentType)
PS C:\> $base64Encoded = [System.Convert]::ToBase64String($data)
PS C:\> $secret = ConvertTo-SecureString -String $base64Encoded -AsPlainText -Force
PS C:\> $secretContentType = 'application/x-pkcs12'
PS C:\> Set-AzureKeyVaultSecret -VaultName 'AzureKeyVaultSign' -Name 'CertificateToSign' -SecretValue $secret -ContentType $secretContentType
The output PowerShell as follows.
- Configure the Visual Studio project.
4.1Create a new C# ASP.NET Core web application project.
4.2Install the following NuGet packages as a reference in your web application project from the NuGet.org.
4.2.1Microsoft.Azure.KeyVault.
4.2.2Microsoft.IdentityModel.Clients.ActiveDirectory.
4.2.3Syncfusion.Pdf.Net.Core.
4.3Include the following code in the index.cshtml file.
@Html.ActionLink("Click here to sign a PDF document using Azure Key Vault","SignPDF","Home")
4.4Include the following namespace in the HomeController.cs file.
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AzureKeyVaultSample.Models;
using Microsoft.AspNetCore.Hosting;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.KeyVault.Models;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Security;
using System.IO;
4.5Added the following code to retrieve the certificate from Azure Key Vault.
private async Task<X509Certificate2> GetCertificateAsync()
{
//Create a new KeyVaultClient
KeyVaultClient keyVaultClient = new KeyVaultClient(async (authority, resource, scope) =>
{
AuthenticationContext authContext = new AuthenticationContext(authority);
//Application Id, Secret Id
ClientCredential clientCredential = new ClientCredential("bd7c93e3-9610-4b31-b787-200bf0fc1fb8", "A[hM2M8Y?6xS]w2vBcuJL_qy:M-IPtXz");
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCredential);
if (result == null)
throw new InvalidOperationException("Failed");
return result.AccessToken;
});
//URL and secret name
SecretBundle certificateSecret = await keyVaultClient.GetSecretAsync("https://azurekeyvaultsign.vault.azure.net", "CertificateToSign");
byte[] certificateData = Convert.FromBase64String(certificateSecret.Value);
return new X509Certificate2(certificateData, (string)null);
}
1. When programmatically signing in, you need to copy the Application Id from the Azure Active Directory application (created in step 1.5).
2. You can use the secret Id that you copied earlier in step 1.7.
4.6Add the following code to sign a PDF document using the Azure Key Vault.
public IActionResult SignPDF()
{
X509Certificate2 result = GetCertificateAsync().Result;
FileStream pdfFile = new FileStream(_hostingEnvironment.WebRootPath + "/Input.pdf", FileMode.Open);
//Load the PDF document.
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(pdfFile);
//Load the existing page.
PdfLoadedPage page = loadedDocument.Pages[0] as PdfLoadedPage;
//Create as PdfCertificate object.
PdfCertificate certificate = new PdfCertificate(result);
//Create a new PDF signature object.
PdfSignature signature = new PdfSignature(loadedDocument, page, certificate, "Sig1");
signature.Bounds = new Syncfusion.Drawing.RectangleF(0, 0, 200, 100);
MemoryStream ms = new MemoryStream();
//Save and close the document.
loadedDocument.Save(ms);
ms.Position = 0;
loadedDocument.Close(true);
return File(ms, "application/pdf", "SignedDocument.pdf");
}
You can download the working sample from AzureKeyVaultSample.
By executing the program, you will get the PDF document as follows.
Take a moment to peruse the documentation, where you will find other options like digitally sign a pdf file, digitally sign an existing pdf document, remove the digital signature from an existing pdf document, and more with code examples.
Click here to explore the rich set of Syncfusion Essential® PDF features.
See Also:
How to digitally sign an existing PDF document using C# and VB.NET.
How to digitally sign a PDF file in C#, VB.NET.
How to apply one or more digital signatures to a PDF using C# and VB.NET.
PDF digital signature and timestamp in .NET.
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or the NuGet feed, include a license key in your projects. Refer to this link to learn about generating and registering the Syncfusion® license key in your application to use the components without trail message.
Conclusion
I hope you enjoyed learning about how to sign ASP.NET Core PDF document using Azure Key Vault.
You can refer to our ASP.NET Core PDF feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core PDF Viewer example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!