Generate Self-Signed Certificates for SharePoint Authentication with PowerShell
Certificate-based authentication is a secure method for connecting to SharePoint Online and Microsoft 365 services using service principals and automated scripts. This guide demonstrates two methods for generating self-signed certificates using PowerShell and how to use them with PnP PowerShell for SharePoint authentication.
Table of Contents
- Why Use Certificate-Based Authentication?
- Prerequisites
- Method 1: Using New-SelfSignedCertificate
- Method 2: Using New-PnPAzureCertificate
- Locating Your Certificate
- Exporting Certificates
- Registering Certificate with Entra ID App
- Connecting to SharePoint with Certificate
- Best Practices
- Troubleshooting
- Conclusion
- References
Why Use Certificate-Based Authentication?
Certificate-based authentication offers several advantages over traditional username/password authentication:
- ✅ Enhanced Security: No passwords stored in scripts or configuration files
- ✅ Automation-Friendly: Ideal for scheduled tasks and CI/CD pipelines
- ✅ No MFA Interruptions: Certificates bypass multi-factor authentication prompts
- ✅ Audit Trail: Better tracking of service principal activities
- ✅ Compliance: Meets enterprise security requirements for automated access
Use Cases:
- SharePoint automation scripts
- Azure DevOps pipelines
- Scheduled PowerShell tasks
- Service principal authentication
- Tenant-to-tenant migrations
Prerequisites
Before generating certificates, ensure you have:
- PowerShell 5.1 or later (or PowerShell 7+)
- Administrative privileges on your local machine
- PnP PowerShell module (for Method 2):
Install-Module -Name PnP.PowerShell -Scope CurrentUser - Entra ID App Registration with appropriate SharePoint permissions
- Application Administrator or Global Administrator role (to upload certificate to Entra ID)
Method 1: Using New-SelfSignedCertificate
The New-SelfSignedCertificate cmdlet is a native PowerShell command available in Windows that provides fine-grained control over certificate generation.
Benefits of This Method
- Built into Windows (no additional modules required)
- Highly customizable parameters
- Direct control over certificate properties
- Suitable for production environments
Generate the Certificate
# Generate a self-signed certificate with custom parameters
$cert = New-SelfSignedCertificate `
-Subject "CN=MyAppName" `
-CertStoreLocation "Cert:\CurrentUser\My" `
-KeyExportPolicy Exportable `
-KeyLength 2048 `
-KeyAlgorithm RSA `
-HashAlgorithm SHA256 `
-NotAfter (Get-Date).AddYears(1)
# Display certificate details
$cert | Format-List Subject, Thumbprint, NotAfter
Parameter Explanation
| Parameter | Description |
|---|---|
-Subject | The certificate’s subject name (Common Name). Use a descriptive name for your application. |
-CertStoreLocation | Where to store the certificate. CurrentUser\My stores it in your personal certificate store. |
-KeyExportPolicy | Set to Exportable to allow exporting the private key later. |
-KeyLength | Key size in bits. 2048 is the minimum recommended; 4096 for higher security. |
-KeyAlgorithm | Cryptographic algorithm. RSA is the standard. |
-HashAlgorithm | Hashing algorithm. SHA256 is secure and widely supported. |
-NotAfter | Certificate expiration date. Adjust the years as needed. |
Export Certificate and Private Key
# Set a strong password for the PFX file
$certPassword = ConvertTo-SecureString "YourStrongPassword123!" -AsPlainText -Force
# Export certificate with private key (PFX)
Export-PfxCertificate -Cert $cert -FilePath ".\MyAppCert.pfx" -Password $certPassword
# Export public key certificate (CER) for Entra ID
Export-Certificate -Cert $cert -FilePath ".\MyAppCert.cer"
Write-Host "Certificate exported successfully!" -ForegroundColor Green
Write-Host "PFX File: MyAppCert.pfx" -ForegroundColor Cyan
Write-Host "CER File: MyAppCert.cer" -ForegroundColor Cyan
Method 2: Using New-PnPAzureCertificate
The New-PnPAzureCertificate cmdlet from PnP PowerShell is specifically designed for creating certificates for Azure/Entra ID application authentication.
Benefits of This Method
- Simplified command with sensible defaults
- Automatically generates both PFX and CER files
- Includes Subject Alternative Names (SANs) by default
- Optimized for PnP PowerShell workflows
Generate the Certificate
# Generate certificate with PnP PowerShell
New-PnPAzureCertificate `
-OutPfx "pnp.pfx" `
-OutCert "pnp.cer" `
-CertificatePassword (ConvertTo-SecureString -String "Pass@word123!" -AsPlainText -Force) `
-CommonName "MyPnPApp" `
-ValidYears 2
What This Command Creates
✅ PFX File (pnp.pfx): Contains the private key and certificate, protected by the password
✅ CER File (pnp.cer): Contains only the public key certificate for uploading to Entra ID
✅ Certificate Store: Automatically installs the certificate in your personal store
Default Configuration:
- Common Name:
pnp.contoso.com(customizable with-CommonName) - Validity Period: 10 years (customizable with
-ValidYears) - Subject Alternative Names: Includes
localhostand the machine name - Key Length: 2048 bits
Advanced Options
# Generate with custom settings
New-PnPAzureCertificate `
-OutPfx "production-app.pfx" `
-OutCert "production-app.cer" `
-CertificatePassword (ConvertTo-SecureString -String "ComplexP@ssw0rd!" -AsPlainText -Force) `
-CommonName "ProductionSharePointApp" `
-ValidYears 1 `
-Country "US" `
-State "California" `
-Locality "San Francisco" `
-Organization "Contoso Ltd"
Locating Your Certificate
After generating a certificate, it’s stored in the Windows Certificate Store.
Open Certificate Manager
- Press
Win + Rto open the Run dialog - Type
certmgr.mscand press Enter - Navigate to: Personal > Certificates
Find Your Certificate
Look for your certificate by:
- Subject Name: The CN value you specified (e.g., “CN=MyAppName”)
- Issued Date: Should match when you created it
- Expiration Date: Based on your validity period
Using PowerShell to List Certificates
# List all personal certificates
Get-ChildItem -Path Cert:\CurrentUser\My |
Select-Object Subject, Thumbprint, NotAfter |
Format-Table -AutoSize
# Find specific certificate by subject name
Get-ChildItem -Path Cert:\CurrentUser\My |
Where-Object { $_.Subject -like "*MyAppName*" } |
Format-List Subject, Thumbprint, NotAfter, HasPrivateKey
Exporting Certificates
If you need to export certificates after creation:
Export with PowerShell
# Get the certificate by thumbprint
$thumbprint = "YOUR_CERTIFICATE_THUMBPRINT"
$cert = Get-ChildItem -Path Cert:\CurrentUser\My\$thumbprint
# Set password for PFX
$password = ConvertTo-SecureString "SecurePassword123!" -AsPlainText -Force
# Export PFX (with private key)
Export-PfxCertificate -Cert $cert -FilePath ".\exported-cert.pfx" -Password $password
# Export CER (public key only)
Export-Certificate -Cert $cert -FilePath ".\exported-cert.cer"
Export via Certificate Manager
- Open
certmgr.msc - Right-click your certificate
- Select All Tasks > Export
- Follow the Certificate Export Wizard
- Choose to export the private key (PFX) or just the certificate (CER)
Registering Certificate with Entra ID App
To use certificate authentication, you must register the certificate with your Entra ID application.
Upload Certificate to Entra ID
- Navigate to Azure Portal
- Go to Entra ID > App registrations
- Select your application
- Click Certificates & secrets
- Under Certificates, click Upload certificate
- Select your
.cerfile and upload - Copy the Thumbprint value for later use
Using PowerShell to Upload
# Install the Microsoft Graph module if needed
Install-Module Microsoft.Graph -Scope CurrentUser
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Application.ReadWrite.All"
# Upload certificate to app registration
$appId = "YOUR_APP_ID"
$certPath = ".\MyAppCert.cer"
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath)
$keyCredential = @{
Type = "AsymmetricX509Cert"
Usage = "Verify"
Key = $cert.GetRawCertData()
}
Update-MgApplication -ApplicationId $appId -KeyCredentials $keyCredential
Connecting to SharePoint with Certificate
Once your certificate is registered, you can use it to authenticate to SharePoint.
Method 1: Using Certificate Path
# Define connection parameters
$tenantId = "your-tenant-id"
$clientId = "your-client-id"
$certPath = ".\pnp.pfx"
$certPassword = ConvertTo-SecureString "Pass@word123!" -AsPlainText -Force
$siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite"
# Connect using certificate file
Connect-PnPOnline -Url $siteUrl `
-ClientId $clientId `
-Tenant $tenantId `
-CertificatePath $certPath `
-CertificatePassword $certPassword
# Verify connection
Get-PnPWeb | Select-Object Title, Url
Method 2: Using Certificate Thumbprint
# Connect using certificate from the store
$thumbprint = "YOUR_CERTIFICATE_THUMBPRINT"
Connect-PnPOnline -Url $siteUrl `
-ClientId $clientId `
-Tenant $tenantId `
-Thumbprint $thumbprint
# Test the connection
Write-Host "Connected to:" (Get-PnPWeb).Title -ForegroundColor Green
Method 3: Using Certificate Object
# Load certificate from file
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(
".\pnp.pfx",
"Pass@word123!"
)
# Connect using certificate object
Connect-PnPOnline -Url $siteUrl `
-ClientId $clientId `
-Tenant $tenantId `
-Certificate $cert
Best Practices
Security Best Practices
Use Strong Passwords: Always use complex passwords for PFX files
# Good: Complex password $password = ConvertTo-SecureString "C0mpl3x!P@ssw0rd#2025" -AsPlainText -Force # Bad: Simple password $password = ConvertTo-SecureString "password" -AsPlainText -ForceSecure Certificate Storage:
- Store PFX files in encrypted locations
- Use Azure Key Vault for production environments
- Never commit certificates to source control
- Set appropriate file permissions
Certificate Expiration:
- Set calendar reminders before expiration
- Implement monitoring for certificate expiry
- Plan certificate rotation strategy
Key Length:
- Minimum 2048 bits for RSA
- Consider 4096 bits for high-security scenarios
Operational Best Practices
- Environment-Specific Certificates: Use different certificates for dev, test, and production
- Naming Conventions: Use descriptive names that indicate purpose and environment
- Documentation: Maintain an inventory of certificates, their purposes, and expiration dates
- Backup: Store backup copies of certificates in a secure location
- Rotation: Establish a certificate rotation schedule before expiration
Example: Secure Certificate Management Script
# Secure certificate generation and storage
$params = @{
Subject = "CN=Production-SharePoint-App"
CertStoreLocation = "Cert:\CurrentUser\My"
KeyExportPolicy = "Exportable"
KeyLength = 4096
KeyAlgorithm = "RSA"
HashAlgorithm = "SHA256"
NotAfter = (Get-Date).AddMonths(11) # Rotate before 1 year
}
$cert = New-SelfSignedCertificate @params
# Secure password generation
Add-Type -AssemblyName System.Web
$securePassword = [System.Web.Security.Membership]::GeneratePassword(20, 5)
$certPassword = ConvertTo-SecureString $securePassword -AsPlainText -Force
# Export to secure location
$securePath = "$env:LOCALAPPDATA\Certificates"
if (-not (Test-Path $securePath)) {
New-Item -ItemType Directory -Path $securePath -Force | Out-Null
}
Export-PfxCertificate -Cert $cert -FilePath "$securePath\prod-cert.pfx" -Password $certPassword
Export-Certificate -Cert $cert -FilePath "$securePath\prod-cert.cer"
# Log certificate details
$logEntry = @{
Thumbprint = $cert.Thumbprint
Subject = $cert.Subject
NotAfter = $cert.NotAfter
CreatedDate = Get-Date
} | ConvertTo-Json
$logEntry | Out-File "$securePath\cert-inventory.log" -Append
Write-Host "Certificate created successfully!" -ForegroundColor Green
Write-Host "Thumbprint: $($cert.Thumbprint)" -ForegroundColor Cyan
Write-Host "Expires: $($cert.NotAfter)" -ForegroundColor Yellow
Troubleshooting
Common Issues and Solutions
Issue 1: “Certificate not found” Error
Symptoms:
Connect-PnPOnline: Certificate with thumbprint 'XXX' not found
Solutions:
# Verify certificate exists in the store
Get-ChildItem -Path Cert:\CurrentUser\My |
Where-Object { $_.Thumbprint -eq "YOUR_THUMBPRINT" }
# Ensure you're looking in the correct certificate store
# Try CurrentUser and LocalMachine stores
Get-ChildItem -Path Cert:\LocalMachine\My
Issue 2: “Access Denied” When Connecting
Causes:
- Certificate not uploaded to Entra ID app
- App doesn’t have required SharePoint permissions
- Incorrect Client ID or Tenant ID
Solutions:
- Verify certificate is uploaded in Azure Portal
- Check API permissions in Entra ID app registration
- Ensure app has been granted admin consent
- Verify Client ID and Tenant ID are correct
Issue 3: Private Key Not Exportable
Error:
Export-PfxCertificate: Cannot export non-exportable private key
Solution:
# Recreate certificate with -KeyExportPolicy Exportable
$cert = New-SelfSignedCertificate `
-Subject "CN=MyApp" `
-CertStoreLocation "Cert:\CurrentUser\My" `
-KeyExportPolicy Exportable # Critical parameter
Issue 4: Certificate Expired
Check Expiration:
$cert = Get-ChildItem -Path Cert:\CurrentUser\My |
Where-Object { $_.Subject -like "*MyApp*" }
if ($cert.NotAfter -lt (Get-Date)) {
Write-Host "Certificate expired on: $($cert.NotAfter)" -ForegroundColor Red
Write-Host "Generate a new certificate and update Entra ID" -ForegroundColor Yellow
}
Issue 5: PFX Password Forgotten
Solution: Unfortunately, there’s no way to recover a forgotten PFX password. You must:
- Generate a new certificate
- Export with a new password
- Update the certificate in Entra ID app registration
Conclusion
Certificate-based authentication provides a secure and automation-friendly method for connecting to SharePoint Online and Microsoft 365 services. Whether you use the native New-SelfSignedCertificate cmdlet or the PnP-specific New-PnPAzureCertificate, both methods create robust self-signed certificates suitable for service principal authentication.
Key Takeaways:
✅ Use certificate-based auth for automated scripts and CI/CD pipelines
✅ Choose 2048-bit or 4096-bit key lengths for security
✅ Store certificates securely and never commit to source control
✅ Monitor certificate expiration and plan rotation strategy
✅ Upload the public certificate (.cer) to Entra ID, keep private key (.pfx) secure
✅ Test connections in development before deploying to production
References
- New-SelfSignedCertificate Official Documentation
- New-PnPAzureCertificate Documentation
- Connect-PnPOnline Documentation
- How to Generate a Self-Signed Certificate in Windows
- Certificate-Based Authentication for Apps
- PnP PowerShell Overview
- Azure Key Vault for Certificate Management