PureBasic
PureBasic
POP3 Auto-Refresh Office365 Access Token
See more Office365 Examples
Demonstrates how to automatically recover from an expired OAuth2 access token when OAuth2 authentication fails in the POP3 protocol. If the server responds with "-ERR Authentication failure: unknown user name or bad password.", then we refresh the access token and retry.Chilkat PureBasic Downloads
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkOAuth2.pb"
IncludeFile "CkMailMan.pb"
Procedure ChilkatExample()
success.i = 0
; This example requires the Chilkat API to have been previously unlocked.
; See Global Unlock Sample for sample code.
mailman.i = CkMailMan::ckCreate()
If mailman.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkMailMan::setCkMailHost(mailman, "outlook.office365.com")
CkMailMan::setCkMailPort(mailman, 995)
CkMailMan::setCkPopSsl(mailman, 1)
; Use your O365 email address here.
CkMailMan::setCkPopUsername(mailman, "OFFICE365_EMAIL_ADDRESS")
; When using OAuth2 authentication, leave the password empty.
CkMailMan::setCkPopPassword(mailman, "")
; Load our previously obtained OAuth2 access token.
jsonToken.i = CkJsonObject::ckCreate()
If jsonToken.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkJsonObject::ckLoadFile(jsonToken,"qa_data/tokens/office365.json")
If success = 0
Debug CkJsonObject::ckLastErrorText(jsonToken)
CkMailMan::ckDispose(mailman)
CkJsonObject::ckDispose(jsonToken)
ProcedureReturn
EndIf
CkMailMan::setCkOAuth2AccessToken(mailman, CkJsonObject::ckStringOf(jsonToken,"access_token"))
; Make the TLS connection to the outlook.office365.com POP3 server.
success = CkMailMan::ckPop3Connect(mailman)
If success <> 1
Debug CkMailMan::ckLastErrorText(mailman)
CkMailMan::ckDispose(mailman)
CkJsonObject::ckDispose(jsonToken)
ProcedureReturn
EndIf
; Authenticate using XOAUTH2
success = CkMailMan::ckPop3Authenticate(mailman)
If success <> 1
; If we're still connected to the mail server, then it means the server sent a non-success response,
; Such as: -ERR Authentication failure: unknown user name or bad password.
If CkMailMan::ckIsPop3Connected(mailman) = 1
; Refresh the OAuth2 access token, and if successful, save the new (refreshed) access token and try authenticating again.
oauth2.i = CkOAuth2::ckCreate()
If oauth2.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; Use your actual Directory (tenant) ID instead of "112d7ed6-71bf-4eba-a866-738364321bfc"
CkOAuth2::setCkTokenEndpoint(oauth2, "https://login.microsoftonline.com/112d7ed6-71bf-4eba-a866-738364321bfc/oauth2/v2.0/token")
; Replace these with your Azure App Registration's actual values.
CkOAuth2::setCkClientId(oauth2, "CLIENT_ID")
CkOAuth2::setCkClientSecret(oauth2, "CLIENT_SECRET")
; Get the "refresh_token"
CkOAuth2::setCkRefreshToken(oauth2, CkJsonObject::ckStringOf(jsonToken,"refresh_token"))
; Send the HTTP POST to refresh the access token..
success = CkOAuth2::ckRefreshAccessToken(oauth2)
If success <> 1
Debug CkOAuth2::ckLastErrorText(oauth2)
CkMailMan::ckDispose(mailman)
CkJsonObject::ckDispose(jsonToken)
CkOAuth2::ckDispose(oauth2)
ProcedureReturn
EndIf
Debug "New access token: " + CkOAuth2::ckAccessToken(oauth2)
Debug "New refresh token: " + CkOAuth2::ckRefreshToken(oauth2)
; Update the JSON with the new tokens.
CkJsonObject::ckUpdateString(jsonToken,"access_token",CkOAuth2::ckAccessToken(oauth2))
CkJsonObject::ckUpdateString(jsonToken,"refresh_token",CkOAuth2::ckRefreshToken(oauth2))
; Save the new JSON access token response to a file.
sbJson.i = CkStringBuilder::ckCreate()
If sbJson.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkJsonObject::setCkEmitCompact(jsonToken, 0)
CkJsonObject::ckEmitSb(jsonToken,sbJson)
CkStringBuilder::ckWriteFile(sbJson,"qa_data/tokens/office365.json","utf-8",0)
Debug "New Access Token = " + CkOAuth2::ckAccessToken(oauth2)
; Update the mailman with the new access token.
CkMailMan::setCkOAuth2AccessToken(mailman, CkOAuth2::ckAccessToken(oauth2))
; Retry the authentication.
success = CkMailMan::ckPop3Authenticate(mailman)
If success = 0
Debug CkMailMan::ckLastErrorText(mailman)
CkMailMan::ckDispose(mailman)
CkJsonObject::ckDispose(jsonToken)
CkOAuth2::ckDispose(oauth2)
CkStringBuilder::ckDispose(sbJson)
ProcedureReturn
EndIf
Else
Debug CkMailMan::ckLastErrorText(mailman)
CkMailMan::ckDispose(mailman)
CkJsonObject::ckDispose(jsonToken)
CkOAuth2::ckDispose(oauth2)
CkStringBuilder::ckDispose(sbJson)
ProcedureReturn
EndIf
EndIf
; Find out how many emails are on the server..
numEmails.i = CkMailMan::ckCheckMail(mailman)
If numEmails < 0
Debug CkMailMan::ckLastErrorText(mailman)
CkMailMan::ckDispose(mailman)
CkJsonObject::ckDispose(jsonToken)
CkOAuth2::ckDispose(oauth2)
CkStringBuilder::ckDispose(sbJson)
ProcedureReturn
EndIf
; Examine the POP3 session log:
Debug CkMailMan::ckPop3SessionLog(mailman)
; The POP3 session log will look something like this:
; **** Connected to outlook.office365.com:995
; < +OK The Microsoft Exchange POP3 service is ready. [QwBIADIAUABSADEANgBDAEEAMAAwADEAMgAuAG4AYQBtAHAAcgBkADEANgAuAHAAcgBvAGQALgBvAHUAdABsAG8AbwBrAC4AYwBvAG0A]
; > AUTH XOAUTH2
; < +
; > <base64 string in XOAUTH2 format>
; < -ERR Authentication failure: unknown user name or bad password.
; > AUTH XOAUTH2
; < +
; > <base64 string in XOAUTH2 format>
; < +OK User successfully authenticated.
; > STAT
; < +OK 248 46637086
; End the POP3 session and close the connection to the GMail server.
success = CkMailMan::ckPop3EndSession(mailman)
If success <> 1
Debug CkMailMan::ckLastErrorText(mailman)
CkMailMan::ckDispose(mailman)
CkJsonObject::ckDispose(jsonToken)
CkOAuth2::ckDispose(oauth2)
CkStringBuilder::ckDispose(sbJson)
ProcedureReturn
EndIf
Debug "Finished."
CkMailMan::ckDispose(mailman)
CkJsonObject::ckDispose(jsonToken)
CkOAuth2::ckDispose(oauth2)
CkStringBuilder::ckDispose(sbJson)
ProcedureReturn
EndProcedure