function/microsoft365/New-AzureADApplicationCertificate.ps1
Function New-AzureADApplicationCertificate { <# .SYNOPSIS Create / Renew Azure Certificate based access .DESCRIPTION Create new self signed certificate and create azure application key for certificate based access. .PARAMETER Name Name of the new created certificate .PARAMETER ObjectId Azure AD Application Object ID .PARAMETER KeyExportPolicy Export Policy for the Certificate .PARAMETER CertLifeTime Certificate lifetime as datetime object .OUTPUTS System.Object[] .EXAMPLE New-AzureADApplicationCertificate -Name newcert -ApplicationId "4564dsf2-9571-4e21-89b3-31d54642f06f" -KeyExportPolicy Exportable -CertLifeTime (Get-Date).AddYears(1) .LINK https://github.com/gisp497/psgisp #> [CmdletBinding(SupportsShouldProcess)] param ( [Parameter( Mandatory = $true, HelpMessage = "Name of the new created certificate" )] [string]$Name, [Parameter( Mandatory = $true, HelpMessage = "Azure AD Application Object ID" )] $ObjectId, [Parameter( Mandatory = $false, HelpMessage = "Export Policy for the Certificate" )] [ValidateSet('Exportable', 'ExportableEncrypted', 'NonExportable')] [string]$KeyExportPolicy = 'Exportable', [Parameter( Mandatory = $false, HelpMessage = "Certificate lifetime" )] [datetime]$CertLifeTime = (Get-Date).AddYears(1) ) Begin { #Connect to Azure AD before using this function try { $null = Get-AzureADTenantDetail -ErrorAction Stop }catch{ Throw "You need to connect to Azure AD to use this function." } } Process { #create self signed cert try { $Certificate = New-SelfSignedCertificate -CertStoreLocation cert:\CurrentUser\my -DnsName $Name -KeyExportPolicy $KeyExportPolicy -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $CertLifeTime $KeyValue = [System.Convert]::ToBase64String($Certificate.GetRawCertData()) } catch { Throw "Can't create self signed certificate: $_" } #Create Azure application keycredential try { $KeyCredential = New-AzureADApplicationKeyCredential -ObjectId $ObjectId -CustomKeyIdentifier $Name -EndDate $Certificate.NotAfter -Type AsymmetricX509Cert -Usage Verify -Value $KeyValue } catch { Throw "Can't create new Azure AD Application Key Credential: $_" } #create output object $OutputObject = New-Object -TypeName psobject Add-Member -InputObject $OutputObject -MemberType NoteProperty -Name 'Thumbprint' -Value $Certificate.Thumbprint Add-Member -InputObject $OutputObject -MemberType NoteProperty -Name 'KeyId' -Value $KeyCredential.KeyId } End { Return $OutputObject } } |