Azure AD login without credentials (unattended)

Unattended login to Azure isn’t that easy, especially if you want to add a PowerShell script to the task scheduler. You will see that Plain Text password do not work, and it doesn’t work with the “CredentialManager” module either. You will get an error message like:

 

1
Connect-AzureAD : One or more errors occurred.: Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.

 

The solution is to add a registered app in Azure AD and connect to that app. Here is the PowerShell I used.

Note that running commands below on Server 2012 R2 or before will fail, it doesn’t support options that comes with Windows Server 2016. Stripping those options will fail the Azure AD login. Execute these commands on a Windows 10 or Server 2016 machine and copy the exported certificate to a Windows Server 2012 R2 machine. Also import the certificate in the Personal store of the “CurrentUser” on that specific machine.

First, login with administrator credentials:

1
Connect-AzureAD

Now Execute this PowerShell:

1
2
3
4
5
6
7
8
9
10
11
12
$pwd = "yourpass"
$thumb = (New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My -subject "unattendedlogin-azuread" -KeyExportPolicy Exportable -NotAfter (Get-Date).AddYears(10) -Type CodeSigningCert -KeySpec Signature).Thumbprint
$pwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
$tmppath = Test-Path C:\tmp
if ($tmppath -eq $false) {mkdir C:\tmp}
Export-PfxCertificate -cert "cert:\CurrentUser\my\$thumb" -FilePath C:\tmp\unattendedlogin-azuread.pfx -Password $pwd
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("C:\tmp\unattendedlogin-azuread.pfx", $pwd)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
$application = New-AzureADApplication -DisplayName "unattendedlogin-azuread" -IdentifierUris "https://unattendedlogin"
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "unattendedlogin" -Type AsymmetricX509Cert -Usage Verify -Value $keyValue
$sp=New-AzureADServicePrincipal -AppId $application.AppId
Add-AzureADDirectoryRoleMember -ObjectId (Get-AzureADDirectoryRole | where-object {$_.DisplayName -eq "Directory Readers"}).Objectid -RefObjectId $sp.ObjectId

Now save the thumbprint, tenantID and appID.

1
2
3
$thumb = "thumbprint"
$tenantid = "tenantid"
$appid = "appid"

You can get these values like this (use the same PowerShell session), executing these commands:

1
2
3
4
5
$thumb
$appid = get-azureadapplication | where DisplayName -match "unattendedlogin"
$appid.AppId
$tenantid = Get-AzureADTenantDetail
$tenantid.ObjectId

Next time login like this:

1
Connect-AzureAD -TenantId $tenantid -ApplicationId $appid -CertificateThumbprint $thumb