Custom client

Creating OAuth client

Create a new client for OAuth is very simple!

1. Use one of two basic classes:

  • OAuthClient for OAuth 1.0
  • OAuth2Client for OAuth 2.0

NOTE: If the provider supports both versions of the protocol. recommended to use OAuth 2.0 (OAuth2Client class).

2. Specify a unique name of the client.

CopyC#
/// <summary>
/// Unique provider name: <b>NewClient</b>.
/// </summary>
public override string ProviderName
{
  get
  {
    return "NewClient";
  }
}

3. In the constructor, specify the base address for authorization and the address for obtaining the access token.

This information can be found on the site of the provider.

CopyC#
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="clientId">The Client ID obtained from the provider website.</param>
/// <param name="clientSecret">The Client Secret obtained from the provider website.</param>
public NewClient(string clientId, string clientSecret) : base
(
  "https://example.org/oauth",
  "https://example.org/oauth/access_token", 
  clientId,
  clientSecret
) 
{ }

4. The hardest: overriding the GetUserInfo method.

You will need to examine API of the provider.

Use the access token to work with the API.

CopyC#
string accessToken = this.AccessToken["access_token"].ToString();

You can use the Helpers.ExecuteRequest method to send a request to the API.

CopyC#
// query parameters
var parameters = new NameValueCollection
{ 
  { "access_token" , this.AccessToken["access_token"].ToString() }
};

// execute the request
var result = Helpers.ExecuteRequest
(
  "GET",
  "https://api.example.com/user",
  parameters,
  null
);

You will need transfer the user data into the UserInfo instance.

You can use the ApiDataMapping class for mapping API results with UserInfo properties.

5. Use your client in the usual way!

CopyC#
OAuthManager.RegisterClient
(
  new NewClient
  (
    "client id",
    "client secret"
  )
);
CopyC#
string url = OAuthWeb.GetAuthorizationUrl("NewClient");

 

If you have any problems with this, let me know.