Skip to content

Instantly share code, notes, and snippets.

@gregjhogan
Created July 19, 2017 05:20
Show Gist options
  • Select an option

  • Save gregjhogan/6e5496d9858e007dbda1448fa04a48ea to your computer and use it in GitHub Desktop.

Select an option

Save gregjhogan/6e5496d9858e007dbda1448fa04a48ea to your computer and use it in GitHub Desktop.
Setup service principal with self-signed certificate for authentication
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