Discuss this help topic in SecureBlackbox Forum

POP3: Login to the server using OAuth2

Login using OAuth2 tokens can be different from server to server. We'll review the GMail case.

The simplest way to login to GMail POP3 server is to use TElSimpleOAuth2Client class. The following code snippet shows how to have this task done.


// create an HTTPS client; it's required to contact the authorization server
TElHTTPSClient https = new TElHTTPSClient();
// assign an event handler to validate SSL certificate(s)
https.OnCertificateValidate += ...;

// create a OAuth 2.0 client
TElSimpleOAuth2Client oauth = new TElSimpleOAuth2Client();
// assign the created HTTPS transport
oauth.HTTPClient = https;
// set the local URL to be used during authorization;
// the specified port must be free and the program
// has to be allowed to open a listening socket on that port
oauth.RedirectURL = @"http://localhost:5050/";
// the event is fired when it's needed to open a web page in a browser
oauth.OnLaunchBrowser += delegate (object Sender, string URL)
// authorization server URLs
oauth.AuthURL = @"https://accounts.google.com/o/oauth2/auth";
oauth.TokenURL = @"https://accounts.google.com/o/oauth2/token";

// copy client id and client secret from Google Developers Console
oauth.ClientID = @"your_client_id";
oauth.ClientSecret = @"your_client_secret";
// tell the authorization server what access is needed
oauth.Scope = @"https://mail.google.com/";

// restore the refresh token from the previous session;
// this allows to not ask the user to login in the browser each time
oauth.RefreshToken = @"refresh_token_string";

// actually, perform the authorization
if (!oauth.Authorize())
    return;    // the user has cancelled authorization

// itís a good idea to save the refresh token for future use
Console.WriteLine("RefreshToken: " + oauth.RefreshToken);
// create a POP3 client
TElPOP3Client pop3 = new TElPOP3Client();
// configure it to connect to Google POP3 server
pop3.Address = "pop.gmail.com";
pop3.Port = 995;
pop3.SSLMode = SBSSLCommon.TSBSSLMode.smImplicit;
pop3.UseSSL = true;
// assign an event handler to validate SSL certificate(s)
pop3.OnCertificateValidate += ...;

// connect to the server

// enable the necessary mechanism
pop3.set_Authorization(SBPOP3Client.Unit.popSASL, true);
pop3.set_AuthorizationPriorities(SBPOP3Client.Unit.popSASL, 1000);
pop3.set_SASLMechanism("XOAUTH2", true);
pop3.set_SASLMechanismPriorities("XOAUTH2", 1000);

// username must be the same as the one used to login in the browser
pop3.Username = "cooluser";
// use access token as the password
pop3.Password = oauth.AccessToken;

// actually, login to the server

How To articles about POP3 client

Discuss this help topic in SecureBlackbox Forum