Created
July 19, 2017 05:20
-
-
Save gregjhogan/6e5496d9858e007dbda1448fa04a48ea to your computer and use it in GitHub Desktop.
Setup service principal with self-signed certificate for authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Set-StrictMode -Version Lastest | |
| $ErrorActionPreference = "Stop" | |
| Logon-AzureRmAccount | |
| $appId = Read-Host "Enter application ID of service principal" | |
| $adApp = (Get-AzureRmADApplication -ApplicationId $appId)[0] | |
| $spnId = (Get-AzureRmADServicePrincipal -ServicePrincipalName $adApp.IdentifierUris[0])[0].ApplicationId.Guid | |
| $endDate = (Get-Date).AddYears(1) | |
| $certSelfSigned = New-SelfSignedCertificate -Subject $spnId -CertStoreLocation Cert:\CurrentUser\My -NotAfter $endDate -KeyExportPolicy Exportable -Type CodeSigningCert -KeySpec Signature | |
| $publicKey = [System.Convert]::ToBase64String($certSelfSigned.GetRawCertData()) | |
| New-AzureRmADSpCredential -ServicePrincipalObjectId $spnId -CertValue $publicKey -EndDate $endDate | |
| # TEST: Login-AzureRmAccount -ServicePrincipal -CertificateThumbprint $certSelfSigned.Thumbprint -ApplicationId $appId -TenantId <guid> | |
| $storeLocation = [Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser | |
| $storeName = [Security.Cryptography.X509Certificates.StoreName]::My | |
| $store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store @($storeName, $storeLocation) | |
| $store.Open([Security.Cryptography.X509Certificates.OpenFlags]::OpenExistingOnly) | |
| $findType = [System.Security.Cryptography.X509Certificates.X509FindType]::FindByThumbprint | |
| $cert = $store.Certificates.Find($findType, $certSelfSigned.Thumbprint, $false) | |
| $pfxBlob = [System.Convert]::ToBase64String($cert.Export([Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12)) | |
| $store.Close() | |
| "THUMBPRINT: $($certSelfSigned.Thumbprint)" | |
| "PFX BLOB: `n$pfxBlob" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment