PC SOFT

FORUMS PROFESSIONNELS
WINDEVWEBDEV et WINDEV Mobile

Accueil → WINDEV 2024 → Settings for Outlook Oauth2
Settings for Outlook Oauth2
Débuté par simon, 26 sep. 2024 14:32 - 7 réponses
Posté le 26 septembre 2024 - 14:32
Hi All

Does anyone have working setting for recovinging the auth token from Microsoft so that I can run SMTP to outlook.com accounts. Since Microsoft have applied Oauth2 to outlook.com, I cannot now use emails. Fortunatley the app is still in development, but this is a must.

The code I am currently using is:

OAuthOutlookCnt is OAuth2Parameters
OAuthOutlookCnt.ClientID = "MyClientID"
OAuthOutlookCnt.ClientSecret = "MyClientSecret"
OAuthOutlookCnt.AuthURL="https://login.microsoftonline.com/MytenantID/oauth2/v2.0/authorize"
OAuthOutlookCnt.TokenURL="https://login.microsoftonline.com/MytenantID/oauth2/v2.0/token"
OAuthOutlookCnt.Scope="https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send"
OAuthOutlookCnt.RedirectionURL = "http://localhost:1998" 
OAuthOutlookCnt.ResponseType = oauth2ResponseTypeCode

MyToken = AuthIdentify(OAuthOutlookCnt)
IF MyToken.Valid = False THEN
STC_Failed.Visible = True
ELSE
STC_Success.Visible = True
END

(MyClientID, MyClientSecret and MytenantID are substitued for the actual codes)

I have tried everything but MyToken.Valid always returns False.
I have it working fine with Gmail, but cannot get this to return a token.
Any suggestions would be greatly appreciated before I finish pulling the last of my hair out!

Thanks
Simon
Posté le 27 septembre 2024 - 20:00
Hi Simon,

It sounds like you're close but just need a few adjustments to get the OAuth2 flow working for Microsoft's new authentication requirements for Outlook.com. Here are some things to check and troubleshoot based on your current setup:

1) Check Your Redirect URI:
Make sure that http://localhost:1998 is registered as a valid Redirect URI in your Azure app registration. Microsoft is strict about matching the redirect URI exactly, so if there's any mismatch, it will cause authentication failures.
Also, consider using https://localhost:1998 instead of HTTP, as some OAuth2 flows prefer HTTPS for security reasons.
2) Token Scopes:
Your scopes look good, but ensure that the permissions are correctly set in the Azure App Registration for the API permissions. You should have:
IMAP.AccessAsUser.All
SMTP.Send
Go to Azure Portal > App Registrations > API permissions and verify these scopes are granted and admin consent is applied (if necessary).
3) Grant Admin Consent:
If your app requires admin consent for the scopes you've requested, make sure you’ve granted it in Azure AD. Without it, the token request will fail silently.
You can do this from API permissions in the Azure portal by clicking Grant admin consent.
4) Ensure Correct Token Flow:
You're using Authorization Code flow (oauth2ResponseTypeCode), which is correct for this scenario, but ensure your app is also set up to handle the authorization code and token exchange properly.
After you get the authorization code from the auth URL, you'll need to exchange it for an access token at the Token URL.
5) Inspect Error Response:
Try logging the actual error response you’re receiving when MyToken.Valid = False. This will give you more insight into whether it’s an issue with authentication, permissions, or token exchange.
6) Verify Tenant ID:
Double-check your tenant ID. If you're using a personal Microsoft account (like for Outlook.com), the tenant ID might be common or consumers instead of your organizational tenant ID.
By ensuring that all the necessary configurations are in place (especially around permissions and redirect URI), you should be able to get the token successfully.

If you’re still stuck, Microsoft’s MSAL library is a good tool to use for managing OAuth2 flows. It’s worth exploring if you want to simplify the token retrieval process. Best of luck with your <a href="https://medhacloud.com/microsoft-365-migration-services/">Microsoft 365 migration</a>


Hope this helps, and good luck!
Posté le 04 octobre 2024 - 15:24
Hi Justa

Sorry for not getting back to you earlier and thanks for your detailed response. I have now manged to get the Auth code, but still cannot start a smtp session. The code returned is in Json rather that an AuthToken format so that could be the problem.
Sorry to be a pain, but do you have working code that can be used to get the auth token and then start an smtp session with outlook.com as I am obviously missing something? I seem to be almost there but still refusing connection.
Just to be clear this is using Outlook.com and not office365.

Thanks for your help
Simon
Posté le 14 janvier 2025 - 19:43
Simon,

Are you still working on this?
I can post an example for you.

Jim
Posté le 24 janvier 2025 - 18:19
Jim wrote:
Simon,

Are you still working on this?
I can post an example for you.

Jim


I would love the code, having the same issue.
Posté le 31 janvier 2025 - 21:05
I'm leaving now, but will post the code on Monday.
Our last hurdle is publishing the app on the backend in Azure.
This is becoming a nightmare.

Jim
Posté le 04 février 2025 - 15:24
OAuthMSOFT is OAuth2Parameters
SessionSMTP is emailSMTPSession
gAccessToken is AuthToken
gRefreshToken is AuthToken
gMyEmail is Email
gFResult is string


First Button

//Working now as of Friday 12/20/2024 Scope was wrong. Client secret not needed native app, only web app.
//Needed a second account to authenticate.

// Paramètres de connexion OAuth for the ar@temp... account
OAuthMSOFT.ClientID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
OAuthMSOFT.ClientSecret = ""//Secret is not necessary!!
OAuthMSOFT.AuthURL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
OAuthMSOFT.TokenURL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
OAuthMSOFT.Scope = "https://outlook.office.com/user.read offline_access"
OAuthMSOFT.RedirectionURL = "http://localhost:9000"
OAuthMSOFT.ResponseType = "code"

// Performs the OAuth connection
gAccessToken = AuthIdentify(OAuthMSOFT)


IF ErrorOccurred THEN
Error(ErrorInfo())
RETURN
END

// If the identification was successful, fill in the boxes refresh token is not being returned
IF gAccessToken.Valid THEN

EDT_AccessToken = gAccessToken.Value
EDT_AuthExpiration = DateTimeToString(gAccessToken.ExpirationDate,maskDateInternet)
EDT_RefreshToken = gAccessToken.Refresh



ELSE
Info("Error getting authentication")

END

Second Button

//If the identification was successful, you can connect to the email box
//
AuthString is string
AuthString = gAccessToken.Value
rslt is boolean

SessionSMTP.ServerAddress = "smtp.office365.com"
SessionSMTP.Name = "someone@outlook.com"
SessionSMTP.Port = 587
SessionSMTP.Option = emailProtocolSMTPS
SessionSMTP.AuthToken = gAccessToken


IF gFResult = "" THEN
ToastDisplay("Nothing to attach",toastShort,vaBottom,haCenter)
ELSE
EmailLoadAttachment(gMyEmail,gFResult)
END


IF EmailStartSession(SessionSMTP) = True THEN

Send_Email()


ELSE

rslt = GetNewAccessToken()
IF EmailStartSession(SessionSMTP) = True THEN
Send_Email()
ELSE
Error("Could not start SMTP email session with new token. ", ErrorInfo())
RETURN
END



END

Local Procedure 1

//Secret in not necessary in Azure
// GetNewAccessToken() just goes and gets the new access token
PROCEDURE GetNewAccessToken()

OAuthMSOFT.ClientID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
OAuthMSOFT.ClientSecret = ""//Secret is not necessary!!
OAuthMSOFT.AuthURL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
OAuthMSOFT.TokenURL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
OAuthMSOFT.Scope = "https://outlook.office.com/user.read offline_access"
OAuthMSOFT.RedirectionURL = "http://localhost:9000"

gAccessToken = AuthRefreshToken(gAccessToken)


IF ErrorOccurred THEN
Error(ErrorInfo())
RETURN False
ELSE

Info("New token obtained")
IF gAccessToken.Valid THEN
WIN_Main.EDT_AccessToken = gAccessToken.Value
EDT_AuthExpiration = DateTimeToString(gAccessToken.ExpirationDate,maskDateInternet)
RETURN True
ELSE
RETURN False
END

END


Local Procedure 2

// Summary: <specify the procedure action>
//Sets up the email and sends it
PROCEDURE Send_Email()

time is DateTime
sTime is string
sTime = DateTimeToString(time,maskDateSystem) + " This is hard"
// Send the message
Add(gMyEmail.Recipient,"xxxxx@website.com")
gMyEmail.Subject = "oAuth2 testing"
gMyEmail.Message = sTime
gMyEmail.Sender = "otheruser@outlook.com"


EmailSendMessage(SessionSMTP, gMyEmail)
Info("Email sent")
EmailCloseSession(SessionSMTP)
Posté le 06 février 2025 - 20:05
Thanks for your detailed response. What have done is basically now using outlook which is installed on every system. I have the reading all working, now having problems sending. It says ian email is sent successfully, but nothing gets sent.

My issue is that the app is designed for the elderly and first time users who find applications difficult to use. There appear to be some problems accessing Outlook but truing to work around them.

Thanks
Simon