### Install Auth0 ASP.NET Core Authentication Package Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/index.html Install the Auth0 ASP.NET Core Authentication SDK using the NuGet Package Manager Console. ```csharp Install-Package Auth0.AspNetCore.Authentication ``` -------------------------------- ### Simplified Auth0 Configuration with SDK Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/MIGRATION.md Simplify Auth0 integration using the Auth0 SDK. This method reduces boilerplate code for authentication setup. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; }); } ``` -------------------------------- ### Configure Services with AddAuth0WebAppAuthentication Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/MIGRATION.md This configuration demonstrates the use of the AddAuth0WebAppAuthentication method, which simplifies the setup and allows direct assignment of OpenIdConnectEvents. ```csharp public void ConfigureServices(IServiceCollection services) { services .AddAuth0WebAppAuthentication(options => { options.OpenIdConnectEvents = new OpenIdConnectEvents { OnTokenValidated = (context) => { return Task.CompletedTask; } }; }); } ``` -------------------------------- ### Basic Auth0 Configuration with OpenIdConnect Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/MIGRATION.md Configure Microsoft's OpenIdConnect middleware for basic Auth0 integration. This setup handles authentication, cookies, and custom logout redirection. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect("Auth0", options => { options.Authority = $"https://{Configuration["Auth0:Domain"]}"; options.ClientId = Configuration["Auth0:ClientId"]; options.CallbackPath = new PathString("/callback"); options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" }; options.Events = new OpenIdConnectEvents { OnRedirectToIdentityProviderForSignOut = (context) => { var logoutUri = $"https://{Configuration["Auth0:Domain"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}"; var postLogoutUri = context.Properties.RedirectUri; if (!string.IsNullOrEmpty(postLogoutUri)) { if (postLogoutUri.StartsWith("/")) { var request = context.Request; postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; } logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; } context.Response.Redirect(logoutUri); context.HandleResponse(); return Task.CompletedTask; } }; }); }); } ``` -------------------------------- ### Custom Logout Token Handler with Distributed Cache Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Implement ILogoutTokenHandler using IDistributedCache for storing and retrieving logout tokens. This example demonstrates integration with a distributed cache like Redis. ```csharp public class CustomDistributedLogoutTokenHandler : ILogoutTokenHandler { private readonly IDistributedCache _cache; public CustomDistributedLogoutTokenHandler(IDistributedCache cache) { _cache = cache; } public async Task OnTokenReceivedAsync(string issuer, string sid, string logoutToken, TimeSpan expiration) { await _cache.SetAsync($"{issuer}|{sid}", Encoding.ASCII.GetBytes(logoutToken), new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = expiration }); } public async Task IsLoggedOutAsync(string issuer, string sid) { var token = await _cache.GetAsync($"{issuer}|{sid}"); return token != null; } } ``` -------------------------------- ### Resolve Auth0 Domain from Subdomain Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Configure Auth0 Web Authentication to resolve the Auth0 domain dynamically based on the subdomain of the incoming request host. For example, 'acme.myapp.com' resolves to 'acme.auth0.com'. ```csharp services.AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; }) .WithCustomDomains(options => { // e.g., "acme.myapp.com" -> "acme.auth0.com" options.DomainResolver = httpContext => { var host = httpContext.Request.Host.Host; var subdomain = host.Split('.')[0]; return Task.FromResult($"{subdomain}.auth0.com"); }; }); ``` -------------------------------- ### Build Project Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/CONTRIBUTING.md Use this command to build the project. ```bash dotnet build ``` -------------------------------- ### Enable Authentication and Authorization in Startup.Configure Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/index.html Ensure that authentication and authorization middleware are enabled in your application's Startup.Configure method. ```csharp ... app.UseAuthentication(); app.UseAuthorization(); ... ``` -------------------------------- ### Implement Login Action Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/README.md Use this method to initiate the login process. It builds authentication properties with a redirect URI and challenges the user with the Auth0 authentication scheme. ```csharp public async Task Login(string returnUrl = "/") { var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithRedirectUri(returnUrl) .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); } ``` -------------------------------- ### Configure Session Store with RedisTicketStore Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Demonstrates how to configure the session store using either a type resolved from the dependency injection container or a pre-constructed instance of RedisTicketStore. ```csharp .WithSessionStore(); ``` ```csharp .WithSessionStore(new RedisTicketStore(cache, dataProtectionProvider)); ``` -------------------------------- ### Configure Logout Extra Parameters Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Use `LogoutAuthenticationPropertiesBuilder` to send parameters to the /v2/logout endpoint when calling `HttpContext.SignOutAsync`. This example shows how to send a parameter without a value. ```csharp var authenticationProperties = new LogoutAuthenticationPropertiesBuilder() .WithParameter("federated") .Build(); await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); ``` -------------------------------- ### Build() Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Returns the configured AuthenticationProperties. ```APIDOC ## Build() ### Description Returns the configured [AuthenticationProperties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties). ### Signature ```csharp public AuthenticationProperties Build() ``` ### Returns [AuthenticationProperties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) The configured [AuthenticationProperties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties). ``` -------------------------------- ### Requesting Access Token for Another Audience Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Use HttpContext.GetAccessTokenAsync with an AccessTokenRequest to get a token for a specific audience and scope. Check for null return to handle cases where no refresh token is available or the refresh fails. ```csharp using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using System.Net.Http; using System.Net.Http.Headers; using Auth0.AspNetCore.Authentication; [Authorize] public async Task CallMessagesApi() { var accessToken = await HttpContext.GetAccessTokenAsync(new AccessTokenRequest { Audience = "https://messages.example.com", Scope = "read:messages" }); if (accessToken == null) { // No refresh token available, or the refresh failed — see "Handling refresh failures" below. return Challenge(); } var request = new HttpRequestMessage(HttpMethod.Get, "https://messages.example.com/api/messages"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await _httpClient.SendAsync(request); return Content(await response.Content.ReadAsStringAsync()); } ``` -------------------------------- ### Configure Services with AddCookie and AddOpenIdConnect Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/MIGRATION.md This configuration uses the AddCookie and AddOpenIdConnect methods for authentication. It shows how to set up event handlers like OnTokenValidated. ```csharp public void ConfigureServices(IServiceCollection services) { services .AddAuthentication(...) .AddCookie() .AddOpenIdConnect("Auth0", options => { options.Events.OnTokenValidated = context => { return Task.CompletedTask; }; }); } ``` -------------------------------- ### Request Access Token for Additional Audience and Scope Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/README.md Obtain an access token for a specific audience and scope using the Multi-Resource Refresh Tokens (MRRT) feature. This allows a single session to get tokens for additional resources without re-authentication. ```csharp var accessToken = await HttpContext.GetAccessTokenAsync(new AccessTokenRequest { Audience = "https://messages.example.com", Scope = "read:messages" }); ``` -------------------------------- ### Initiate Auth0 Login Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs-source/index.md Call this method to initiate the login process. It uses HttpContext to challenge the user with the Auth0 authentication scheme and specifies a return URL. ```csharp public async Task Login(string returnUrl = "/") { var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithRedirectUri(returnUrl) .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); } ``` -------------------------------- ### Build Method Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LogoutAuthenticationPropertiesBuilder.html Finalizes the configuration and returns the constructed AuthenticationProperties object. ```APIDOC ## Build() ### Description Return the configured [AuthenticationProperties](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties). ### Returns [AuthenticationProperties](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) - The configured [AuthenticationProperties](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties). ``` -------------------------------- ### Run Unit Tests Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/CONTRIBUTING.md Execute all unit tests for the project before submitting a pull request. ```bash dotnet test ``` -------------------------------- ### Auth0WebAppOptions Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.html Options used to configure the SDK. ```APIDOC ## Class: Auth0WebAppOptions ### Description Configuration options for the Auth0 ASP.NET Core SDK, allowing customization of various aspects of the authentication process. ### Usage Instances of this class are typically provided during the `AddAuth0WebApp` configuration step. ``` -------------------------------- ### Add Auth0 Web App Authentication Services Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/index.html Configure the Auth0 authentication services in your Startup.ConfigureServices method, providing your Auth0 domain and Client ID. ```csharp services.AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; }); ``` -------------------------------- ### BackchannelLogoutHandler Constructor Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.BackchannelLogout.BackchannelLogoutHandler.html Initializes a new instance of the BackchannelLogoutHandler class. ```APIDOC ## BackchannelLogoutHandler(ILogoutTokenHandler) ### Description Initializes a new instance of the `BackchannelLogoutHandler` class. ### Parameters #### Parameters - **tokenHandler** (ILogoutTokenHandler) - The handler for logout tokens. ``` -------------------------------- ### Domain Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppOptions.html Auth0 domain name, e.g. tenant.auth0.com. ```APIDOC ## Domain ### Description Auth0 domain name, e.g. tenant.auth0.com. ### Property Value [string](https://learn.microsoft.com/dotnet/api/system.string) ``` -------------------------------- ### Accept User Invitation via Authentication Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Handle user invitations by creating a controller action that extracts organization and invitation details from the URL. It then uses these details to initiate the authentication challenge. ```csharp public class InvitationController : Controller { public async Task Accept(string organization, string invitation) { var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithOrganization(organization) .WithInvitation(invitation) .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); } } ``` -------------------------------- ### WithOrganization Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Builds AuthenticationProperties using the provided organization. ```APIDOC ## WithOrganization(string) ### Description Build the [AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) using the provided organization. ### Method Signature `public LoginAuthenticationPropertiesBuilder WithOrganization(string organization)` ### Parameters #### Path Parameters - **organization** (string) - Required - The organization used when logging in. ### Remarks * If you provide an Organization ID (a string with the prefix `org_`), it will be validated against the `org_id` claim of your user's ID Token. The validation is case-sensitive. * If you provide an Organization Name (a string _without_ the prefix `org_`), it will be validated against the `org_name` claim of your user's ID Token. The validation is case-insensitive. ``` -------------------------------- ### Auth0WebAppWithAccessTokenOptions Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.html Options used to configure the SDK when using Access Tokens ```APIDOC ## Class: Auth0WebAppWithAccessTokenOptions ### Description Configuration options specifically for scenarios where the Auth0 ASP.NET Core SDK is used to obtain and manage access tokens. ### Usage These options are applied when configuring authentication for applications that require access tokens for API calls. ``` -------------------------------- ### Implement RedisTicketStore for ITicketStore Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md A minimal IDistributedCache-backed implementation of ITicketStore. It serializes, encrypts, and stores authentication tickets in a distributed cache, honoring ticket expiration. ```csharp public class RedisTicketStore : ITicketStore { private readonly IDistributedCache _cache; private readonly IDataProtector _protector; public RedisTicketStore(IDistributedCache cache, IDataProtectionProvider provider) { _cache = cache; _protector = provider.CreateProtector("Auth0.AspNetCore.Authentication.RedisTicketStore"); } public async Task StoreAsync(AuthenticationTicket ticket) { var key = $"auth-session-{Guid.NewGuid():N}"; await RenewAsync(key, ticket); return key; } public async Task RenewAsync(string key, AuthenticationTicket ticket) { var options = new DistributedCacheEntryOptions { AbsoluteExpiration = ticket.Properties.ExpiresUtc }; var payload = _protector.Protect(TicketSerializer.Default.Serialize(ticket)); await _cache.SetAsync(key, payload, options); } public async Task RetrieveAsync(string key) { var bytes = await _cache.GetAsync(key); return bytes == null ? null : TicketSerializer.Default.Deserialize(_protector.Unprotect(bytes)); } public Task RemoveAsync(string key) => _cache.RemoveAsync(key); } ``` -------------------------------- ### Simplified API Access Token Retrieval with SDK Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/MIGRATION.md Use the Auth0 SDK to simplify obtaining an access token for API calls. This requires specifying the client secret and audience. ```csharp public void ConfigureServices(IServiceCollection services) { services .AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; options.ClientSecret = Configuration["Auth0:ClientSecret"]; }) .WithAccessToken(options => { options.Audience = Configuration["Auth0:Audience"]; }); } ``` -------------------------------- ### Configure Server-Side Session Storage with Redis Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Use `WithSessionStore` to integrate a custom `ITicketStore` implementation, such as `RedisTicketStore`, for server-side session management. This is useful when authentication sessions, including tokens, exceed browser cookie size limits. ```csharp services .AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; options.ClientSecret = Configuration["Auth0:ClientSecret"]; }) .WithAccessToken(options => { options.Audience = Configuration["Auth0:Audience"]; options.UseRefreshTokens = true; }) .WithSessionStore(); ``` -------------------------------- ### Auth0WebAppAuthenticationBuilder Constructors Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppAuthenticationBuilder.html Constructors for initializing the Auth0WebAppAuthenticationBuilder. ```APIDOC ## Auth0WebAppAuthenticationBuilder(IServiceCollection, Auth0WebAppOptions) ### Description Constructs an instance of [Auth0WebAppAuthenticationBuilder] with the specified service collection and options. ### Parameters - **services** (IServiceCollection) - The original IServiceCollection instance. - **options** (Auth0WebAppOptions) - The Auth0WebAppOptions used when calling AddAuth0WebAppAuthentication. ## Auth0WebAppAuthenticationBuilder(IServiceCollection, string, Auth0WebAppOptions) ### Description Constructs an instance of [Auth0WebAppAuthenticationBuilder] with the specified service collection, authentication scheme, and options. ### Parameters - **services** (IServiceCollection) - The original IServiceCollection instance. - **authenticationScheme** (string) - The authentication scheme to use. - **options** (Auth0WebAppOptions) - The Auth0WebAppOptions used when calling AddAuth0WebAppAuthentication. ``` -------------------------------- ### Configure Backchannel Logout Services Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Configure backchannel logout by calling WithBackchannelLogout() when adding Auth0 authentication services. Ensure domain, client ID, and client secret are provided. ```csharp services .AddAuth0WebAppAuthentication(PlaygroundConstants.AuthenticationScheme, options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; options.ClientSecret = Configuration["Auth0:ClientSecret"]; }).WithBackchannelLogout(); ``` -------------------------------- ### Configure Auth0 Settings in appsettings.json Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/index.html Add the Auth0 domain and Client ID to your application's appsettings.json file. These values are obtained from your Auth0 Dashboard. ```json { "Auth0": { "Domain": "YOUR_AUTH0_DOMAIN", "ClientId": "YOUR_AUTH0_CLIENT_ID" } } ``` -------------------------------- ### LoginAuthenticationPropertiesBuilder Constructor Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Initializes a new instance of the LoginAuthenticationPropertiesBuilder class. ```APIDOC ## LoginAuthenticationPropertiesBuilder Constructor ### Description Initializes a new instance of the [LoginAuthenticationPropertiesBuilder](Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html) class. ### Signature ```csharp public LoginAuthenticationPropertiesBuilder(AuthenticationProperties? properties = null) ``` ### Parameters * **properties** ([AuthenticationProperties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties)) - Optional. The initial [AuthenticationProperties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) to use. ``` -------------------------------- ### Restore Nuget Dependencies Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/CONTRIBUTING.md Use this command to restore Nuget dependencies for the project. ```bash dotnet restore ``` -------------------------------- ### WithScope Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Builds AuthenticationProperties using the provided scope. ```APIDOC ## WithScope(string) ### Description Build the [AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) using the provided scope. ### Method Signature `public LoginAuthenticationPropertiesBuilder WithScope(string scope)` ``` -------------------------------- ### Implement Custom IConfigurationManagerCache Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Provides a template for implementing a custom caching strategy by inheriting from IConfigurationManagerCache. This allows for advanced caching solutions, such as distributed caches. ```csharp public class MyCustomConfigurationManagerCache : IConfigurationManagerCache { public IConfigurationManager GetOrCreate( string metadataAddress, Func> factory) { // Return a cached instance or call factory(metadataAddress) to create one } public void Clear() { /* Evict all entries */ } public void Dispose() { /* Clean up resources */ } } // Usage .WithCustomDomains(options => { options.DomainResolver = httpContext => { /* ... */ }; options.ConfigurationManagerCache = new MyCustomConfigurationManagerCache(); }) ``` -------------------------------- ### Auth0WebAppOptions Properties Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppOptions.html The Auth0WebAppOptions class provides several properties to configure the authentication process. These include settings for the callback path, client ID and secret, security keys, backchannel HTTP client, and access denied path. ```APIDOC ## Class Auth0WebAppOptions Namespace [Auth0](Auth0.html).[AspNetCore](Auth0.AspNetCore.html).[Authentication](Auth0.AspNetCore.Authentication.html) Assembly Auth0.AspNetCore.Authentication.dll Options used to configure the SDK public class Auth0WebAppOptions Properties ---------- ### AccessDeniedPath Gets or sets the optional path the user agent is redirected to if the user doesn't approve the authorization demand requested by the remote server. This property is not set by default. In this case, an exception is thrown if an access_denied response is returned by the remote authorization server. public PathString AccessDeniedPath { get; set; } #### Property Value [PathString](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.http.pathstring) ### Backchannel Backchannel used to communicate with the Identity Provider. public HttpClient? Backchannel { get; set; } #### Property Value [HttpClient](https://learn.microsoft.com/dotnet/api/system.net.http.httpclient) ### CallbackPath The path within the application to redirect the user to. public string? CallbackPath { get; set; } #### Property Value [string](https://learn.microsoft.com/dotnet/api/system.string) #### Remarks Processed internally by the Open Id Connect middleware. ### ClientAssertionSecurityKey Security Key to use with Client Assertion public SecurityKey? ClientAssertionSecurityKey { get; set; } #### Property Value [SecurityKey](https://learn.microsoft.com/dotnet/api/microsoft.identitymodel.tokens.securitykey) ### ClientAssertionSecurityKeyAlgorithm Algorithm for the Security Key to use with Client Assertion public string? ClientAssertionSecurityKeyAlgorithm { get; set; } #### Property Value [string](https://learn.microsoft.com/dotnet/api/system.string) ### ClientId Client ID of the application. public string ClientId { get; set; } #### Property Value [string](https://learn.microsoft.com/dotnet/api/system.string) ### ClientSecret Client Secret of the application. public string? ClientSecret { get; set; } #### Property Value [string](https://learn.microsoft.com/dotnet/api/system.string) ``` -------------------------------- ### Implement Login PageModel in Blazor Server Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Create a LoginModel PageModel to handle user redirection to Auth0 for authentication. This allows for custom redirect URIs. ```csharp public class LoginModel : PageModel { public async Task OnGet(string redirectUri) { var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithRedirectUri(redirectUri) .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); } } ``` -------------------------------- ### BaseAuthenticationPropertiesBuilder Constructor Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.BaseAuthenticationPropertiesBuilder.html Initializes a new instance of the BaseAuthenticationPropertiesBuilder class. ```APIDOC ## BaseAuthenticationPropertiesBuilder Constructor ### Description Initializes a new instance of the BaseAuthenticationPropertiesBuilder class. ### Signature ```csharp protected BaseAuthenticationPropertiesBuilder(AuthenticationProperties? properties = null) ``` ### Parameters * **properties** ([AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties)) - Optional. The initial authentication properties. ``` -------------------------------- ### Configure Global Login Extra Parameters Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Set `LoginParameters` globally when adding Auth0 authentication to pass extra parameters to the /authorize endpoint. This is useful for configuring default behaviors like showing the signup page. ```csharp services.AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; options.LoginParameters = new Dictionary() { { "screen_hint", "signup" } }; }); ``` -------------------------------- ### Configure Per-Request Login Extra Parameters Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Use `LoginAuthenticationPropertiesBuilder` to supply extra parameters for a specific login request when calling `HttpContext.ChallengeAsync`. These parameters take precedence over globally configured ones. ```csharp var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithParameter("screen_hint", "signup") .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); ``` -------------------------------- ### WithRedirectUri Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Builds AuthenticationProperties using the provided redirect URI. ```APIDOC ## WithRedirectUri(string) ### Description Build the [AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) using the provided redirect URI. ### Method Signature `public LoginAuthenticationPropertiesBuilder WithRedirectUri(string redirectUri)` ### Parameters #### Path Parameters - **redirectUri** (string) - Required - Full path or absolute URI to be used to redirect back to your application. ### Remarks Defaults to "/" when [WithRedirectUri(string)](Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html#Auth0_AspNetCore_Authentication_LoginAuthenticationPropertiesBuilder_WithRedirectUri_System_String_) is not called while building the [AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties). ``` -------------------------------- ### Configure Auth0 Authentication with Custom Domain Resolver Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/README.md Configure Auth0 Web Authentication with a custom domain resolver to handle multiple custom domains. The resolver can dynamically determine the Auth0 domain based on request headers. ```csharp services.AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; }) .WithCustomDomains(options => { // Example: resolve from a custom header options.DomainResolver = httpContext => { var tenant = httpContext.Request.Headers["X-Tenant-Domain"].FirstOrDefault(); return Task.FromResult(tenant ?? "default-tenant.auth0.com"); }; }); ``` -------------------------------- ### WithParameter Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Builds AuthenticationProperties using a parameter that will be sent to Auth0's Authorize endpoint. ```APIDOC ## WithParameter(string, string) ### Description Build the [AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) using a parameter that will be sent to Auth0's Authorize endpoint. ### Method Signature `public LoginAuthenticationPropertiesBuilder WithParameter(string key, string value)` ### Parameters #### Path Parameters - **key** (string) - Required - The key for the parameter. - **value** (string) - Required - The value for the parameter. ``` -------------------------------- ### WithAccessToken Method Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppAuthenticationBuilder.html Configures the builder to use Access Tokens for authentication. ```APIDOC ## WithAccessToken(Action) ### Description Configures the use of Access Tokens by providing a delegate to configure [Auth0WebAppWithAccessTokenOptions]. ### Parameters - **configureOptions** (Action) - A delegate used to configure the Auth0WebAppWithAccessTokenOptions. ``` -------------------------------- ### Handle MFA Challenge and Verification in ASP.NET Core Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md This snippet shows how to catch `MfaRequiredException`, trigger an MFA challenge, and verify the user's input. It includes handling token expiration and invalid tokens. ```csharp public class ResourceController : Controller { private readonly IAuthenticationApiClient _authClient; public ResourceController(IAuthenticationApiClient authClient) => _authClient = authClient; public async Task CallApi() { try { var accessToken = await HttpContext.GetAccessTokenAsync( new AccessTokenRequest { Audience = "https://my-second-api" }); // ... use accessToken ... return Ok(); } catch (MfaRequiredException ex) { // ex.MfaToken is an opaque, encrypted token valid for 5 minutes. // Inspect ex.MfaRequirements to discover which challenge types are available. var canUseOtp = ex.MfaRequirements?.Challenge? .Any(c => c.Type == "otp") ?? false; // Trigger a challenge (e.g. send an OTP / push). authenticatorId is optional. var challenge = await _authClient.MfaChallengeAsync(new MfaChallengeRequest { MfaToken = ex.MfaToken, ChallengeType = "otp" }); // Store ex.MfaToken (and challenge.OobCode if using OOB) for the verify step, // then prompt the user for their code. The token expires 5 minutes after issue. TempData["mfa_token"] = ex.MfaToken; return RedirectToAction("EnterCode"); } } [HttpPost] public async Task EnterCode(string otp) { var mfaToken = (string)TempData["mfa_token"]!; try { var tokens = await _authClient.GetTokenAsync(new MfaOtpTokenRequest { MfaToken = mfaToken, Otp = otp }); // tokens.AccessToken is now valid for the requested audience. // Persisting these tokens into the session is your responsibility — see below. return Ok(); } catch (MfaTokenExpiredException) { // The 5-minute window elapsed — restart the flow to obtain a fresh token. return RedirectToAction("CallApi"); } catch (MfaTokenInvalidException) { // The token was tampered with or malformed — restart the flow. return RedirectToAction("CallApi"); } } } ``` -------------------------------- ### Auth0WebAppWithAccessTokenAuthenticationBuilder Constructors Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppWithAccessTokenAuthenticationBuilder.html Constructors for the Auth0WebAppWithAccessTokenAuthenticationBuilder class, used to initialize the builder with necessary services and options. ```APIDOC ## Auth0WebAppWithAccessTokenAuthenticationBuilder(IServiceCollection, Action, Auth0WebAppOptions) ### Description Constructs an instance of Auth0WebAppWithAccessTokenAuthenticationBuilder. ### Parameters - **services** (IServiceCollection) - The original IServiceCollection instance - **configureOptions** (Action) - A delegate used to configure the Auth0WebAppWithAccessTokenOptions - **options** (Auth0WebAppOptions) - The Auth0WebAppOptions used when calling AddAuth0WebAppAuthentication. ## Auth0WebAppWithAccessTokenAuthenticationBuilder(IServiceCollection, Action, Auth0WebAppOptions, string) ### Description Constructs an instance of Auth0WebAppWithAccessTokenAuthenticationBuilder. ### Parameters - **services** (IServiceCollection) - The original IServiceCollection instance - **configureOptions** (Action) - A delegate used to configure the Auth0WebAppWithAccessTokenOptions - **options** (Auth0WebAppOptions) - The Auth0WebAppOptions used when calling AddAuth0WebAppAuthentication. - **authenticationScheme** (string) - The authentication scheme to use. ``` -------------------------------- ### DefaultLogoutTokenHandler Constructor Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.BackchannelLogout.DefaultLogoutTokenHandler.html Initializes a new instance of the DefaultLogoutTokenHandler class. ```APIDOC ## DefaultLogoutTokenHandler(IMemoryCache, ILoggerFactory) ### Description Initializes a new instance of the `DefaultLogoutTokenHandler` class. ### Parameters #### Path Parameters - **memoryCache** (IMemoryCache) - Required - The memory cache instance. - **loggerFactory** (ILoggerFactory) - Required - The logger factory instance. ``` -------------------------------- ### Enable Backchannel Logout Middleware Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Enable the backchannel logout middleware by calling UseBackchannelLogout() on the ApplicationBuilder. This should be done after authentication services are configured. ```csharp app.UseBackchannelLogout(); ``` -------------------------------- ### Configure Login Parameters for Auth0 Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppOptions.html Set custom parameters to be sent to Auth0's /authorize endpoint. This is useful for passing additional information during the authentication request. ```csharp services.AddAuth0WebAppAuthentication(options => { options.LoginParameters = new Dictionary() { { "Test", "123" } }; }); ``` -------------------------------- ### Login with Specific Scopes via ChallengeAsync Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Use LoginAuthenticationPropertiesBuilder to specify scopes when initiating the login flow via HttpContext.ChallengeAsync. This overrides global scope settings. ```csharp var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithScope("openid profile scope1 scope2") .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); ``` -------------------------------- ### WithInvitation Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Builds AuthenticationProperties using the provided invitation ID. ```APIDOC ## WithInvitation(string) ### Description Build the [AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) using the provided invitation. ### Method Signature `public LoginAuthenticationPropertiesBuilder WithInvitation(string invitation)` ### Parameters #### Path Parameters - **invitation** (string) - Required - The Id of an invitation to accept. This is available from the URL that is given when participating in a user invitation flow. ``` -------------------------------- ### Configure API Access with Client Secret and Audience Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Configure the Auth0 SDK for API access using the Authorization Code Grant, requiring a ClientSecret. Specify the API's Audience for token requests. ```csharp services .AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; options.ClientSecret = Configuration["Auth0:ClientSecret"]; }) .WithAccessToken(options => { options.Audience = Configuration["Auth0:Audience"]; }); ``` -------------------------------- ### WithBackchannelLogout() Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppAuthenticationBuilder.html Configures the use of Access Tokens for backchannel logout. ```APIDOC ## WithBackchannelLogout() ### Description Configures the use of Access Tokens. ### Method `Auth0WebAppAuthenticationBuilder WithBackchannelLogout()` ### Returns An instance of `Auth0WebAppAuthenticationBuilder`. ``` -------------------------------- ### WithAudience(string) Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Configures the AuthenticationProperties to request API access for a specific audience. ```APIDOC ## WithAudience(string) ### Description Build the [AuthenticationProperties](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) using the provided audience to request API access. ### Signature ```csharp public LoginAuthenticationPropertiesBuilder WithAudience(string audience) ``` ### Parameters * **audience** ([string](https://learn.microsoft.com/en-us/dotnet/api/system.string)) - Required. Audience to request API access for. ### Returns [LoginAuthenticationPropertiesBuilder](Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html) The current [LoginAuthenticationPropertiesBuilder](Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html) instance. ``` -------------------------------- ### Configure Authentication with Custom Scopes Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Configure the Auth0 SDK to request specific scopes during web application authentication. The 'openid' scope is always included. ```csharp services.AddAuth0WebAppAuthentication(options => { options.Domain = Configuration["Auth0:Domain"]; options.ClientId = Configuration["Auth0:ClientId"]; options.Scope = "openid profile scope1 scope2"; }); ``` -------------------------------- ### AuthenticationBuilderExtensions Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.html Contains AuthenticationBuilder extensions for registering Auth0. ```APIDOC ## Class: AuthenticationBuilderExtensions ### Description Provides extension methods for the `IAuthenticationBuilder` interface, simplifying the registration of Auth0 authentication services in ASP.NET Core. ### Usage These extensions are called on the `AuthenticationBuilder` object during application startup to configure Auth0 authentication. ``` -------------------------------- ### Implement Logout Action Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/README.md This method handles user logout. It signs out the user from the Auth0 scheme and the cookie authentication scheme, redirecting them to a specified URL after logout. Ensure the redirect URI is configured in Auth0's Allowed Logout URLs. ```csharp [Authorize] public async Task Logout() { var authenticationProperties = new LogoutAuthenticationPropertiesBuilder() // Indicate here where Auth0 should redirect the user after a logout. // Note that the resulting absolute Uri must be added in the // **Allowed Logout URLs** settings for the client. .WithRedirectUri(Url.Action("Index", "Home")) .Build(); await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } ``` -------------------------------- ### WithRedirectUri Method Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LogoutAuthenticationPropertiesBuilder.html Configures the redirect URI for the logout process. This is the URI the user will be redirected to after logging out. ```APIDOC ## WithRedirectUri(string redirectUri) ### Description Build the [AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties) using the provided redirect URI. ### Method Signature ```csharp public LogoutAuthenticationPropertiesBuilder WithRedirectUri(string redirectUri) ``` ### Parameters #### Path Parameters - **redirectUri** (string) - Required - Full path or absolute URI to be used to redirect back to your application. ### Returns [LogoutAuthenticationPropertiesBuilder](Auth0.AspNetCore.Authentication.LogoutAuthenticationPropertiesBuilder.html) The current [LogoutAuthenticationPropertiesBuilder](Auth0.AspNetCore.Authentication.LogoutAuthenticationPropertiesBuilder.html) instance. ### Remarks Defaults to "/" when [WithRedirectUri(string)](Auth0.AspNetCore.Authentication.LogoutAuthenticationPropertiesBuilder.html#Auth0_AspNetCore_Authentication_LogoutAuthenticationPropertiesBuilder_WithRedirectUri_System_String_) is not called while building the [AuthenticationProperties](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.authentication.authenticationproperties). ``` -------------------------------- ### Configure Default MemoryConfigurationManagerCache Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Configures the default in-memory cache for OpenID Connect configuration managers with specified size and expiration. Use this to adjust caching behavior based on the number of distinct domains or memory constraints. ```csharp .WithCustomDomains(options => { options.DomainResolver = httpContext => { /* ... */ }; options.ConfigurationManagerCache = new MemoryConfigurationManagerCache( maxSize: 100, // Maximum number of domains to cache slidingExpiration: TimeSpan.FromHours(1) // Optional: evict entries not accessed within 1 hour ); }) ``` -------------------------------- ### OpenIdConnectConfigurationKeys Fields Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.OpenIdConnectConfigurationKeys.html The OpenIdConnectConfigurationKeys class contains static string fields representing standard OpenID Connect discovery document keys. ```APIDOC ## Class OpenIdConnectConfigurationKeys Namespace [Auth0](Auth0.html).[AspNetCore](Auth0.AspNetCore.html).[Authentication](Auth0.AspNetCore.Authentication.html) Assembly Auth0.AspNetCore.Authentication.dll public static class OpenIdConnectConfigurationKeys Fields ------ ### BACKCHANNEL_LOGOUT_SESSION_SUPPORTED public static string BACKCHANNEL_LOGOUT_SESSION_SUPPORTED #### Field Value [string](https://learn.microsoft.com/dotnet/api/system.string) ### BACKCHANNEL_LOGOUT_SUPPORTED public static string BACKCHANNEL_LOGOUT_SUPPORTED #### Field Value [string](https://learn.microsoft.com/dotnet/api/system.string) ``` -------------------------------- ### Auth0WebAppAuthenticationBuilder Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.AuthenticationBuilderExtensions.html Configures Auth0 authentication for web applications. Returns the Auth0WebAppAuthenticationBuilder instance for further configuration. ```APIDOC ## Auth0WebAppAuthenticationBuilder ### Description Configures Auth0 authentication for web applications. This method returns an `Auth0WebAppAuthenticationBuilder` instance, which allows for further customization of the authentication setup. ### Returns [Auth0WebAppAuthenticationBuilder](Auth0.AspNetCore.Authentication.Auth0WebAppAuthenticationBuilder.html) - The `Auth0WebAppAuthenticationBuilder` instance that has been configured. ``` -------------------------------- ### WithScope Method Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html Sets the scopes to be used when requesting tokens. ```APIDOC ## WithScope Method ### Description Sets the scopes to be used when requesting tokens. This allows you to specify the permissions your application requires. ### Method Signature `LoginAuthenticationPropertiesBuilder WithScope(string scope)` ### Parameters #### Parameters - **scope** (string) - Required - Scopes to be used to request token(s). (e.g. "Scope1 Scope2 Scope3") ### Returns [LoginAuthenticationPropertiesBuilder](Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html) The current [LoginAuthenticationPropertiesBuilder](Auth0.AspNetCore.Authentication.LoginAuthenticationPropertiesBuilder.html) instance, allowing for method chaining. ``` -------------------------------- ### Auth0WebAppWithAccessTokenEvents Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.html Events allowing you to hook into specific moments in the Auth0 middleware. ```APIDOC ## Class: Auth0WebAppWithAccessTokenEvents ### Description Allows developers to subscribe to and handle specific events that occur during the Auth0 authentication middleware pipeline when using access tokens. ### Usage Used to customize behavior at different stages of the authentication flow, such as before or after token validation. ``` -------------------------------- ### Blueprint for Custom Logout Token Handler Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md A blueprint for implementing the ILogoutTokenHandler interface. This involves storing logout tokens with specific identifiers and checking their validity. ```csharp public class CustomLogoutTokenHandler : ILogoutTokenHandler { public CustomLogoutTokenHandler() { } public Task OnTokenReceivedAsync(string issuer, string sid, string logoutToken, TimeSpan expiration) { // When a token is received, you need to store it for the duration of `expiration`, using `issuer` and `sid` as the identifiers. } public Task IsLoggedOutAsync(string issuer, string sid) { // Return a boolean based on whether or not you find a logout token using the `issuer` and `sid`. } } ``` -------------------------------- ### OnTokenReceivedAsync Method Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.BackchannelLogout.DefaultLogoutTokenHandler.html Handles the reception of a logout token, processing it and storing relevant information. ```APIDOC ## OnTokenReceivedAsync(string, string, string, TimeSpan) ### Description Handles the reception of a logout token, processing it and storing relevant information for future checks. ### Parameters #### Path Parameters - **issuer** (string) - Required - The issuer of the logout token. - **sid** (string) - Required - The session ID associated with the logout token. - **logoutToken** (string) - Required - The logout token string received. - **expiration** (TimeSpan) - Required - The expiration time of the logout token. ### Returns - **Task** - A task that represents the asynchronous operation. ``` -------------------------------- ### Login and Logout in ASP.NET Core Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/index.html Use HttpContext to trigger login and logout flows. For logout, specify the redirect URI and ensure it's added to Auth0's Allowed Logout URLs. ```csharp public async Task Login(string returnUrl = "/") { var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithRedirectUri(returnUrl) .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); } ``` ```csharp [Authorize] public async Task Logout() { var authenticationProperties = new LogoutAuthenticationPropertiesBuilder() // Indicate here where Auth0 should redirect the user after a logout. // Note that the resulting absolute Uri must be added in the // **Allowed Logout URLs** settings for the client. .WithRedirectUri(Url.Action("Index", "Home")) .Build(); await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } ``` -------------------------------- ### Auth0WebAppAuthenticationBuilder Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.html Builder to add functionality on top of OpenId Connect authentication. ```APIDOC ## Class: Auth0WebAppAuthenticationBuilder ### Description Provides a fluent API for configuring Auth0 authentication services within an ASP.NET Core application, extending the base OpenId Connect authentication builder. ### Usage This builder is used during application startup to customize Auth0 authentication settings. ``` -------------------------------- ### LoginParameters Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppOptions.html Parameters to be sent to Auth0's /authorize endpoint. ```APIDOC ## LoginParameters ### Description Parameters to be send to Auth0's `/authorize` endpoint. ### Property Value [IDictionary](https://learn.microsoft.com/dotnet/api/system.collections.generic.idictionary-2)<[string](https://learn.microsoft.com/dotnet/api/system.string), [string](https://learn.microsoft.com/dotnet/api/system.string)>? ### Examples ```csharp services.AddAuth0WebAppAuthentication(options => { options.LoginParameters = new Dictionary() { { "Test", "123" } }; }); ``` ``` -------------------------------- ### ErrorApiException Constructors Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Exceptions.ErrorApiException.html Provides information about the constructors available for the ErrorApiException class. ```APIDOC ## ErrorApiException() ### Description Initializes a new instance of the ErrorApiException class. ### Method `public ErrorApiException()` ## ErrorApiException(HttpStatusCode, ApiError?) ### Description Initializes a new instance of the ApiException class with a specified `statusCode` and optional `apiError`. ### Method `public ErrorApiException(HttpStatusCode statusCode, ApiError? apiError = null)` ### Parameters #### Path Parameters - **statusCode** (HttpStatusCode) - Required - HttpStatusCode code of the failing API call. - **apiError** (ApiError) - Optional - ApiError of the failing API call. ``` -------------------------------- ### AddAuth0WebAppWithAccessToken Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppWithAccessTokenAuthenticationBuilder.html Adds Auth0 authentication services to the application with support for access tokens. This method configures the necessary services for integrating Auth0 authentication, including options for managing access tokens. ```APIDOC ## AddAuth0WebAppWithAccessToken ### Description Adds Auth0 authentication services to the application with support for access tokens. This method configures the necessary services for integrating Auth0 authentication, including options for managing access tokens. ### Method Signature `public static IServiceCollection AddAuth0WebAppWithAccessToken(this IServiceCollection services, Action configureOptions, string authenticationScheme = "Cookies")` ### Parameters #### services - `IServiceCollection` - The original `IServiceCollection` instance. #### configureOptions - `Action` - A delegate used to configure the `Auth0WebAppWithAccessTokenOptions`. #### authenticationScheme - `string` - The authentication scheme to use. Defaults to "Cookies". ``` -------------------------------- ### Implement Logout PageModel in Blazor Server Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Create a LogoutModel PageModel to handle user sign-out from Auth0 and the application. It redirects the user to the root path after logout. ```csharp [Authorize] public class LogoutModel : PageModel { public async Task OnGet() { var authenticationProperties = new LogoutAuthenticationPropertiesBuilder() .WithRedirectUri("/") .Build(); await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } } ``` -------------------------------- ### AddAuth0WebAppAuthentication(AuthenticationBuilder, Action) Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.AuthenticationBuilderExtensions.html Adds Auth0 configuration to the application using OpenID Connect. This overload uses the default authentication scheme. ```APIDOC ## AddAuth0WebAppAuthentication(AuthenticationBuilder, Action) ### Description Adds Auth0 configuration using Open ID Connect. This method configures the authentication builder with default settings for Auth0 web application authentication. ### Method `public static Auth0WebAppAuthenticationBuilder AddAuth0WebAppAuthentication(this AuthenticationBuilder builder, Action configureOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `builder` (AuthenticationBuilder) - The original AuthenticationBuilder instance. - `configureOptions` (Action) - A delegate used to configure the Auth0WebAppOptions. ### Returns Auth0WebAppAuthenticationBuilder - The AuthenticationBuilder instance that has been configured. ``` -------------------------------- ### SignOutScheme Property Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/docs/api/Auth0.AspNetCore.Authentication.Auth0WebAppOptions.html Specifies the authentication scheme to be used with SignOut on the SignOutPath. Falls back to SignInScheme if not set. ```APIDOC ## SignOutScheme ### Description The Authentication Scheme to use with SignOut on the SignOutPath. SignInScheme will be used if this is not set. ### Property Value `string?` ``` -------------------------------- ### Log in to a Specific Organization Source: https://github.com/auth0/auth0-aspnetcore-authentication/blob/main/EXAMPLES.md Initiate the login process for a specific organization using `LoginAuthenticationPropertiesBuilder`. This method allows overriding the globally configured organization for a single login request. ```csharp var authenticationProperties = new LoginAuthenticationPropertiesBuilder() .WithOrganization("YOUR_ORGANIZATION_ID_OR_NAME") .Build(); await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties); ```