Reputation: 21
For authentication, we are using below scopes as mentioned in the doc https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth
offline_access https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send We are able to get access_token and refresh_token successfully
We want to get userPrincipalName but https://outlook.office.com/api/v2.0/me/ api doesn't return userPrincipalName. We tried using graph api https://graph.microsoft.com/v1.0/me to get userPrincipalName however we are getting error , looks like for hitting graph api only graph scopes would work.
We tried with graph scopes urls,
https://graph.microsoft.com/IMAP.AccessAsUser.All , https://graph.microsoft.com/SMTP.Send and able to hit graph api , however smtp and imap authentication is not working with these scopes.
since Microsoft is deprecating outlook rest apis and asking to move to graph api then why graph scopes urls are not supported for SMTP and IMAP ?
Is there any way we can get the userPricipalName ?
Upvotes: 2
Views: 2056
Reputation: 497
You are absolutely correct. This has wasted the whole night for me.
When requesting tokens for Microsoft oAuth2 Outlook IMAP/SMTP/POP access you must provide scopes, such as:
offline_access https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send
You cannot mix https://outlook.office.com
scopes with any other type of scope or AUTH will fail when trying to oAuth2 to IMAP or SMTP - even though the token looks perfectly valid.
The answer to extracting the email address is:
' Get the Header, Payload and Signature of the token
' Header & Payload are Base64 encoded strings - add missing padding
Dim jwtH As String = Encoding.UTF8.GetString(Convert.FromBase64String(AddMissingBase64Padding(Token.Split(".")(0))))
Dim jwtP As String = Encoding.UTF8.GetString(Convert.FromBase64String(AddMissingBase64Padding(Token.Split(".")(1))))
Dim jwtS As String = Result.Token.Split(".")(2)
' Now extract the Email Address
Dim Username As String = JsonConvert.DeserializeObject(jwtP)("upn").value
Private Function AddMissingBase64Padding(Base64String As String) As String
' Calculate the number of padding characters needed
Return Base64String & Left("===", Base64String.Length Mod 4)
End Function
Upvotes: 0
Reputation: 9549
You need to IMAP.AccessAsUser.All
and SMTP.Send
are added to MS graph api, and then grant admin consent.
Then use the auth code flow to get the access token.
Call the /me
endpoint.
Upvotes: 1