multi-factor authentication issue in accessing mails using microsoft graph

Anandhan Sathyanarayanan 141 Reputation points
2023-08-18T18:24:44.8966667+00:00

Hi, I'm getting the below error while accessing emails using delegated permission. This script will run in unattended mode, hence it's not possible to bring user prompt-based authentication.

"error":"interaction_required","error_description":"AADSTS50076: Due to a configuration      
     | change made by your administrator, or because you moved to a new location, you must use       
     | multi-factor authentication to access '00000003-0000-0000-c000-000000000000'
# Create a credential object
$SecPasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$CredObject = New-Object System.Management.Automation.PSCredential ($mailuserid, $SecPasswd)

    # Define the token endpoint and parameters
    $tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/token"
    $tokenParams = @{
        "resource"      = "https://graph.microsoft.com"
        "client_id"     = $clientId
        "client_secret" = $clientSecret    
        "grant_type"    = "password"
        "username"      = $CredObject.username
        "password"      = $CredObject.GetNetworkCredential().Password
    }

    # Get the access token using the client credentials flow
    $tokenResponse = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $tokenParams -ContentType "application/x-www-form-urlencoded"

    # Extract the access token from the response
    $accessToken = $tokenResponse.access_token 

    # Set up the required headers for the API request
    $headers = @{
        "Authorization" = "Bearer $accessToken"
        "Content-Type" = "application/json"
    } 

    $uri = "https://graph.microsoft.com/v1.0/users/$mailuserid/messages"
    $response = $null
    $response = Invoke-RestMethod -Uri $uri -Headers $headers -Method Get
}else{
    Write-Host "Please update password.."
}
Microsoft Security Microsoft Graph
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Andy David - MVP 157.4K Reputation points MVP Volunteer Moderator
    2023-08-18T18:41:38.52+00:00

    You dont want to use a grant_type flow that requires a password, use the client cred flow instead:

    https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow

    If you use an account and password, then it would need to be a service account excluded from MFA requirements.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.