BoldSignDocumentation
BoldSign Mobile Icon

Authentication

Mon, 5 Apr, 2021

Our API uses both basic and OAuth 2.0 authentication to make requests to BoldSign API. Using OAuth, you can request a signature on behalf of other BoldSign users.

Basic Authentication

The API key authentication is a basic authentication methodology. It is simple and can be used as alternative for OAuth for connecting and authenticating BoldSign’s API services. This type of authentication is supported only with live environment and will not work with sandbox environment.

This section will explain, how to get the API token from our APP with screenshots and steps to implement it in code:

  1. Go to the API menu item on the app’s left navigation pane and then click on “API Key”.

api_key_main.png

  1. Click the “Generate API Key” button.
  2. You will be prompted with the “Generate API Key” dialog.

api_key_dialog.png

  1. Click “Generate Token” button
  2. Copy the API key and this key is required to configure the Basic Authentication in your app.

api_key_final.png

Create a new instance of the ApiClient as shown below and then add API key in default header with key name as “X-API-Key”, then you are ready to make all document-based API calls.

C#CURL

ApiClient apiClient = new ApiClient();
// Added api key in default header.
apiClient.Configuration.DefaultHeader.Add("X-API-KEY", "**Api key**");
curl -X GET 'https://api.boldsign.com/v1/document/list?page=1&pagesize=20' \
-H 'Content-Type: application/json' \
-H 'X-API-KEY: <apikey>'

OAuth 2.0

OAuth allows you to perform actions on behalf of other BoldSign users, using “Authorization Code Grant Flow” and “client credential flow” to authenticate themselves and get a token.

App Registration

App registration process is available in this link

Authorization Code Grant Flow

The below code explains Authorization Code Grant with ASP.NET Core and add the following code to your startup.cs file in the method ConfigureServices()

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureSameSiteNoneCookies();

    // Add authentication services
    services.AddAuthentication(options =>
    {
        options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
         options.DefaultChallengeScheme = "BoldSign";
    })
    .AddCookie()
            .AddOAuth("BoldSign", options =>
            {
                string domain = "https://account.boldsign.com";

                // Configure the Auth0 Client ID and Client Secret
                options.ClientId = "***client-id***";
                options.ClientSecret = "***client-secret***";
                options.CallbackPath = new PathString("/redirect");
                options.AuthorizationEndpoint = domain + "/connect/authorize";
                options.TokenEndpoint = domain + "/connect/token";
                options.UserInformationEndpoint = domain + "/connect/userinfo";
                // Configure the scope
                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("offline_access");
                options.Scope.Add("BoldSign.Documents.All");
                options.Scope.Add("BoldSign.Templates.All");
                options.SaveTokens = true;
                options.UsePkce = true;
                options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
                options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                options.ClaimActions.MapJsonKey("access_token", "access_token");
                options.ClaimActions.MapJsonKey("refresh_token", "refresh_token");
                options.ClaimActions.MapJsonKey("expires_in", "expires_in");
                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                        var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();
                        var user = JObject.Parse(await response.Content.ReadAsStringAsync());

                        user.Add("access_token", context.AccessToken);
                        user.Add("refresh_token", context.RefreshToken);
                        user.Add("expires_in", DateTime.Now.AddMinutes(1).ToString());

                        using (JsonDocument payload = JsonDocument.Parse(user.ToString()))
                        {
                            context.RunClaimActions(payload.RootElement);
                        }
                    },
                    OnRemoteFailure = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);
                        return Task.FromResult(0);
                    },
                    OnAccessDenied = context =>
                    {
                        return Task.FromResult(0);
                    }
                };
            });
}

And then to ensure that the authentication services execute on each request, add UseAuthentication to Configure in Startup:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication();
    app.UseAuthorization();
}

Add the below method in your controller.

public async Task Login(string returnUrl = "/")
{
    await HttpContext.ChallengeAsync("BoldSign", new AuthenticationProperties()
    {
        RedirectUri = returnUrl
    });
}

Run the application and, once it’s finished, it opens the following browser page:

login-page.png

Enter the username and password and then click the Login button. You’ll be redirected to the BoldSign official authorization web page. Then, click the “Allow button” and you’ll be redirected to the application again.

authorize.png

scope

The scopes provide a way to limit the amount of access that is granted to an access token. For example, an access token issued to a client app may be granted READ and WRITE access to protected resources, or just READ access. We will support following scopes:

"BoldSign.Documents.All",
"BoldSign.Documents.Read",
"BoldSign.Documents.Write",
"BoldSign.Documents.Delete",
"BoldSign.Documents.Create",
"BoldSign.Templates.All",
"BoldSign.Templates.Read",
"BoldSign.Templates.Write",
"BoldSign.Templates.Delete",
"BoldSign.Templates.Create"

Client Credential Flow

The Client Credentials grant is used when applications request an access token to access their own resources, not on behalf of a user. Typically the service will allow either additional request parameters client_id and client_secret, or accept the client ID and secret in the HTTP Basic auth header.

grant_type

The grant_type parameter must be set to client_credentials.

Example

The following is an example of authorization code grant the service would receive:

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 fectch 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);
Copied to clipboard