Sample code for 30+ languages & platforms
PowerBuilder Requires Chilkat v11.0.0+

Microsoft 365: Obtain Mail OAuth2 Tokens with Desktop PKCE

See more Office365 Examples

Obtain delegated SMTP, IMAP, and POP access with authorization code flow and S256 PKCE. Register a public desktop application in Microsoft Entra with a Mobile and desktop applications loopback redirect URI of http://localhost:3017/. Do not register this callback as a Web or SPA application. No client secret belongs in a distributed desktop application. Run the sample where the user can launch a browser and return to the local listener; it is not a web-server callback example.

The common authority supports work/school and personal accounts only if the app registration supports those account types. For a single-tenant work/school app, replace common in both endpoints with the mailbox tenant ID. The account needs an Exchange Online mailbox; administrator consent or Conditional Access can restrict authorization.

The example requests all three delegated protocol permissions for demonstration. Remove unused scopes in your application. Microsoft Graph scopes and ID tokens are not substitutes for mail-protocol access tokens. The user may need consent again after revocation or policy changes; refresh is not guaranteed indefinitely.

Create qa_data/tokens in a private, access-controlled working directory before running. The saved JSON contains credentials, not just settings. Use separate caches per account, app, and authority; prevent concurrent writers, use an OS credential store in production, and never publish token responses. The sample validates the response before writing, but a production cache also needs atomic replacement and recovery from write failures.

Microsoft reference documentation

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Oauth
string ls_AuthUrl
long li_Waited
oleobject loo_Token
oleobject loo_Obtained

li_Success = 0

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

loo_Oauth = create oleobject
li_rc = loo_Oauth.ConnectToNewObject("Chilkat.OAuth2")
if li_rc < 0 then
    destroy loo_Oauth
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Oauth.TokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
loo_Oauth.ClientId = "CLIENT_ID"
//  A public desktop client does not have a client secret.

loo_Oauth.AuthorizationEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
loo_Oauth.LocalHost = "localhost"
loo_Oauth.ListenPort = 3017
loo_Oauth.CodeChallenge = 1
loo_Oauth.CodeChallengeMethod = "S256"
//  Request only the protocols your application needs; this sample covers all three.
loo_Oauth.Scope = "offline_access https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All"
li_Success = loo_Oauth.AddAuthQueryParam("prompt","select_account")
if li_Success <> 1 then
    Write-Debug "Could not configure account selection."
    destroy loo_Oauth
    return
end if

ls_AuthUrl = loo_Oauth.StartAuth()
if loo_Oauth.LastMethodSuccess <> 1 then
    Write-Debug "Could not start the loopback listener."
    destroy loo_Oauth
    return
end if

li_Success = loo_Oauth.LaunchBrowser(ls_AuthUrl)
if li_Success <> 1 then
    loo_Oauth.Cancel()
    Write-Debug "Could not open the system browser."
    destroy loo_Oauth
    return
end if

li_Waited = 0
do while ((loo_Oauth.AuthFlowState < 3) AND (li_Waited < 180000))
    loo_Oauth.SleepMs(200)
    li_Waited = li_Waited + 200
loop
if loo_Oauth.AuthFlowState < 3 then
    loo_Oauth.Cancel()
    Write-Debug "Authorization timed out."
    destroy loo_Oauth
    return
end if

if loo_Oauth.AuthFlowState <> 3 then
    Write-Debug "Authorization did not complete. Flow state: " + string(loo_Oauth.AuthFlowState)
    destroy loo_Oauth
    return
end if

loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")

li_Success = loo_Token.Load(loo_Oauth.AccessTokenResponse)
if li_Success <> 1 then
    Write-Debug "Could not parse the token response."
    destroy loo_Oauth
    destroy loo_Token
    return
end if

if (loo_Token.JsonTypeOf("refresh_token") <> 1) OR (loo_Token.StringOfEquals("refresh_token","",1) = 1) then
    Write-Debug "No offline refresh token was issued. The existing cache was preserved."
    destroy loo_Oauth
    destroy loo_Token
    return
end if

if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
    Write-Debug "The response did not contain an access token. The existing cache was preserved."
    destroy loo_Oauth
    destroy loo_Token
    return
end if

loo_Obtained = create oleobject
li_rc = loo_Obtained.ConnectToNewObject("Chilkat.CkDateTime")

loo_Obtained.SetFromCurrentSystemTime()
loo_Token.UpdateString("obtained_at",loo_Obtained.GetAsTimestamp(0))
//  The token response includes expires_in (seconds). Refresh before the access token expires.
//  The file contains credentials: use a private, access-controlled directory.
li_Success = loo_Token.WriteFile("qa_data/tokens/office365.json")
if li_Success <> 1 then
    Write-Debug "Could not save the token file."
    destroy loo_Oauth
    destroy loo_Token
    destroy loo_Obtained
    return
end if

Write-Debug "Credentials saved in the private working directory."


destroy loo_Oauth
destroy loo_Token
destroy loo_Obtained