I referred this link and it explain how to connect using client and secret.
But, I cannot use this in production environment as the PowerShell script is going to store in the server. Anyone can open it and see the creds.
Could you please kindly explain me how to use a certificate instead of client and secret to connect Azure AD and extract users last log in information without any user interaction or MFA prompts with pop-up windows.
Thanks
Initially, I created one self-signed certificate from PowerShell using below script:
$certname = "graphcert12"
$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256
Export-Certificate -Cert $cert -FilePath "C:/test/$certname.cer" ## Specify your preferred location
Response:
Now, I uploaded this certificate to my app registration in Entra ID like this:
To connect to Microsoft Graph as a service principal with certificate, you can make use of below PowerShell script that does not involve any user interaction:
$CertPath = "C:/test/graphcert12.cer"
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($CertPath)
Connect-MgGraph -ClientId "appId" -TenantId "tenantId" -CertificateThumbprint "certthumbprint"
Response:
Now, I ran below PowerShell script and got last log in date time of users successfully in response without any pop-up window:
$users = Get-MgUser -Property 'SignInActivity'
foreach ($user in $users) {
$displayName = $user.DisplayName
$lastSignInDateTime = $user.SignInActivity.LastSignInDateTime
if ($lastSignInDateTime -eq $null) {
Write-Host "$displayName has never signed in."
} else {
Write-Host "$displayName last signed in on $lastSignInDateTime"
}
}
Response:
Reference: Using Microsoft Graph PowerShell authentication commands | Microsoft