Skip to content

Mastercard/oauth1-signer-csharp

Repository files navigation

oauth1-signer-csharp

Table of Contents

Overview

Compatibility

.NET

  • OAuth1Signer.Core targets .NET Standard 2.1
  • OAuth1Signer.RestSharp targets .NET Standard 2.1
  • OAuth1Signer.RestSharpV2 targets .NET Standard 2.1

.NET Standard versions supported by .NET implementations can be found in the following articles: .NET Standard, .NET Standard versions.

Strong Naming

Assemblies are strong-named as per Strong naming and .NET libraries. The SN key is available here: Identity.snk.

References

Versioning and Deprecation Policy

Usage

Prerequisites

Before using this library, you will need to set up a project in the Mastercard Developers Portal.

As part of this set up, you'll receive credentials for your app:

  • A consumer key (displayed on the Mastercard Developer Portal)
  • A private request signing key (matching the public certificate displayed on the Mastercard Developer Portal)

Adding the Libraries to Your Project

Package Manager

Install-Package Mastercard.Developer.OAuth1Signer.{Core|RestSharp|RestSharpV2}

.NET CLI

dotnet add package Mastercard.Developer.OAuth1Signer.{Core|RestSharp|RestSharpV2}

Loading the Signing Key

A System.Security.Cryptography.RSA key object can be created by calling the AuthenticationUtils.LoadSigningKey method:

var signingKey = AuthenticationUtils.LoadSigningKey(
                        "<insert PKCS#12 key file path>", 
                        "<insert key alias>", 
                        "<insert key password>");

Creating the OAuth Authorization Header

The method that does all the heavy lifting is OAuth.GetAuthorizationHeader, in the OAuth1Signer.Core package. You can call into it directly and as long as you provide the correct parameters, it will return a string that you can add into your request's Authorization header.

var consumerKey = "<insert consumer key>";
var uri = "https://sandbox.api.mastercard.com/service";
var method = "POST";
var payload = "Hello world!";
var encoding = Encoding.UTF8;
var authHeader = OAuth.GetAuthorizationHeader(uri, method, payload, encoding, consumerKey, signingKey);

Signing HTTP Client Request Objects

Alternatively, you can use helper classes for some of the commonly used HTTP clients.

These classes will modify the provided request object in-place and will add the correct Authorization header. Once instantiated with a consumer key and private key, these objects can be reused.

Usage briefly described below, but you can also refer to the test project for examples.

System.Net.Http.HttpClient

The NetHttpClientSigner class is located in the OAuth1Signer.Core package.

Usage:

var baseUri = new Uri("https://api.mastercard.com/");
var httpClient = new HttpClient(new RequestSignerHandler(consumerKey, signingKey)) { BaseAddress = baseUri };
var postTask = httpClient.PostAsync(new Uri("/service", UriKind.Relative), new StringContent("{\"foo\":\"bår\"}");
// (…)

internal class RequestSignerHandler : HttpClientHandler
{
    private readonly NetHttpClientSigner signer;

    public RequestSignerHandler(string consumerKey, RSA signingKey)
    {
        signer = new NetHttpClientSigner(consumerKey, signingKey);
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        signer.Sign(request);
        return base.SendAsync(request, cancellationToken);
    }
}

RestSharp

A RestSharpSigner class is provided for both RestSharp and RestSharp Portable. It can be found in the OAuth1Signer.RestSharp and OAuth1Signer.RestSharpV2 packages.

Usage:

var baseUri = new Uri("https://api.mastercard.com/");
var request = new RestRequest
{
    Method = Method.POST,
    Resource = "/service",
    Parameters =
    {
        new Parameter { Type = ParameterType.RequestBody, Encoding = Encoding.UTF8, Value = "{\"foo\":\"bår\"}"} // "application/json; charset=utf-8"
    }
};
var signer = new RestSharpSigner(consumerKey, signingKey);
signer.Sign(baseUri, request);

Integrating with OpenAPI Generator API Client Libraries

OpenAPI Generator generates API client libraries from OpenAPI Specs. It provides generators and library templates for supporting multiple languages and frameworks.

This project provides you with some authenticator classes you can use when configuring your API client. These classes will take care of adding the correct Authorization header before sending the request.

Generators currently supported:

csharp-netcore

OpenAPI Generator

Client libraries can be generated using the following command:

openapi-generator-cli generate -i openapi-spec.yaml -g csharp-netcore -c config.json -o out

config.json:

{ "targetFramework": "netstandard2.1" }

See also:

Usage of the RestSharpSigner

RestSharpSigner is located in the OAuth1Signer.RestSharpV2 package.

Usage

Create a new file (for instance, MastercardApiClient.cs) extending the definition of the generated ApiClient class:

partial class ApiClient
{
    private readonly Uri _basePath;
    private readonly RestSharpSigner _signer;

    /// <summary>
    /// Construct an ApiClient which will automatically sign requests
    /// </summary>
    public ApiClient(RSA signingKey, string basePath, string consumerKey)
    {
        _baseUrl = basePath;
        _basePath = new Uri(basePath);
        _signer = new RestSharpSigner(consumerKey, signingKey);
    }

    partial void InterceptRequest(RestRequest request)
    {
        _signer.Sign(_basePath, request);
    }
}

Configure your ApiClient instance the following way:

var client = new ApiClient(SigningKey, BasePath, ConsumerKey);
var serviceApi = new ServiceApi() { Client = client };
// …

csharp (deprecated)

OpenAPI Generator

Client libraries can be generated using the following command:

openapi-generator-cli generate -i openapi-spec.yaml -g csharp -c config.json -o out

config.json:

{ "targetFramework": "netstandard2.1" }

⚠️ v5.0 was used for targetFramework in OpenAPI Generator versions prior 5.0.0.

See also:

Usage of the RestSharpOAuth1Authenticator

RestSharpOAuth1Authenticator is located in the OAuth1Signer.RestSharp package.

var config = Configuration.Default;
config.BasePath = "https://sandbox.api.mastercard.com";
config.ApiClient.RestClient.Authenticator = new RestSharpOAuth1Authenticator(ConsumerKey, signingKey, new Uri(config.BasePath));
var serviceApi = new ServiceApi(config);
// …