Outlook.com: 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.
Choose an app registration supporting personal Microsoft accounts. The consumers authority permits personal accounts only, including Outlook.com, Hotmail, and Live.
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 Android™ Downloads
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;
import android.app.Activity;
import com.chilkatsoft.*;
import android.widget.TextView;
import android.os.Bundle;
public class SimpleActivity extends Activity {
private static final String TAG = "Chilkat";
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkOAuth2 oauth = new CkOAuth2();
oauth.put_TokenEndpoint("https://login.microsoftonline.com/consumers/oauth2/v2.0/token");
oauth.put_ClientId("CLIENT_ID");
// A public desktop client does not have a client secret.
oauth.put_AuthorizationEndpoint("https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize");
oauth.put_LocalHost("localhost");
oauth.put_ListenPort(3017);
oauth.put_CodeChallenge(true);
oauth.put_CodeChallengeMethod("S256");
// Request only the protocols your application needs; this sample covers all three.
oauth.put_Scope("offline_access https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All");
success = oauth.AddAuthQueryParam("prompt","select_account");
if (success != true) {
Log.i(TAG, "Could not configure account selection.");
return;
}
String authUrl = oauth.startAuth();
if (oauth.get_LastMethodSuccess() != true) {
Log.i(TAG, "Could not start the loopback listener.");
return;
}
success = oauth.LaunchBrowser(authUrl);
if (success != true) {
oauth.Cancel();
Log.i(TAG, "Could not open the system browser.");
return;
}
int waited = 0;
while (((oauth.get_AuthFlowState() < 3) and (waited < 180000))) {
oauth.SleepMs(200);
waited = waited + 200;
}
if (oauth.get_AuthFlowState() < 3) {
oauth.Cancel();
Log.i(TAG, "Authorization timed out.");
return;
}
if (oauth.get_AuthFlowState() != 3) {
Log.i(TAG, "Authorization did not complete. Flow state: " + String.valueOf(oauth.get_AuthFlowState()));
return;
}
CkJsonObject token = new CkJsonObject();
success = token.Load(oauth.accessTokenResponse());
if (success != true) {
Log.i(TAG, "Could not parse the token response.");
return;
}
if ((token.JsonTypeOf("refresh_token") != 1) or (token.StringOfEquals("refresh_token","",true) == true)) {
Log.i(TAG, "No offline refresh token was issued. The existing cache was preserved.");
return;
}
if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true)) {
Log.i(TAG, "The response did not contain an access token. The existing cache was preserved.");
return;
}
CkDateTime obtained = new CkDateTime();
obtained.SetFromCurrentSystemTime();
token.UpdateString("obtained_at",obtained.getAsTimestamp(false));
// The token response includes expires_in (seconds). Refresh before the access token expires.
// The file contains credentials: use a private, access-controlled directory.
success = token.WriteFile("qa_data/tokens/hotmail.json");
if (success != true) {
Log.i(TAG, "Could not save the token file.");
return;
}
Log.i(TAG, "Credentials saved in the private working directory.");
}
static {
System.loadLibrary("chilkat");
// Note: If the incorrect library name is passed to System.loadLibrary,
// then you will see the following error message at application startup:
//"The application <your-application-name> has stopped unexpectedly. Please try again."
}
}