Skip to content

Adding Auth0.AuthenticationApi package dependency #148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
- [Roles](#roles)
- [Backchannel Logout](#backchannel-logout)
- [Blazor Server](#blazor-server)
- [Accessing Auth0.AuthenticationApi features](#accessing-auth0authenticationapi-features)
- [Accessing specific features like CIBA](#accessing-specific-features-like-ciba)

## Login and Logout
Triggering login or logout is done using ASP.NET's `HttpContext`:
Expand Down Expand Up @@ -444,3 +446,97 @@ public class LogoutModel : PageModel
}
}
```

## Accessing Auth0.AuthenticationApi features
`Auth0.AuthenticationApi` package is our standalone Authentication package that supports a wide range of
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`Auth0.AuthenticationApi` package is our standalone Authentication package that supports a wide range of
`Auth0.AuthenticationApi` package is our standalone Authentication package that supports a wide range of

options for Authentication. For example, you can use it to implement the [client credentials flow](https://auth0.com/docs/get-started/authentication-and-authorization-flow/client-credentials-flow), as shown below :

```csharp
/// Register the dependency in the container as below.
/// Program.cs / Startup.cs
builder.Services.AddAuth0WebAppAuthentication(options =>
{
options.Domain = "domain";
options.ClientId = "ClientId";
options.ClientSecret = "clientSecret";
}).WithAuthenticationApiClient();


/// Accessing the Api Client in the controller
public AccountController(IAuthenticationApiClient apiClient)
{
_apiClient = apiClient;
}

[Authorize]
public async Task LoginWithAuthenticationApi()
{
await _apiClient.GetTokenAsync(new ClientCredentialsTokenRequest()
{
ClientId = "",
ClientSecret = ""
}, new CancellationToken());
}
```

## Accessing specific features like CIBA
Although `Auth0.AuthenticationApi` package has a wide range of options for Authentication.
We can access the CIBA feature as below. It aims to make it easy to integrate into an appllication.

```csharp
/// Register the dependency in the container as below.
/// Program.cs / Startup.cs
builder.Services.AddAuth0WebAppAuthentication(options =>
{
options.Domain = "domain"; // required
options.ClientId = "ClientId"; // required
options.ClientSecret = "clientSecret"; // required
}).WithClientInitiatedBackchannelAuthentication();


/// Accessing the Auth0CibaService in the controller
public AccountController(IAuth0CibaService auth0CibaService)
{
_auth0CibaService = auth0CibaService;
}

public async Task<IActionResult> InitiateLoginWithCiba(string returnUrl = "/")
{
var response = await _auth0CibaService.InitiateAuthenticationAsync(new CibaInitiationRequest()
{
Scope = "openid profile",
BindingMessage = "BindingMessage",
LoginHint = new LoginHint()
{
Format = "iss_sub",
Issuer = "https://your-domain/",
Subject = "userId"
}
});

// Cache the details for polling.
TempData["AuthRequestId"] = response.AuthRequestId;
TempData["CibaInitiationDetails"] = JsonSerializer.Serialize(response);
return RedirectToAction("Waiting");
}

// You could use the built-in polling mechanism or could implement your own polling mechanism by
// accessing the `GetTokenAsync` method using the AuthenticationApiClient as shown in the example before.
[HttpGet]
public async Task<IActionResult> CheckCibaStatus()
{
var cibaInitiateResponse = JsonSerializer.Deserialize<CibaInitiationDetails>(TempData["CibaInitiationDetails"]?.ToString() ?? string.Empty);
var authRequestId = cibaInitiateResponse?.AuthRequestId;
if (string.IsNullOrEmpty(authRequestId))
{
return Json(new { isError = true });
}

var status = await _auth0CibaService.PollForTokensAsync(cibaInitiateResponse);

if (status.IsSuccessful)
{
// Parse the accessToken / IdToken and use it as required.
}
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Auth0.AuthenticationApi" Version="7.*" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.*" Condition="'$(TargetFramework)' == 'net6.0'" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="6.*" Condition="'$(TargetFramework)' == 'net6.0'" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="7.0.*" Condition="'$(TargetFramework)' == 'net7.0'" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
using System;
using System.Threading.Tasks;
using Auth0.AspNetCore.Authentication.BackchannelLogout;
using Auth0.AspNetCore.Authentication.ClientInitiatedBackChannelAuthentication;
using Auth0.AuthenticationApi;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Auth0.AspNetCore.Authentication
{
Expand Down Expand Up @@ -61,6 +64,31 @@ public Auth0WebAppAuthenticationBuilder WithBackchannelLogout()
return this;
}

/// <summary>
/// Configures the IAuthenticationApiClient to leverage Auth0.AuthenticationApi
/// </summary>
/// <returns></returns>
public Auth0WebAppAuthenticationBuilder WithAuthenticationApiClient()
{
_services.AddSingleton<IAuthenticationApiClient>(
_ => new AuthenticationApiClient(new Uri($"https://{_options.Domain}")));
_services.AddTransient<ILogoutTokenHandler, DefaultLogoutTokenHandler>();
return this;
}

/// <summary>
/// Configures the IAuth0CibaService to leverage the CIBA features.
/// </summary>
/// <returns></returns>
public Auth0WebAppAuthenticationBuilder WithClientInitiatedBackchannelAuthentication()
{
_services.TryAddSingleton<IAuthenticationApiClient>(
_ => new AuthenticationApiClient(new Uri($"https://{_options.Domain}")));
_services.TryAddScoped<IAuth0CibaService, Auth0CibaService>();

return this;
}

private void EnableWithAccessToken(Action<Auth0WebAppWithAccessTokenOptions> configureOptions)
{
var auth0WithAccessTokensOptions = new Auth0WebAppWithAccessTokenOptions();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
using System;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

using Auth0.AuthenticationApi;
using Auth0.AuthenticationApi.Models.Ciba;
using Auth0.Core.Exceptions;

namespace Auth0.AspNetCore.Authentication.ClientInitiatedBackChannelAuthentication;

internal class Auth0CibaService : IAuth0CibaService
{
private readonly IAuthenticationApiClient _authenticationApiClient;
private readonly Auth0WebAppOptions _options;
private readonly ILogger<Auth0CibaService> _logger;

/// <summary>
/// Initiates an instance of Auth0CibaService which can be used to execute the CIBA workflow.
/// </summary>
/// <param name="authenticationApiClient">Instance of <see cref="Auth0.AuthenticationApi.IAuthenticationApiClient"/> </param>
/// <param name="optionsAccessor"><see cref="Auth0WebAppOptions"/></param>
/// <param name="logger"></param>
public Auth0CibaService(
IAuthenticationApiClient authenticationApiClient,
IOptions<Auth0WebAppOptions> optionsAccessor,
ILogger<Auth0CibaService> logger)
{
_authenticationApiClient = authenticationApiClient;
_options = optionsAccessor.Value;
_logger = logger;
}

/// <inheritdoc cref="Auth0.AspNetCore.Authentication.ClientInitiatedBackChannelAuthentication.IAuth0CibaService.InitiateAuthenticationAsync"/>
public async Task<CibaInitiationDetails> InitiateAuthenticationAsync(
CibaInitiationRequest request)
{
try
{
var cibaRequest = new ClientInitiatedBackchannelAuthorizationRequest
{
ClientId = _options.ClientId,
ClientSecret = _options.ClientSecret,
ClientAssertionSecurityKey = _options.ClientAssertionSecurityKey,
ClientAssertionSecurityKeyAlgorithm = _options.ClientAssertionSecurityKeyAlgorithm,
Audience = request.Audience,
LoginHint = request.LoginHint,
Scope = request.Scope,
RequestExpiry = request.RequestExpiry,
AdditionalProperties = request.AdditionalProperties,
BindingMessage = request.BindingMessage,
};

_logger.LogInformation("Initiating CIBA request!");
var response = await _authenticationApiClient.ClientInitiatedBackchannelAuthorization(cibaRequest);

return new CibaInitiationDetails()
{
AuthRequestId = response.AuthRequestId,
ExpiresIn = response.ExpiresIn,
Interval = response.Interval,
IsSuccessful = true,
ErrorMessage = null
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initiating CIBA request");
throw;
}
}

/// <inheritdoc cref="Auth0.AspNetCore.Authentication.ClientInitiatedBackChannelAuthentication.IAuth0CibaService.PollForTokensAsync"/>
public async Task<CibaCompletionDetails> PollForTokensAsync(
CibaInitiationDetails initDetails, CancellationToken cancellationToken)
{
var request = new ClientInitiatedBackchannelAuthorizationTokenRequest()
{
ClientId = _options.ClientId,
ClientSecret = _options.ClientSecret,
ClientAssertionSecurityKey = _options.ClientAssertionSecurityKey,
ClientAssertionSecurityKeyAlgorithm = _options.ClientAssertionSecurityKeyAlgorithm,
AuthRequestId = initDetails.AuthRequestId
};

var completionDetails = new CibaCompletionDetails()
{
IsSuccessful = false,
IsAuthenticationPending = true
};

while (completionDetails is { IsAuthenticationPending: true, IsSuccessful: false })
{
_logger.LogDebug($"Polling CIBA token endpoint for auth_req_id: {initDetails.AuthRequestId} ");
try
{
var response = await _authenticationApiClient.GetTokenAsync(request, cancellationToken);

completionDetails.AccessToken = response.AccessToken;
completionDetails.IdToken = response.IdToken;
completionDetails.TokenType = response.TokenType;
completionDetails.Scope = response.Scope;
completionDetails.ExpiresIn = response.ExpiresIn;
completionDetails.RefreshToken = response.RefreshToken;
completionDetails.IsSuccessful = true;
completionDetails.IsAuthenticationPending = false;
}
catch (ErrorApiException ex)
{
_logger.LogWarning(
ex,
$"CIBA polling error for auth_req_id: {initDetails.AuthRequestId}." +
$" Error: {ex.ApiError.Error}, Description: {ex.ApiError.Message}");

if (ex.ApiError.Error.Contains("authorization_pending", StringComparison.OrdinalIgnoreCase))
{
await Task.Delay(TimeSpan.FromSeconds(initDetails.Interval));
continue;
}

completionDetails.IsAuthenticationPending = false;
completionDetails.Error = ex.ApiError.Error;
completionDetails.ErrorMessage = ex.ApiError.Message;
completionDetails.IsSuccessful = false;
}
}
return completionDetails;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using Auth0.AuthenticationApi.Models.Ciba;

namespace Auth0.AspNetCore.Authentication.ClientInitiatedBackChannelAuthentication;

public class CibaInitiationDetails : ClientInitiatedBackchannelAuthorizationResponse
{
/// <summary>
/// Indicates whether the polling was successful.
/// </summary>
public bool IsSuccessful { get; init; } = true;

/// <summary>
/// Indicates any errors that occurred during the initiation of the CIBA request.
/// </summary>
public string? ErrorMessage { get; init; }
}

public class CibaInitiationRequest
{
/// <inheritdoc cref="Auth0.AuthenticationApi.Models.Ciba.ClientInitiatedBackchannelAuthorizationRequest.BindingMessage"/>
public string? BindingMessage { get; set; }

/// <inheritdoc cref="Auth0.AuthenticationApi.Models.Ciba.LoginHint"/>
public LoginHint? LoginHint { get; set; }

/// <inheritdoc cref="Auth0.AuthenticationApi.Models.Ciba.ClientInitiatedBackchannelAuthorizationRequest.Scope"/>
public string? Scope { get; set; }

/// <inheritdoc cref="Auth0.AuthenticationApi.Models.Ciba.ClientInitiatedBackchannelAuthorizationRequest.Audience"/>
public string? Audience { get; set; }

/// <inheritdoc cref="Auth0.AuthenticationApi.Models.Ciba.ClientInitiatedBackchannelAuthorizationRequest.RequestExpiry"/>
public int? RequestExpiry { get; set; }

/// <inheritdoc cref="Auth0.AuthenticationApi.Models.Ciba.ClientInitiatedBackchannelAuthorizationRequest.AdditionalProperties"/>
public IDictionary<string, string> AdditionalProperties { get; set; } = new Dictionary<string, string>();
}

public class CibaCompletionDetails : ClientInitiatedBackchannelAuthorizationTokenResponse
{
/// <summary>
/// Signifies if the authentication is pending.
/// </summary>
public bool IsAuthenticationPending { get; set; } = true;

/// <summary>
/// Signifies if the authentication is successful.
/// </summary>
public bool IsSuccessful { get; set; } = false;

/// <summary>
/// The error received in case of expiry or consent rejection
/// </summary>
public string? Error { get; set; }

/// <summary>
/// The error message received in case of expiry or consent rejection
/// </summary>
public string? ErrorMessage { get; set; }
}

public interface IAuth0CibaService
{
/// <summary>
/// Initiates a Client-Initiated Backchannel Authentication (CIBA) flow.
/// </summary>
/// <param name="request">Contains the information required for initiating the CIBA request.</param>
Task<CibaInitiationDetails> InitiateAuthenticationAsync(CibaInitiationRequest request);

/// <summary>
/// Polls the token endpoint to check the status of a CIBA request and retrieve tokens upon completion.
/// </summary>
/// <param name="cibaInitiationDetails">The information required to poll for the CIBA status.</param>
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
/// <returns>Details about the CIBA completion status or the retrieved tokens.</returns>
Task<CibaCompletionDetails> PollForTokensAsync(CibaInitiationDetails cibaInitiationDetails, CancellationToken cancellationToken = default);
}
Loading
Loading