In the 4D v18 R6, 4D introduced OAuth 2.0 authentication to access emails through IMAP, SMTP, or POP3 transporters. Starting with 4D v19 R3, 4D continues to implement OAuth 2.0 protocol and provides a way to request easily by programming a token from the Microsoft identity platform to connect to the API for Microsoft 365.
HDI OAUTH2 Microsoft
Prerequisites
Before getting a token from the Microsoft identity platform, the first step is to register your application in the Azure portal. It establishes a trust relationship between your app and the Microsoft identity platform. The trust is unidirectional: your app trusts the Microsoft identity platform and not the other way around.
This tutorial by Microsoft is a great resource to understand how to register your application in the Azure portal.
Registration integrates your application with the Microsoft identity platform and establishes the information that it uses to get tokens, including:
- a Client ID: A unique identifier assigned by the Microsoft identity platform.
- a Redirect URI/URL: One or more endpoints where your app will receive responses from the Microsoft identity platform.
- a Client Secret: A password or a public/private key pair that your app uses to authenticate with the Microsoft identity platform. (required only when getting access for a service)
getTING AN access token
Access tokens issued by the Microsoft identity platform contain information that Microsoft Graph, the API for Microsoft 365, uses to validate the caller and ensure that they have the proper permissions to perform the operation they’re requesting.
To get your token, you just need to use the New OAuth2 provider command with all the information given during the registration:
$param:=New object()
$param.name:="Microsoft"
$param.permission:="signedIn"
$param.clientId:="7008ebf5-xxxx-xxxx"
$param.redirectURI:="http://127.0.0.1:50993/"
$param.scope:="https://outlook.office.com/IMAP.AccessAsUser.All"
// Create new OAuth2 object
$oAuth2:=New OAuth2 provider($param)
// Ask for a token
$token:=$oAuth2.getToken()
If ($token#Null)
// Using of the token to access emails over IMAP
$IMAPParameters:=New object
$IMAPParameters.authenticationMode:=IMAP authentication OAUTH2
// Token received from the server
$IMAPParameters.accessTokenOAuth2:=$token.token.access_token
// e-mail address of the user for whom the token was created
$IMAPParameters.user:=$user
$IMAPParameters.host:="Outlook.office365.com"
$IMAPTransporter:=IMAP New transporter($IMAPParameters)
$status:=$IMAPTransporter.checkConnection()
If (Not($status.success))
ALERT("Access denied to IMAP server")
End if
End if
This command is part of the new 4D NetKit component, whose sources and documentation can be found on github.