API client configuration

BoldSign API authentication supports both authentication code flow and client credentials. In the following example, it is demonstrated with client credentials grant type.

ASP.NET core

BoldSign's API authentication is done using OAuth2 Client Credential flow. The TokenService is a helper class to get the access token and to be used for dependency injection.

public class TokenService
{
    private readonly HttpClient httpClient;
    private readonly ApiClient apiClient;
    private static string accessToken = null;
    private static DateTime? expiresAt = null;

    public TokenService(HttpClient httpClient, ApiClient apiClient)
    {
        this.httpClient = httpClient;
        this.apiClient = apiClient;
    }

    public async Task SetTokenAsync()
    {
        if (!(accessToken != null && expiresAt != null && expiresAt > DateTime.UtcNow.AddMinutes(-5)))
        {
            // Need to add required scopes.
            var parameters = new List<KeyValuePair<string, string>>
            {
            new KeyValuePair<string, string>("grant_type", "client_credentials"),
            new KeyValuePair<string, string>("scope", "BoldSign.Documents.All BoldSign.Templates.All")
            };

            using var encodedContent = new FormUrlEncodedContent(parameters);

            using var request = new HttpRequestMessage()
            {
                Content = encodedContent,
                Method = HttpMethod.Post,
                RequestUri = new Uri("https://account.boldsign.com/connect/token"),
            };

            //Clientid to get access token
            const string clientId = "***client-id***";

            //Clientsecret for get access token
            const string clientSecret = "***client-secret***";
            var encodedAuth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedAuth);
            var encodedAuth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedAuth);

            //Send request for fetching access token
            using var response = await this.httpClient.SendAsync(request).ConfigureAwait(false);
            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            var tokenResponse = JsonConvert.DeserializeObject<Dictionary<string, string>>(content);
            tokenResponse.TryGetValue("access_token", out accessToken);
            tokenResponse.TryGetValue("expires_in", out var expiresIn);
            expiresAt = DateTime.UtcNow.AddSeconds(Convert.ToInt32(expiresIn));
            this.apiClient.Configuration.DefaultHeader.Remove("Authorization");
            // Added accesstoken in default header.
            this.apiClient.Configuration.DefaultHeader.TryAdd("Authorization", "Bearer " + accessToken);
        }
    }

The ApiClient class represents the base class object used as a starting point for all API calls and injects the ApiClient and TokenService into Startup.ConfigureServices.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ApiClient>();
    services.AddHttpClient<TokenService>();
}

Add a middleware to set the access token by using the TokenService in the StartUp Configure method.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.RequestServices.GetRequiredService<TokenService>().SetTokenAsync().ConfigureAwait(false);
        await next();
    });
}

Once you have fetched the access token, you will be able to authenticate and use BoldSign API endpoints.

You can consume BoldSign API either using the REST API or the C# SDK. BoldSign's SDK is the simplest way to consume the API from .NET.

You will be able to reuse this ApiClient in both DocumentClient and TemplateClient.

public class HomeController : Controller
{
    private readonly ApiClient apiClient;

    /// <summary>
    /// Initializes a new instance of the <see cref="HomeController"/> class.
    /// </summary>
    /// <param name=" apiClient ">The api client.</param>
    public HomeController(ApiClient apiClient)
    {
        this.apiClient = apiClient;
    }
}

Create a new instance of the DocumentClient as shown below. By instantiating the DocumentClient class to use the preconfigured apiClient, you are ready to make all document-based API calls.

var documentClient = new DocumentClient(this.apiClient);

DotNet core console app

In the following examples, we have used client credentials for the BoldSign's API authentication and used the HttpClient to get the access token.

using var http = new HttpClient();
string accessToken = null;
// need to add required scopes.
var parameters = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("grant_type", "client_credentials"),
    new KeyValuePair<string, string>("scope", "BoldSign.Documents.All BoldSign.Templates.All")
};

using var encodedContent = new FormUrlEncodedContent(parameters);
using var request = new HttpRequestMessage()
{
    Content = encodedContent,
    Method = HttpMethod.Post,
    RequestUri = new Uri("https://account.boldsign.com/connect/token"),
};

//clientid for get access token
const string clientId = "***client-id***";

//clientsecret for get access token
const string clientSecret = "***client-secret***";

var encodedAuth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedAuth);

//send request for fetch access token
using var response = await this.httpClient.SendAsync(request).ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var tokenResponse = JsonConvert.DeserializeObject<Dictionary<string, string>>(content);
tokenResponse.TryGetValue("access_token", out accessToken);
var configuration = new Configuration();

// set your OAuth2 Access Token for authentication.
configuration.SetBearerToken(accessToken);
var apiClient = new ApiClient(configuration);

This access token configuration will be applied to all the API calls, so you can start creating signature requests using the Document API class.

Create a new instance of the DocumentClient, as shown in the following code sample.

var documentClient = new DocumentClient(apiClient);