Create a Application in Azure AD with Azure PowerShell Certificate authentication - azure

I was trying to Create a Application in Azure AD with Azure PowerShell Certificate authentication, below is the Powershell snippet:
Login-AzureRmAccount
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("PATH_TO_CER_FILE")
$key = [System.Convert]::ToBase64String($cert.GetRawCertData())
$app = New-AzureRmADApplication -DisplayName "SetupTet4" -HomePage "http://localhost" -IdentifierUris "http://localhost" -KeyValue $key -KeyType AsymmetricX509Cert
New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
New-AzureRmRoleAssignment -RoleDefinitionName "Owner" -ServicePrincipalName $app.ApplicationId
the Azure AD application was created successfully, however for Azure AD application with Certificate Authentication, the customKeyIdentifier and value of in the keyCredentials is null after creation, this is the portion of manifest of my application I downloaded from Azure portal:
"keyCredentials": [{
"customKeyIdentifier": null,
"endDate": "2017-02-25T20:48:35.5174541Z",
"keyId": "575580cc-ce4e-4862-ad3e-1ba5833fe7f6",
"startDate": "2016-02-25T20:48:35.5174541Z",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"value": null
}],
FYI the certificate is a self signed certificate I use makecert command generated locally.
Any advice, great appreciate.
James

Add a call to Set-AzureRmKeyVaultAccessPolicy to specify the access level you want the service principle to have for the key vault. See the changes in the last two lines for your script.
Login-AzureRmAccount
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("PATH_TO_CER_FILE")
$key = [System.Convert]::ToBase64String($cert.GetRawCertData())
$app = New-AzureRmADApplication -DisplayName "SetupTet4" -HomePage "http://localhost" -IdentifierUris "http://localhost" -KeyValue $key -KeyType AsymmetricX509Cert
$sp = New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId
Set-AzureRmKeyVaultAccessPolicy -VaultName "<your-vault-name>" `
-ServicePrincipalName $sp.ServicePrincipalName `
-PermissionsToKeys all -PermissionsToSecrets all `
-ResourceGroupName "<your-resource-group-name>"

Related

Can't Connect to Exchange Online with a private certificate at Poweshell

I'm trying to create powershell script with the next flow.
Login to Azure Active Directory via Application.
Create Private Certificate.
Upload Certificate to Azure AD Application Certificates.
Connect to ExchangeOnline.
For this I created the next sсript according to the steps:
1st Step:
$clientId = 'xxx'
$tenantId = 'xxx'
$clientSecret = 'xxx'
$org = 'xxx.onmicrosoft.com'
$clientSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
$credObject = New-Object System.Management.Automation.PSCredential ($clientId, $clientSecret)
Connect-AzAccount -Credential $credObject -Tenant $tenantId -ServicePrincipal
2nd and 3d Step:
$cert = New-SelfSignedCertificate -DnsName $org -NotAfter (Get-Date).AddYears(1) -KeySpec KeyExchange
$binCert = $cert.GetRawCertData()
$credValue = [System.Convert]::ToBase64String($binCert)
$validFrom = [datetime]::Parse($cert.GetEffectiveDateString())
$validTo = [datetime]::Parse($pfx.GetExpirationDateString())
$validTo = $validTo.AddDays(-1);
New-AzADAppCredential -ApplicationId $clientId -CertValue $credValue -StartDate $validFrom -EndDate $validTo
And up to now all is going fine. I can see this certificate at certificates list of Application.
But when I'm going to connect to MS Exchange Online with this command:
Connect-ExchangeOnline -Certificate $cert -AppID $clientId -Organization $org
i getting the next issue:
{
"error":"invalid_client",
"error_description":"xxx: Client assertion contains an invalid signature. [Reason - The key used is expired., Thumbprint of key used by client: 'xxx', Found key 'Start=03/11/2021 14:59:26, End=03/11/2022 13:09:26', Please visit the Azure Portal, Graph Explorer or directly use MS Graph to see configured keys for app Id 'xxx'. Review the documentation at https://learn.microsoft.com/en-us/graph/deployments to determine the corresponding service endpoint and https://learn.microsoft.com/en-us/graph/api/application-get?view=graph-rest-1.0&tabs=http to build a query request URL, such as 'https://graph.microsoft.com/beta/applications/xxx']\r\nTrace ID: xxxx\r\nCorrelation ID: xxx\r\nTimestamp: 2021-03-11 13:15:28Z",
"error_codes":[
700027
],
"timestamp":"2021-03-11 13:15:28Z",
"trace_id":"xxx",
"correlation_id":"xxx",
"error_uri":"https://login.microsoftonline.com/error?code=700027"
}
But this newly created certificate could not expire. I'll be glad to see any idea. Stacked with this for few days.
EDIT:
Also i admitted that if i uploading newly created certificate with UI but not with this command:
New-AzADAppCredential -ApplicationId $clientId -CertValue $credValue -StartDate $validFrom -EndDate $validTo
Then i can to exchange online with newly created certificate
The issue lies on $validTo = $validTo.AddDays(-1);. As a result, $validTo is earlier than $cert.NotAfter.
Please modify the script like this:
$cert = New-SelfSignedCertificate -DnsName $org -CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date).AddYears(1) -KeySpec KeyExchange
$binCert = $cert.GetRawCertData()
$credValue = [System.Convert]::ToBase64String($binCert)
New-AzADAppCredential -ApplicationId $clientId -CertValue $credValue -StartDate $cert.NotBefore -EndDate $cert.NotAfter

How to Add Api Permissions to an Azure App Registration using PowerShell

I am figure out the commands in Azure PowerShell to add an the User.Read Ape Permission to my App Registration in Azure.
I can find some examples using *Azure, but would prefer one that uses the *Az commands, e.g. https://learn.microsoft.com/en-us/powershell/azure/?view=azps-2.8.0.
Wonder if anybody knows how to do this? Thanks!
This can currently only be achieved using the Azure AD PowerShell. Please note that there is a difference between Azure AD PowerShell and Azure PowerShell. The Azure AD PowerShell is not simply the old Azure PowerShell module.
Azure AD PowerShell is a separate module. There is no "AZ*" for Azure AD yet. Only couple of most commonly used commands, that have Azure Resource Provider implementation.
Azure PowerShell has a limited set of features for working with Azure AD. If you need more features, like the one you mention, you must use Azure AD PowerShell. Azure AD PowerShell is not depricated and is the officially supported PowerShell module for working with Azure AD.
You can manage these required permissions by the Set-AzureAdApplication cmdlet and passing proper -RequiredResourceAccess object.
In order to construct this object, you must first get a reference to "exposed" permissions. Because permissions are exposed by other service principals.
as I cannot upload whole file, here is a PowerShell script that creates a sample application with required permission to some MS Graph and some Power BI permissions.
Function GetToken
{
param(
[String] $authority = "https://login.microsoftonline.com/dayzure.com/oauth2/token",
[String] $clientId,
[String] $clientSecret,
[String] $resourceId = "https://graph.windows.net"
)
$scope = [System.Web.HttpUtility]::UrlEncode($resourceId)
$encSecret = [System.Web.HttpUtility]::UrlEncode($clientSecret)
$body = "grant_type=client_credentials&resource=$($scope)&client_id=$($clientId)&client_secret=$($encSecret)"
$res = Invoke-WebRequest -Uri $authority -Body $body -Method Post
$authResult = $res.Content | ConvertFrom-Json
return $authResult.access_token
}
#`
# -RequiredResourceAccess #($requiredResourceAccess)
#
Function CreateChildApp
{
param (
[string] $displayName,
[string] $tenantName
)
# create your new application
Write-Output -InputObject ('Creating App Registration {0}' -f $displayName)
if (!(Get-AzureADApplication -SearchString $displayName)) {
$app = New-AzureADApplication -DisplayName $displayName `
-Homepage "https://localhost" `
-ReplyUrls "https://localhost" `
-IdentifierUris ('https://{0}/{1}' -f $tenantName, $displayName)
# create SPN for App Registration
Write-Output -InputObject ('Creating SPN for App Registration {0}' -f $displayName)
# create a password (spn key)
$appPwd = New-AzureADApplicationPasswordCredential -ObjectId $app.ObjectId
$appPwd
# create a service principal for your application
# you need this to be able to grant your application the required permission
$spForApp = New-AzureADServicePrincipal -AppId $app.AppId -PasswordCredentials #($appPwd)
}
else {
Write-Output -InputObject ('App Registration {0} already exists' -f $displayName)
$app = Get-AzureADApplication -SearchString $displayName
}
#endregion
return $app
}
Function GrantAllThePermissionsWeWant
{
param
(
[string] $targetServicePrincipalName,
$appPermissionsRequired,
$childApp,
$spForApp
)
$targetSp = Get-AzureADServicePrincipal -Filter "DisplayName eq '$($targetServicePrincipalName)'"
# Iterate Permissions array
Write-Output -InputObject ('Retrieve Role Assignments objects')
$RoleAssignments = #()
Foreach ($AppPermission in $appPermissionsRequired) {
$RoleAssignment = $targetSp.AppRoles | Where-Object { $_.Value -eq $AppPermission}
$RoleAssignments += $RoleAssignment
}
$ResourceAccessObjects = New-Object 'System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.ResourceAccess]'
foreach ($RoleAssignment in $RoleAssignments) {
$resourceAccess = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess"
$resourceAccess.Id = $RoleAssignment.Id
$resourceAccess.Type = 'Role'
$ResourceAccessObjects.Add($resourceAccess)
}
$requiredResourceAccess = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$requiredResourceAccess.ResourceAppId = $targetSp.AppId
$requiredResourceAccess.ResourceAccess = $ResourceAccessObjects
# set the required resource access
Set-AzureADApplication -ObjectId $childApp.ObjectId -RequiredResourceAccess $requiredResourceAccess
Start-Sleep -s 1
# grant the required resource access
foreach ($RoleAssignment in $RoleAssignments) {
Write-Output -InputObject ('Granting admin consent for App Role: {0}' -f $($RoleAssignment.Value))
New-AzureADServiceAppRoleAssignment -ObjectId $spForApp.ObjectId -Id $RoleAssignment.Id -PrincipalId $spForApp.ObjectId -ResourceId $targetSp.ObjectId
Start-Sleep -s 1
}
}
cls
#globaladminapp
$clientID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
$key = "****"
$tenantId = "aaaaaaaa-bbbb-xxxx-yyyy-aaaaaaaaaaaa";
$TenantName = "customdomain.com";
$AppRegName = "globaladminChild-0003";
$token = GetToken -clientId $clientID -clientSecret $key
Disconnect-AzureAD
Connect-AzureAD -AadAccessToken $token -AccountId $clientID -TenantId $tenantId
$appPermissionsRequired = #('Application.ReadWrite.OwnedBy', 'Device.ReadWrite.All', 'Domain.ReadWrite.All')
$targetServicePrincipalName = 'Windows Azure Active Directory'
#$appPermissionsRequired = #('Files.ReadWrite.All','Sites.FullControl.All','Notes.ReadWrite.All')
#$targetServicePrincipalName = 'Microsoft Graph'
$app = CreateChildApp -displayName $AppRegName -tenantName $TenantName
$spForApp = Get-AzureADServicePrincipal -Filter "DisplayName eq '$($AppRegName)'"
$appPermissionsRequired = #('Tenant.ReadWrite.All')
$targetServicePrincipalName = 'Power BI Service'
GrantAllThePermissionsWeWant -targetServicePrincipalName $targetServicePrincipalName -appPermissionsRequired $appPermissionsRequired -childApp $app -spForApp $spForApp
$appPermissionsRequired = #('Files.ReadWrite.All','Sites.FullControl.All','Notes.ReadWrite.All')
$targetServicePrincipalName = 'Microsoft Graph'
GrantAllThePermissionsWeWant -targetServicePrincipalName $targetServicePrincipalName -appPermissionsRequired $appPermissionsRequired -childApp $app -spForApp $spForApp
The interesting parts are around "apppermissionrequired" and "targetserviceprincipalname" variables.
I can't reply to Rolfo's comment directly as I don't have enough clout yet. While it's true it's not dead simple, it's possible to use both in the same session as of July 2021. Not sure this was always the case, or something was updated to allow it.
#Import modules if needed
$mList = #("AzureAD","Az.Resources","Az.Accounts")
foreach($m in $mList){if ((gmo -l $m).Count -eq 0){Install-Module -Name $m -AllowClobber -Scope CurrentUser -Force}}
#Authentication Popup
Connect-AzAccount
#Use authentication context cached from above to authenticate to AAD graph
$IDObject = Get-AzAccessToken -Resource "https://graph.windows.net"
Connect-AzureAD -AadAccessToken $IDObject.token -AccountId $IDObject.UserId
UPDATE
With the new Graph API we can use the following command to add API permissions to an App Registration/Service Principal using PowerShell. It's much simpler than the old process.
Add-AzADAppPermission -ApplicationId "$spId" -ApiId "00000009-0000-0000-c000-000000000000" -PermissionId "7504609f-c495-4c64-8542-686125a5a36f"
(This is the case for the PowerBI API)
If deploying via an Azure Devops Pipeline I often recommend using the following script to authenticate into AAD:
echo "Install Azure AD module..."
Install-Module -Name "AzureAD" -Force
Import-Module AzureAD -Force
echo "Connect Azure AD..."
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
echo $context
$graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
echo $graphToken
$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
Write-Output "Hi I'm $($context.Account.Id)"
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken
echo "Connection ends"

When are my Azure application registration/service principal credentials going to expire?

So that our Azure Web Apps can access Azure Key Vault, we use certificates and application registrations with service principals.
After generating a certificate, we use the following Azure PowerShell to create an application registration and service principal and then give the service principal access to the Azure Key Vault. The Web App then loads this certificate and uses it to authenticate with Azure Key Vault. It all works fine.
$subscriptionId = Read-Host -Prompt 'SubscriptionId'
Select-AzureRmSubscription -SubscriptionId $subscriptionId
$resourceGroupName = Read-Host -Prompt 'Resource group name'
$vaultName = Read-Host -Prompt 'Vault name'
$certificateName = Read-Host -Prompt 'Certificate name'
$applicationName = Read-Host -Prompt 'Application name'
$certificatePath = Join-Path (Get-Location) "$certificateName.cer"
$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$certificate.Import($certificatePath)
$rawCertData = [System.Convert]::ToBase64String($certificate.GetRawCertData())
$now = [System.DateTime]::UtcNow
$application = New-AzureRmADApplication -DisplayName $applicationName -HomePage "https://$applicationName" -IdentifierUris "https://$applicationName" -CertValue $rawCertData -StartDate $now -EndDate $now.AddYears(1)
$servicePrincipal = New-AzureRmADServicePrincipal -ApplicationId $application.ApplicationId
Set-AzureRmKeyVaultAccessPolicy -ResourceGroupName $resourceGroupName -VaultName $vaultName -ServicePrincipalName "https://$applicationName" -PermissionsToSecrets get
The problem is this line:
$application = New-AzureRmADApplication -DisplayName $applicationName -HomePage "https://$applicationName" -IdentifierUris "https://$applicationName" -CertValue $rawCertData -StartDate $now -EndDate $now.AddYears(1)
It sets the StartDate and EndDate to the current date and the current date plus 1 year. In hindsight I think it should have been the certificate start and end date:
$application = New-AzureRmADApplication -DisplayName $applicationName -HomePage "https://$applicationName" -IdentifierUris "https://$applicationName" -CertValue $rawCertData -StartDate` $certificate.NotBefore -EndDate $certificate.NotAfter
My question is - what will happen after $now.AddYears(1)? The certificate was created with a 3 year expiry but the application registration/service principal was created with an earlier EndDate - but what does that mean?
From the docs, it's the effective end date for the credential so I would assume the credential would stop working at that time.
https://learn.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermadapplication?view=azurermps-5.1.1
You can use New-AzureRmADAppCredential to roll the secret before that time.
https://learn.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermadappcredential?view=azurermps-5.1.1

Create an Azure AD application with KeyVault & Azure PowerShell Certificate authentication

I was trying to Create a Application in Azure AD with Azure PowerShell Certificate authentication, below is the Powershell snippet:
Login-AzureRmAccount
$certPassword = ConvertTo-SecureString $CertPassword -AsPlainText -Force
$x509 = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList $certPath,$certPassword
$credValue = [System.Convert]::ToBase64String($x509.GetRawCertData())
$adapp = New-AzureRmADApplication -DisplayName $ApplicationName -HomePage $URL -IdentifierUris $URL -CertValue $credValue -StartDate $startDate -EndDate $endDate
$sp = New-AzureRmADServicePrincipal -ApplicationId $adapp.ApplicationId
Set-AzureRmKeyVaultAccessPolicy -VaultName $VaultName -ServicePrincipalName $sp.ServicePrincipalNames[1] -PermissionsToKeys all –PermissionsToSecrets all -ResourceGroupName $ResourceGroupName
The Azure AD application was created successfully, however for Azure AD application with Certificate Authentication, the customKeyIdentifier and value of in the keyCredentials is null after creation, this is the portion of manifest of my application I downloaded from Azure portal:
"keyCredentials": [{
"customKeyIdentifier": null,
"endDate": "2018-01-25T11:55:35.7680698Z",
"keyId": "ca1e536c-2220-478b-af73-1198d125bb5f",
"startDate": "2017-01-25T11:55:35.7680698Z",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"value": null
} ]
The certificate is a self signed certificate created using makecert command generated locally.
I am using Powershell Version of 2.0.1
C# Code to retrieve the token with Application Id & Thumbprint
public static async Task GetAccessToken(string authority,
string resource, string scope) {
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var result = await context.AcquireTokenAsync(resource, AssertionCert);
return result.AccessToken; }
This Code errors out at var result with "Keyset does not exists"
Is there any way to resolve this issue?
Thank you :)
Did you look at the answer here?
Create a Application in Azure AD with Azure PowerShell Certificate authentication
In the comments he mentions that CustomKeyIdentifier being null does not matter for authentication.
Did you try authenticating regardless of the null value?\
EDIT:
If you want to generate a thumbprint for a public certificate you own, you can do so using the following powershell cmdlets:
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cer.Import(“mycer.cer”)
$bin = $cer.GetCertHash()
$base64Thumbprint = [System.Convert]::ToBase64String($bin)
I hope this helps.

Authenticated with "Login-AzureRmAccount -ServicePrincipal" but no subscription is set?

I've successfully created a self-signed certificate with application & service principle using the New-AzureRmADApplication and New-AzureRmADServicePrincipal cmdlets.
I can execute the login using this command after retrieving the certificate:
Login-AzureRmAccount -ServicePrincipal -CertificateThumbprint $cert.Thumbprint -TenantId $tenantID -ApplicationId $applicationID
However, the SubscriptionId/SubscriptionName attributes of this authentication display as blank:
Environment : AzureCloud
Account : ********************
TenantId : ********************
SubscriptionId :
SubscriptionName :
CurrentStorageAccount :
Subsquently, this command works!
$secret = Get-AzureKeyVaultSecret -VaultName $vaultName -Name $keyName
What is confusing to me is that I am able to retrieve a AzureKeyVaultSecret in my DEV subscription, but I do not understand how this cmdlet knows which of my subscriptions to use??? I intend to create the same vault in my PROD subscription, but first need to understand how this ServicePrincipal/Certificate authentication knows which subscription to pull from and/or how to manipulate it?
I can say that when I created the App/ServicePrincipal, I logged in specifying the "DEV" subscription like so:
$subscriptionName = "DEV"
$user = "user#company.com"
$password = "*****"
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($user, $securePassword)
Login-AzureRmAccount -Credential $credential -SubscriptionName $subscriptionName

Resources