Skip to content

Repository files navigation

C# SDK for Auth0 MyAccount

NuGet NuGet Downloads License

📚 Documentation • 🚀 Getting Started • 💻 Usage • 💬 Feedback


The Auth0 My Account API SDK for C# provides convenient access to the Auth0 My Account API. The My Account API lets an authenticated end user manage their own account - enrolling and managing authentication methods (factors) and linking external identity providers as connected accounts. All operations run in the context of the signed-in user's access token.

Documentation

  • Examples - code samples for every operation and SDK feature.
  • Docs site - explore our docs site and learn more about Auth0.
  • API Reference - complete API reference documentation.

Getting Started

Requirements

This library supports the following targets:

  • .NET 8.0+
  • .NET Standard 2.0+
  • .NET Framework 4.6.2+

Installation

The SDK is available on NuGet and can be installed via the CLI or Package Manager Console:

dotnet add package Auth0.MyAccountApi

Prerequisites

  • An Auth0 account (sign up for free).
  • An application configured to request an access token for the My Account API audience (https://{yourDomain}/me/), with the scopes matching the operations you intend to call (for example read:me:authentication_methods, create:me:authentication_methods, delete:me:connected_accounts).
  • A signed-in end user. Every My Account API call is made on behalf of that user, using their access token - not a machine-to-machine token.

Your First Request

The recommended entry point is MyAccountClient, which wraps the low-level MyAccountApiClient and resolves the user's token on each request through an ITokenProvider:

using Auth0.MyAccountApi;

var client = new MyAccountClient(new MyAccountClientOptions
{
    Domain = "<YOUR_AUTH0_DOMAIN>", // e.g. "your-tenant.auth0.com"
    TokenProvider = new DelegateTokenProvider(
        async cancellationToken => await GetCurrentUserAccessTokenAsync(cancellationToken)
    )
});

var methods = await client.AuthenticationMethods.ListAsync(
    new ListAuthenticationMethodsRequestParameters()
);

foreach (var method in methods.AuthenticationMethods)
{
    Console.WriteLine(method.Type);
}

Note The Base URL is constructed automatically as https://{Domain}/me/v1. The domain must not include a scheme prefix or a path/trailing slash - use "your-tenant.auth0.com", not "https://your-tenant.auth0.com" or "your-tenant.auth0.com/". An ArgumentException is thrown if an invalid domain value is detected.

Exploring the Client

The client exposes the My Account API through strongly-typed sub-clients:

Resource Description Examples
client.Factors List factors enabled for the tenant and available for enrollment. Factors
client.AuthenticationMethods List, enrol, verify, update, and delete the user's authentication methods. Authentication Methods
client.ConnectedAccounts Link, complete, list, and delete accounts connected to external identity providers. Connected Accounts
client.ConnectedAccounts.Connections List connections available for account linking. Discovering available connections

Usage

Full code samples for everything below live in EXAMPLES.md. This section summarises the concepts and links to the matching example.

Authentication

The SDK obtains the end user's access token through an ITokenProvider. The provider is invoked on every request, so you remain in control of how the token is obtained, cached, and refreshed. DelegateTokenProvider covers most cases; implement ITokenProvider yourself for custom token-lifecycle logic.

Because the token is resolved per request, a single MyAccountClient can be registered as a singleton and still act on behalf of whichever user is making the current request.

Scenario Example
Supply the token from your own session, cache, or store Custom Token Source
Custom token-lifecycle logic Implementing ITokenProvider
You already hold a bearer token Static Token
Register the client in DI and read the token off the current request ASP.NET Core Integration

Working With Factors and Authentication Methods

client.Factors.ListAsync reports which factors the tenant has enabled and whether each can be used as a primary or secondary method - check this before offering enrollment. See Listing Available Factors.

client.AuthenticationMethods.ListAsync returns the signed-in user's methods, optionally filtered by factor type. Each AuthenticationMethod is a discriminated union over the supported factor types: use Visit/Match to handle every case exhaustively, or the Is* / TryAs* members when you only care about one type. See Listing Authentication Methods and Working With the AuthenticationMethod Union.

Enrollment is always a two-step flow - CreateAsync starts it and returns an Id plus an AuthSession, then VerifyAsync confirms it with whatever proof the factor requires. The CreateAsync response is a discriminated union whose variant depends on the factor:

Factor Create response accessor Verify payload Example
Email AsMfaBaseCreationResponse() VerifyEmailAuthenticationMethod Email
Phone AsMfaBaseCreationResponse() VerifyPhoneAuthenticationMethod Phone
Push notification AsMfaBaseCreationResponse() VerifyPushNotificationAuthenticationMethod -
TOTP AsQrCodeCreationResponse() VerifyTotpAuthenticationMethod TOTP
Recovery code AsRecoveryCodeCreationResponse() VerifyRecoveryCodeAuthenticationMethod Recovery Code
Password AsPasswordCreationResponse() VerifyPasswordAuthenticationMethod Changing a Password
Passkey AsPasskeyCreationResponse() VerifyPasskeyAuthenticationMethod Passkeys and WebAuthn

CreateAuthenticationMethodRequestContent models the seven factor types above. The create response can additionally surface AsWebAuthnCreationResponse(), verified with VerifyWebAuthnPlatformAuthenticationMethod or VerifyWebAuthnRoamingAuthenticationMethod; WebAuthn platform and roaming methods otherwise appear on list and get responses as AsWebauthnPlatform() / AsWebauthnRoaming().

Existing methods can be retrieved, renamed (or switched between SMS and voice), and deleted - see Managing Existing Authentication Methods.

Connected Accounts

Linking an external identity provider is a two-step, redirect-based flow: CreateAsync returns a connect URI and ticket to redirect the user to, and CompleteAsync exchanges the connect code from your callback. The RedirectUri must match across both steps, and the CodeVerifier must match the CodeChallenge sent in step 1.

Task Example
Start the link flow 1. Start the link flow
Complete the link flow 2. Complete the link flow
List and remove connected accounts Listing and removing
Filter by one or many connections Filtering by connection
Find out which connections the user can link Discovering available connections

Pagination

The connected-accounts list endpoints are cursor-paginated and return a Pager<T>, which implements IAsyncEnumerable<T> - await foreach over it and the SDK fetches subsequent pages transparently. You can also iterate AsPagesAsync() a page at a time, or drive the cursor manually via CurrentPage, HasNextPage, and GetNextPageAsync(). See Pagination.

Note Take accepts values from 1 to 20 and defaults to 10. client.AuthenticationMethods.ListAsync and client.Factors.ListAsync are not paginated - they return the full collection.

Configuration

Options can be configured at the client level (affecting all requests) or per request. See Request Options for a worked example, and the dedicated examples for Retries, Timeouts, Base URL, Cancellation, and HttpClient Lifetime.

Client options (MyAccountClientOptions):

Option Description
TokenProvider Required. Supplies the end user's access token on every request.
Domain Auth0 tenant domain (e.g. "your-tenant.auth0.com"); used to construct the base URL as https://{Domain}/me/v1
BaseUrl Override the base URL directly; takes precedence over Domain
HttpClient Provide a custom HttpClient
AdditionalHeaders Additional HTTP headers sent with every request
MaxRetries Maximum retry attempts (default 2)
Timeout Request timeout (default 30 seconds)

Per-request options (RequestOptions):

Option Description
MaxRetries Maximum retry attempts for this request
Timeout Request timeout
AdditionalHeaders Additional HTTP headers to send
AdditionalQueryParameters Additional query parameters to append
AdditionalBodyProperties Additional JSON body properties
BaseUrl Override the base URL for this request
HttpClient Override the HttpClient for this request

Requests are retried automatically with exponential backoff and jitter on 408, 429, and 5XX responses. The Retry-After and X-RateLimit-Reset headers are respected when present, and the delay is capped at 60 seconds.

Telemetry

The SDK sends an Auth0-Client header on every request containing the SDK name (MyAccount.NET), version, and .NET runtime target (base64-encoded JSON). The header is injected automatically and requires no configuration. It carries no tokens or personal data. See Telemetry to opt out.

Error Handling

When the API returns a non-success status code (4xx or 5xx), the SDK throws a typed subclass of MyAccountApiException. Each subclass exposes a strongly-typed ErrorResponse body, so validation failures can be surfaced field by field - see Error Handling.

Type Status Code Description
BadRequestError 400 Invalid request
UnauthorizedError 401 Token missing, invalid, or expired
ForbiddenError 403 Insufficient scope
NotFoundError 404 Resource not found
UnsupportedMediaTypeError 415 Unsupported request content type
TooManyRequestsError 429 Rate limit exceeded

All of the above derive from MyAccountApiException, which in turn derives from MyAccountException - the base type for every exception this SDK raises.

ErrorResponse exposes Type, Status, Title, Detail, and an optional ValidationErrors collection, where each ValidationError carries Detail, Field, Pointer, and Source.

Raw Responses

Use .WithRawResponse() to access the status code, URL, and headers alongside the parsed response data. See Raw Responses.

Explicit Null Values

By default, fields with null values are omitted from the request. Query parameters modelled as Optional<T?> let you distinguish "omit this parameter" from "send it explicitly as null" - for example to opt out of the default Take = 10. Assigning a value directly also works; an implicit conversion wraps it for you. See Explicit Null Values.

Forward Compatible Enums

This SDK uses forward-compatible enums that handle unknown values gracefully, so new server-side values won't break your code. Use FromCustom for values the SDK doesn't know about, and switch on .Value with a default branch. See Forward Compatible Enums.

API Reference

The full API reference is available in reference.md.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the contributing guidelines.

While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!

Raise an Issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform.
To learn more check out Why Auth0?

Copyright 2026 Okta, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

About

Repository for MyAccountAPI .NET SDK

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages