skip to Main Content

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

2

Answers


  1. A common approach to this problem would be to fetch the secret from a key management solution such as Azure KeyVault. You can store the client secret in Azure KeyVault and fetch it from server using Managed Identity. A step-by-step guide can be found here.

    Login or Signup to reply.
  2. Initially, I created one self-signed certificate from PowerShell using below script:

    $certname = "graphcert12"    
    $cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:CurrentUserMy" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256
    Export-Certificate -Cert $cert -FilePath "C:/test/$certname.cer"   ## Specify your preferred location
    

    Response:

    enter image description here

    Now, I uploaded this certificate to my app registration in Entra ID like this:

    enter image description here

    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:

    enter image description here

    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:

    enter image description here

    Reference:
    Using Microsoft Graph PowerShell authentication commands | Microsoft

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search