BoldSignDocumentation
BoldSign Mobile Icon

Preparing your application

Thu, 31 Mar, 2021

Install the package

dotnet add package BoldSign.Api 

The other ways of installing a package available here.

Install and manage NuGet packages in Visual Studio

Prerequisites

  1. To work with BoldSign API, you need an enterprise or trial plan.

https://www.boldsign.com/pricing/

  1. You should be an account admin to create a developer and configuring webhooks.

Acquire app credentials

  1. Go to API menu item on the app's left navigation pane and then click on "Developer Apps".
  2. Click the "Create App" button in the top right corner.

Create app button

  1. You will be prompted with the Create Application dialog. It is possible to configure separate credentials for test and live production environments.

Create application

  1. Specify the Application Name and Client Secret Validity details.
  2. In the redirect URL section, add the needed URLs. For ex, local development URL's could be http://localhost:3000, live application URL's will be something like https://yourapp.com/.
  3. Click Save.
  4. You will now be redirected to the App details page of your new API application.

App details page

  1. You need to copy the Client ID and Client Secret Key and store it for future reference. These keys are required to configure the OAuth Client in your app.

Note: Client Secret key cannot be viewed again after you have navigated away from this page. A new key has to be created in case you lose this client secret key.

API Client configuration

BoldSign API authentication supports both Authentication code flow and client credentials. In the below 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))
{
// added accesstoken in default header.
this.apiClient.Configuration.DefaultHeader.TryAdd("Authorization", "Bearer " + accessToken);
}
else
{
// 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);
tokenResponse.TryGetValue("expires_in", out var expiresIn);
expiresAt = DateTime.UtcNow.AddSeconds(Convert.ToInt32(expiresIn));

// 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 inject 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 into 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 fetched the access token, you will be able to authenticate and use BoldSign API endpoints.

You can consume BoldSign API either using REST API or C# SDK. BoldSign's SDK is the simpler 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 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 below examples, we have used client credential for the BoldSign's API authentication, and used HttpClient to get 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 new instance of the DocumentClient as shown below.

var documentClient = new DocumentClient(apiClient);