OAuth2 Class
This class provides methods for OAuth 2.0 authentication process.
Inheritance Hierarchy
SystemObject
  MailBeeOAuth2

Namespace: MailBee
Assembly: MailBee.NET (in MailBee.NET.dll) Version: 12.4 build 677 for .NET 4.5
Syntax
public class OAuth2

The OAuth2 type exposes the following members.

Constructors
  NameDescription
Public methodOAuth2
Initializes a new instance of OAuth2 object with a client key pair.
Top
Methods
  NameDescription
Public methodCode exampleAuthorizeToken
Fetches Request Authorize from the specified URI (URL).
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected methodFinalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object.)
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodCode exampleGetXOAuthKey
Fetches XOAuth key for the specified e-mail address.
Public methodStatic memberCode exampleGetXOAuthKeyStatic
The version of GetXOAuthKey(String, String) which does not require you to create an instance of OAuth2 class.
Protected methodMemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Top
Fields
  NameDescription
Public fieldStatic memberClientIdKey
The name of Client-ID-Key parameter.
Public fieldStatic memberRedirectUriKey
The name of Redirect-Uri-Key parameter.
Public fieldStatic memberResponseTypeKey
The name of Response-Type-Key parameter.
Public fieldStatic memberScope
The name of Scope parameter.
Top
Remarks

OAuth enables websites or applications to access users' mailboxes and profile data without requiring users to disclose their credentials to these web sites or applications. It means that a 3d party application doesn't need to get the username and the password to access data via API from the restricted application.

For instance, your application can ask the user to authorize its attempt to access data in their Gmail or Outlook.com mailbox. MailBee provides your application with the URL on Google or Microsoft web site which should be opened in the browser. The page asks the user if they confirm that your application is trusted to access their mailbox. If the user confirms that, Google or Microsoft returns the authorization key. The application then use this key to get an access token from Google or Microsoft server, and then you can then use it with OAuth 2.0 method when logging in Gmail or Microsoft account of the user. The same will work for any OAuth 2.0 capable provider which supports XOAUTH2 extension in their IMAP or SMTP service.

The methods of this class help you complete OAuth 2.0 authorization process and get OAuth keys which can be used for authentication on IMAP/SMTP servers that support XOAUTH2 extension. You can also use this class to get OAuth 2.0 keys for other purposes with any software capable of OAuth 2.0 authentication because the produced keys are not specific to MailBee.

Note Note
Check OAuth 2.0 in Windows and ASP.NET MVC apps topic for detailed tutorials on using OAuth 2.0 with Office 365, Outlook.com, Live.com, Hotmail.com, Gmail (including Google Apps specific case, Service Accounts). The tutorials cover many related aspects such as refresh tokens, passing OAuth authorization code from OAuth providers' web sites to the application, IIS configuration, etc.
Examples

This sample authenticates client in Gmail IMAP via OAuth 2.0 using DotNetOpenAuth library (.NET 3.5+). User should get registered their application as described here: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth and specify the keys received from Google in the application code (clientID and clientSecret variables) along with their e-mail address. The keys can be generated in Google Developers Console at https://console.developers.google.com, where you select your project and then "APIs & auth" / "Credentials".

A newer way of doing OAuth 2.0 with Google is using Google API Auth Client library described in OAuth 2.0 for Google Regular Accounts (installed applications) tutorial. Note that Google API requires .NET 4.0 or higher. You can find the example at GetXOAuthKeyStatic(String, String) topic.

The sample uses IMAP but for SMTP and POP3 it would be all the same (assuming that the corresponding mail service provider supports OAuth 2.0 for that protocols).

using System;
using System.Collections.Specialized;
using MailBee;
using MailBee.ImapMail;
using DotNetOpenAuth.OAuth2;

class Sample
{
    static string GetAccessToken(string clientID, string clientSecret, string key)
    {
        UserAgentClient consumer;
        IAuthorizationState grantedAccess;

        // Second: Fetch Access Token
        StringDictionary parameters2 = new StringDictionary();
        parameters2.Add(OAuth2.RedirectUriKey, "urn:ietf:wg:oauth:2.0:oob");

        string uri = "https://accounts.google.com/o/oauth2/token";

        AuthorizationServerDescription server = new AuthorizationServerDescription();
        server.TokenEndpoint = new Uri(uri);
        server.ProtocolVersion = ProtocolVersion.V20;

        consumer = new UserAgentClient(server, clientID, clientSecret);

        consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret);

        IAuthorizationState authorizationState = new AuthorizationState(null);

        if (parameters2.ContainsKey(OAuth2.RedirectUriKey))
        {
            authorizationState.Callback = new Uri(parameters2[OAuth2.RedirectUriKey]);
        }

        // Build a generic URL containing the auth code.
        // This is done here as we cannot modify the DotNetOpenAuth library 
        // and the underlying method only allows parsing an URL as a method 
        // of retrieving the AuthorizationState.
        string url = "http://example.com/?code=" + key;

        try
        {
            grantedAccess = consumer.ProcessUserAuthorization(new Uri(url), authorizationState);
        }
        catch (DotNetOpenAuth.Messaging.ProtocolException e)
        {
            Console.WriteLine(e.Message);
            return null;
        }

        return grantedAccess.AccessToken;
    }

    static void Main(string[] args)
    {
        string clientID = "somewhat like 628470012345.apps.googleusercontent.com";
        string clientSecret = "somewhat like 8IbRSofadFQ7ThjClxp8GBa2";
        string userEmail = "john.doe@gmail.com";

        OAuth2 myOAuth2 = new OAuth2(clientID, clientSecret);

        StringDictionary parameters1 = new StringDictionary();
        parameters1.Add(OAuth2.Scope, "https://mail.google.com/");
        parameters1.Add(OAuth2.RedirectUriKey, "urn:ietf:wg:oauth:2.0:oob");
        parameters1.Add(OAuth2.ResponseTypeKey, "code");

        // First: Redirect to Authorization and Fire up the browser
        System.Diagnostics.Process.Start(
            myOAuth2.AuthorizeToken("https://accounts.google.com/o/oauth2/auth", parameters1));

        Console.Write("Please enter the Authorization key from Google: ");
        string key = Console.ReadLine().Trim();

        // Second: Fetch Access Token
        string accessToken = GetAccessToken(clientID, clientSecret, key);
        if (accessToken == null)
        {
            return;
        }

        // Get XOAuth key for IMAP.
        string imapXOAuthKey = myOAuth2.GetXOAuthKey(userEmail, accessToken);

        Imap imp = new Imap();

        // In the log, you can find the actual search queries sent to the server.
        imp.Log.Filename = "C:\\Temp\\log.txt";
        imp.Log.Enabled = true;
        imp.Log.Clear();

        imp.Connect("imap.gmail.com", 993);
        imp.Login(null, imapXOAuthKey, AuthenticationMethods.SaslOAuth2, AuthenticationOptions.None, null);
        imp.SelectFolder("INBOX");

        Console.WriteLine(imp.MessageCount.ToString() + " message(s) in INBOX");

        imp.Disconnect();
    }
}
See Also