DarkRose
DarkRose

Reputation: 125

Outlook Office 365 - how to get access token(through API) using username and App password when MFA is enabled?

As you all aware that MS Office 365 changed from Basic Auth to Modern Authentication recently, so it blocks all access from protocols such as IMAP/POP/SMTP. In that case we have to use Access token (OAUTH 2.0) generated from MS API by passing the client/secret, username , password & scope.

Currently, I'm able to get the access token for users who do not use MFA(able to access user mailboxes with IMAP protocol), but for the users who uses MFA, we have the app password for them. For mfa users, I'm passing their app password(in the password field) to get the access token, but I'm getting the following error

"error": "invalid_grant",
"error_description": "AADSTS50126: Error validating credentials due to invalid username or password.",
"error_codes": [
    50126
],

grant type I'm using for this request is "password". Any suggestion how to resolve this issue? Do I delegate any API permissions in azure ad application side? I have currently enabled IMAP accessforALL for my usage.

Please help.. Thanks in advance

Upvotes: 3

Views: 3437

Answers (2)

Neo
Neo

Reputation: 2395

While this is an old question, you can use the microsoft graph system.

Here is an example in php

    $Secret = '**YourSecret**';
    $AppID = '**YourAppID**';
    $TenantID = '**YourTenantID**';
    $Username = '**YourUsername**';
    $Password = '**YourPassword**';


    $guzzle = new \GuzzleHttp\Client(['headers' => ['User-Agent' => 'Token-Request']]);
    $url = 'https://login.microsoftonline.com/'.$TenantID.'/oauth2/v2.0/token';
    $token = json_decode($guzzle->post($url, [
        'form_params' => [
            'grant_type'    => 'password',
            'client_id'     => $AppID,
            'client_secret' => $Secret,
            'scope'         => 'https://outlook.office365.com/IMAP.AccessAsUser.All',
            'username'      => $Username,
            'password'      => $Password,
        ],
    ])->getBody()->getContents());

    $AccessToken = $token->access_token;
    

Upvotes: 0

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66235

You can't - the access and refresh tokens are retrieved through a browser-based login (which requires user interaction).

If you need to avoid that, you will need to register your app in Azure and application secret to authenticate without prompts.

Upvotes: 0

Related Questions