How to implement OAuth authentication in a .NET application using the BoldSign API?

OAuth2 is a protocol that lets applications securely access the BoldSign API. It uses the OpenID Connect framework for strong and standardized authentication.

To get an access token and use the API, you can use BoldSign's supported OAuth2 workflows, like Client Credential or Authorization Code Grant. This guide focuses on the Authorization Code Grant flow, offering a detailed walkthrough with code examples to help you integrate OAuth2 authentication into your C# application easily.

Below is a detailed walkthrough with code examples for each part of the process.

Create an OAuth2 Application in BoldSign

To start the OAuth2 authorization process, you need to create an OAuth2 application in BoldSign. This application will provide you with the necessary credentials client ID and client secret to authenticate and interact with the BoldSign API.

To create an OAuth app, refer to the article Create an OAuth app

Implement Authorization Code Flow

To begin the OAuth2 authorization code flow with C#, you need to set up a web application that handles the redirect URI endpoint. This endpoint is crucial for receiving the authorization code and exchanging it for access and refresh tokens. Ensure you have the necessary packages installed. You will need System.Net.Http for HTTP requests.

Here's a step-by-step guide to help you get started.

Code snippet

using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;

[Route("api/[controller]")]
[ApiController]
public class OAuthController : ControllerBase
{
    private readonly HttpClient _httpClient = new HttpClient();
    private const string ClientId = "YOUR_CLIENT_ID";
    private const string ClientSecret = "YOUR_CLIENT_SECRET";
    private const string RedirectUri = "http://localhost:5000/api/oauth/callback";
    private const string AuthorizationUrl = "https://account.boldsign.com/connect/authorize";
    private const string TokenUrl = "https://account.boldsign.com/connect/token";
    private const string Scope = "openid profile email offline_access BoldSign.Documents.All";
    private const string CodeVerifier = "YOUR_CODE_VERIFIER";
    private const string CodeChallenge = "YOUR_CODE_CHALLENGE";

    [HttpGet("authorize")]
    public IActionResult Authorize()
    {
        var authorizationUri = $"{AuthorizationUrl}?response_type=code&client_id={ClientId}&redirect_uri={RedirectUri}&scope={Scope}&code_challenge={CodeChallenge}&code_challenge_method=S256";
        return Redirect(authorizationUri);
    }

    [HttpGet("callback")]
    public async Task<IActionResult> Callback(string code)
    {
        var content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "authorization_code"),
            new KeyValuePair<string, string>("client_id", ClientId),
            new KeyValuePair<string, string>("client_secret", ClientSecret),
            new KeyValuePair<string, string>("code", code),
            new KeyValuePair<string, string>("redirect_uri", RedirectUri),
            new KeyValuePair<string, string>("code_verifier", CodeVerifier),
        });

        var response = await _httpClient.PostAsync(TokenUrl, content);
        var responseString = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
        {
            return StatusCode((int)response.StatusCode, responseString);
        }

        return Ok(responseString);
    }
}
    

In the provided code example, replace CLIENT ID with your client id from BoldSign application, CLIENT SECRET with your client secret from BoldSign application.

Generate PKCE Code Verifier and Challenge

When implementing OAuth2 with PKCE (Proof Key for Code Exchange), you need to generate a code verifier and a code challenge to enhance the security of your authorization flow. The code verifier is a random string, and the code challenge is a hashed version of the verifier, both of which are used to verify the authenticity of the authorization request.

To generate a PKCE code verifier and challenge in C#, you can use the following utility function:

Code snippet

using System;
using System.Security.Cryptography;
using System.Text;

public static class PKCEUtil
{
    public static (string CodeVerifier, string CodeChallenge) GeneratePKCECodes()
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var bytes = new byte[32];
            rng.GetBytes(bytes);
            var codeVerifier = Base64UrlEncode(bytes);

            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                var codeChallenge = Base64UrlEncode(hash);
                return (codeVerifier, codeChallenge);
            }
        }
    }

    private static string Base64UrlEncode(byte[] bytes)
    {
        var base64 = Convert.ToBase64String(bytes);
        return base64.Replace("+", "-").Replace("/", "_").Replace("=", "");
    }
}

// Example usage
var (codeVerifier, codeChallenge) = PKCEUtil.GeneratePKCECodes();
Console.WriteLine($"Code Verifier: {codeVerifier}");
Console.WriteLine($"Code Challenge: {codeChallenge}");

     

Refresh Access Token

Once you have the refresh token, you can use it to obtain a new access token without requiring the user to reauthorize your application. This process ensures continuous access to the BoldSign API. Here's how you can do it:

Code snippet

public async Task RefreshAccessTokenAsync(string refreshToken)
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("grant_type", "refresh_token"),
        new KeyValuePair<string, string>("client_id", ClientId),
        new KeyValuePair<string, string>("client_secret", ClientSecret),
        new KeyValuePair<string, string>("refresh_token", refreshToken),
    });

    var response = await _httpClient.PostAsync(TokenUrl, content);
    var responseString = await response.Content.ReadAsStringAsync();

    if (!response.IsSuccessStatusCode)
    {
        Console.WriteLine($"Error refreshing access token: {responseString}");
        return;
    }

    Console.WriteLine($"New tokens: {responseString}");
}

// Example usage
await RefreshAccessTokenAsync("YOUR_CURRENT_REFRESH_TOKEN");
     

Testing the Token Refresh Endpoint

You can test the /refresh-token endpoint using Postman or an HTML form. Here’s how to do it with Postman:

  1. Open Postman and create a new POST request.

  2. Set the URL to {Your application URL}/refresh-token.

  3. Set the Body to x-www-form-urlencoded and add the following key-value pairs:

  4. refresh_token: The refresh token you received from the initial token exchange.

  5. Send the Request and you should receive a new access token and refresh token in the response.

Using these techniques, you can securely integrate OAuth2 authentication into your C# applications and access the BoldSign API.