Skip to content

clerk/clerk-sdk-csharp

Repository files navigation

The most comprehensive User Management Platform



Summary

Clerk Backend API: The Clerk REST Backend API, meant to be accessed by backend servers.

Versions

When the API changes in a way that isn't compatible with older versions, a new version is released. Each version is identified by its release date, e.g. 2025-04-10. For more information, please see Clerk API Versions.

Please see https://clerk.com/docs for more information.

More information about the API can be found at https://clerk.com/docs

Table of Contents

SDK Installation

NuGet

To add the NuGet package to a .NET project:

dotnet add package Clerk.BackendAPI

Locally

To add a reference to a local instance of the SDK in a .NET project:

dotnet add reference src/Clerk/BackendAPI/Clerk.BackendAPI.csproj

SDK Example Usage

Example

using Clerk.BackendAPI;
using Clerk.BackendAPI.Models.Components;

var sdk = new ClerkBackendApi(bearerAuth: "<YOUR_BEARER_TOKEN_HERE>");

var res = await sdk.EmailAddresses.GetAsync(emailAddressId: "email_address_id_example");

// handle response

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
BearerAuth http HTTP Bearer

To authenticate with the API the BearerAuth parameter must be set when initializing the SDK client instance. For example:

using Clerk.BackendAPI;
using Clerk.BackendAPI.Models.Components;
using Clerk.BackendAPI.Models.Operations;

var sdk = new ClerkBackendApi(bearerAuth: "<YOUR_BEARER_TOKEN_HERE>");

GetPublicInterstitialRequest req = new GetPublicInterstitialRequest() {
    FrontendApiQueryParameter = "frontend-api_1a2b3c4d",
    FrontendApiQueryParameter1 = "pub_1a2b3c4d",
};

var res = await sdk.Miscellaneous.GetPublicInterstitialAsync(req);

// handle response

Request Authentication

Use the AuthenticateRequestAsync method to authenticate a request from your app's frontend (when using a Clerk frontend SDK) to Clerk's Backend API. For example the following utility function checks if the user is effectively signed in:

using Clerk.BackendAPI.Helpers.Jwks;
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class UserAuthentication
{
    public static async Task<bool> IsSignedInAsync(HttpRequestMessage request)
    {
        var options = new AuthenticateRequestOptions(
            secretKey: Environment.GetEnvironmentVariable("CLERK_SECRET_KEY"),
            authorizedParties: new string[] { "https://example.com" }
        );

        var requestState = await AuthenticateRequest.AuthenticateRequestAsync(request, options);

        return requestState.isSignedIn();
    }
}

Machine Authentication

For machine-to-machine authentication, you can use machine tokens as shown below.

using Clerk.BackendAPI.Helpers.Jwks;
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class MachineAuthentication
{
    // Accept only machine tokens
    public static async Task<bool> IsMachineAuthenticatedAsync(HttpRequestMessage request)
    {
        var options = new AuthenticateRequestOptions(
            secretKey: Environment.GetEnvironmentVariable("CLERK_SECRET_KEY"),
            acceptsToken: new[] { "oauth_token" }  // Only accept oauth tokens
        );

        var requestState = await AuthenticateRequest.AuthenticateRequestAsync(request, options);
        return requestState.isSignedIn();
    }
}

Available Resources and Operations

Available methods
  • List - List all identifiers on the allow-list
  • Create - Add identifier to the allow-list
  • Delete - Delete identifier from allow-list
  • List - List all identifiers on the block-list
  • Create - Add identifier to the block-list
  • Delete - Delete identifier from block-list
  • List - List all clients ⚠️ Deprecated
  • Verify - Verify a client
  • Get - Get a client
  • List - List all instance domains
  • Add - Add a domain
  • Delete - Delete a satellite domain
  • Update - Update a domain
  • Create - Create an email address
  • Get - Retrieve an email address
  • Delete - Delete an email address
  • Update - Update an email address
  • Upsert - Update a template for a given type and slug ⚠️ Deprecated
  • List - List all templates ⚠️ Deprecated
  • Get - Retrieve a template ⚠️ Deprecated
  • Revert - Revert a template ⚠️ Deprecated
  • ToggleTemplateDelivery - Toggle the delivery by Clerk for a template of a given type and slug ⚠️ Deprecated
  • Create - Create an invitation
  • List - List all invitations
  • BulkCreate - Create multiple invitations
  • Revoke - Revokes an invitation
  • GetJWKS - Retrieve the JSON Web Key Set of the instance
  • List - List all templates
  • Create - Create a JWT template
  • Get - Retrieve a template
  • Update - Update a JWT template
  • Delete - Delete a Template
  • Verify - Verify an OAuth Access Token
  • List - Get a list of OAuth applications for an instance
  • Create - Create an OAuth application
  • Get - Retrieve an OAuth application by ID
  • Update - Update an OAuth application
  • Delete - Delete an OAuth application
  • RotateSecret - Rotate the client secret of the given OAuth application
  • Create - Create a new organization domain.
  • List - Get a list of all domains of an organization.
  • Update - Update an organization domain.
  • Delete - Remove a domain from an organization.
  • ListAll - List all organization domains
  • GetAll - Get a list of organization invitations for the current instance
  • Create - Create and send an organization invitation
  • List - Get a list of organization invitations
  • BulkCreate - Bulk create and send organization invitations
  • ListPending - Get a list of pending organization invitations ⚠️ Deprecated
  • Get - Retrieve an organization invitation by ID
  • Revoke - Revoke a pending organization invitation
  • Create - Create a new organization membership
  • List - Get a list of all members of an organization
  • Update - Update an organization membership
  • Delete - Remove a member from an organization
  • UpdateMetadata - Merge and update organization membership metadata
  • List - Get a list of organizations for an instance
  • Create - Create an organization
  • Get - Retrieve an organization by ID or slug
  • Update - Update an organization
  • Delete - Delete an organization
  • MergeMetadata - Merge and update metadata for an organization
  • UploadLogo - Upload a logo for the organization
  • DeleteLogo - Delete the organization's logo.
  • GetBillingSubscription - Retrieve an organization's billing subscription
  • Create - Create a phone number
  • Get - Retrieve a phone number
  • Delete - Delete a phone number
  • Update - Update a phone number
  • Verify - Verify the proxy configuration for your domain
  • List - List all redirect URLs
  • Create - Create a redirect URL
  • Get - Retrieve a redirect URL
  • Delete - Delete a redirect URL
  • List - Get a list of SAML Connections for an instance
  • Create - Create a SAML Connection
  • Get - Retrieve a SAML Connection by ID
  • Update - Update a SAML Connection
  • Delete - Delete a SAML Connection
  • Create - Create sign-in token
  • Revoke - Revoke the given sign-in token
  • Get - Retrieve a sign-up by ID
  • Update - Update a sign-up
  • Preview - Preview changes to a template ⚠️ Deprecated
  • Create - Retrieve a new testing token
  • List - List all waitlist entries
  • Create - Create a waitlist entry
  • Delete - Delete a pending waitlist entry
  • Invite - Invite a waitlist entry
  • Reject - Reject a waitlist entry

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply pass a RetryConfig to the call:

using Clerk.BackendAPI;
using Clerk.BackendAPI.Models.Operations;

var sdk = new ClerkBackendApi();

GetPublicInterstitialRequest req = new GetPublicInterstitialRequest() {
    FrontendApiQueryParameter = "frontend-api_1a2b3c4d",
    FrontendApiQueryParameter1 = "pub_1a2b3c4d",
};

var res = await sdk.Miscellaneous.GetPublicInterstitialAsync(
    retryConfig: new RetryConfig(
        strategy: RetryConfig.RetryStrategy.BACKOFF,
        backoff: new BackoffStrategy(
            initialIntervalMs: 1L,
            maxIntervalMs: 50L,
            maxElapsedTimeMs: 100L,
            exponent: 1.1
        ),
        retryConnectionErrors: false
    ),
    request: req
);

// handle response

If you'd like to override the default retry strategy for all operations that support retries, you can use the RetryConfig optional parameter when intitializing the SDK:

using Clerk.BackendAPI;
using Clerk.BackendAPI.Models.Operations;

var sdk = new ClerkBackendApi(retryConfig: new RetryConfig(
    strategy: RetryConfig.RetryStrategy.BACKOFF,
    backoff: new BackoffStrategy(
        initialIntervalMs: 1L,
        maxIntervalMs: 50L,
        maxElapsedTimeMs: 100L,
        exponent: 1.1
    ),
    retryConnectionErrors: false
));

GetPublicInterstitialRequest req = new GetPublicInterstitialRequest() {
    FrontendApiQueryParameter = "frontend-api_1a2b3c4d",
    FrontendApiQueryParameter1 = "pub_1a2b3c4d",
};

var res = await sdk.Miscellaneous.GetPublicInterstitialAsync(req);

// handle response

Error Handling

SDKBaseError is the base exception class for all HTTP error responses. It has the following properties:

Property Type Description
Message string Error message
Request HttpRequestMessage HTTP request object
Response HttpResponseMessage HTTP response object

Some exceptions in this SDK include an additional Payload field, which will contain deserialized custom error data when present. Possible exceptions are listed in the Error Classes section.

Example

using Clerk.BackendAPI;
using Clerk.BackendAPI.Models.Components;
using Clerk.BackendAPI.Models.Errors;
using Clerk.BackendAPI.Models.Operations;
using System.Collections.Generic;

var sdk = new ClerkBackendApi(bearerAuth: "<YOUR_BEARER_TOKEN_HERE>");

try
{
    VerifyClientRequestBody req = new VerifyClientRequestBody() {
        Token = "jwt_token_example",
    };

    var res = await sdk.Clients.VerifyAsync(req);

    // handle response
}
catch (SDKBaseError ex)  // all SDK exceptions inherit from SDKBaseError
{
    // ex.ToString() provides a detailed error message
    System.Console.WriteLine(ex);

    // Base exception fields
    HttpRequestMessage request = ex.Request;
    HttpResponseMessage response = ex.Response;
    var statusCode = (int)response.StatusCode;
    var responseBody = ex.Body;

    if (ex is ClerkErrors) // different exceptions may be thrown depending on the method
    {
        // Check error data fields
        ClerkErrorsPayload payload = ex.Payload;
        List<ClerkError> Errors = payload.Errors;
        Clerk.BackendAPI.Models.Errors.Meta Meta = payload.Meta;
    }

    // An underlying cause may be provided
    if (ex.InnerException != null)
    {
        Exception cause = ex.InnerException;
    }
}
catch (System.Net.Http.HttpRequestException ex)
{
    // Check ex.InnerException for Network connectivity errors
}

Error Classes

Primary exceptions:

Less common exceptions (13)

* Refer to the relevant documentation to determine whether an exception applies to a specific operation.

Server Selection

Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:

using Clerk.BackendAPI;
using Clerk.BackendAPI.Models.Operations;

var sdk = new ClerkBackendApi(serverUrl: "https://api.clerk.com/v1");

GetPublicInterstitialRequest req = new GetPublicInterstitialRequest() {
    FrontendApiQueryParameter = "frontend-api_1a2b3c4d",
    FrontendApiQueryParameter1 = "pub_1a2b3c4d",
};

var res = await sdk.Miscellaneous.GetPublicInterstitialAsync(req);

// handle response

Custom HTTP Client

The C# SDK makes API calls using an ISpeakeasyHttpClient that wraps the native HttpClient. This client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The ISpeakeasyHttpClient interface allows you to either use the default SpeakeasyHttpClient that comes with the SDK, or provide your own custom implementation with customized configuration such as custom message handlers, timeouts, connection pooling, and other HTTP client settings.

The following example shows how to create a custom HTTP client with request modification and error handling:

using Clerk.BackendAPI;
using Clerk.BackendAPI.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

// Create a custom HTTP client
public class CustomHttpClient : ISpeakeasyHttpClient
{
    private readonly ISpeakeasyHttpClient _defaultClient;

    public CustomHttpClient()
    {
        _defaultClient = new SpeakeasyHttpClient();
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        // Add custom header and timeout
        request.Headers.Add("x-custom-header", "custom value");
        request.Headers.Add("x-request-timeout", "30");
        
        try
        {
            var response = await _defaultClient.SendAsync(request, cancellationToken);
            // Log successful response
            Console.WriteLine($"Request successful: {response.StatusCode}");
            return response;
        }
        catch (Exception error)
        {
            // Log error
            Console.WriteLine($"Request failed: {error.Message}");
            throw;
        }
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
        _defaultClient?.Dispose();
    }
}

// Use the custom HTTP client with the SDK
var customHttpClient = new CustomHttpClient();
var sdk = new ClerkBackendApi(client: customHttpClient);
You can also provide a completely custom HTTP client with your own configuration:
using Clerk.BackendAPI.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

// Custom HTTP client with custom configuration
public class AdvancedHttpClient : ISpeakeasyHttpClient
{
    private readonly HttpClient _httpClient;

    public AdvancedHttpClient()
    {
        var handler = new HttpClientHandler()
        {
            MaxConnectionsPerServer = 10,
            // ServerCertificateCustomValidationCallback = customCertValidation, // Custom SSL validation if needed
        };

        _httpClient = new HttpClient(handler)
        {
            Timeout = TimeSpan.FromSeconds(30)
        };
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        return await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None);
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}

var sdk = ClerkBackendApi.Builder()
    .WithClient(new AdvancedHttpClient())
    .Build();
For simple debugging, you can enable request/response logging by implementing a custom client:
public class LoggingHttpClient : ISpeakeasyHttpClient
{
    private readonly ISpeakeasyHttpClient _innerClient;

    public LoggingHttpClient(ISpeakeasyHttpClient innerClient = null)
    {
        _innerClient = innerClient ?? new SpeakeasyHttpClient();
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        // Log request
        Console.WriteLine($"Sending {request.Method} request to {request.RequestUri}");
        
        var response = await _innerClient.SendAsync(request, cancellationToken);
        
        // Log response
        Console.WriteLine($"Received {response.StatusCode} response");
        
        return response;
    }

    public void Dispose() => _innerClient?.Dispose();
}

var sdk = new ClerkBackendApi(client: new LoggingHttpClient());

The SDK also provides built-in hook support through the SDKConfiguration.Hooks system, which automatically handles BeforeRequestAsync, AfterSuccessAsync, and AfterErrorAsync hooks for advanced request lifecycle management.

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Languages