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 5 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
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,8 @@
using System;
using System.Threading.Tasks;
using Auth0.AspNetCore.Authentication.BackchannelLogout;
using Auth0.AspNetCore.Authentication.ClientInitiatedBackChannelAuthentication;
using Auth0.AuthenticationApi;

namespace Auth0.AspNetCore.Authentication
{
Expand Down Expand Up @@ -61,6 +63,28 @@ 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.AddScoped<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,119 @@
using System;
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;

public Auth0CibaService(
IAuthenticationApiClient authenticationApiClient,
IOptions<Auth0WebAppOptions> optionsAccessor,
ILogger<Auth0CibaService> logger)
{
_authenticationApiClient = authenticationApiClient;
_options = optionsAccessor.Value;
_logger = logger;
}

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;
}
}

public async Task<CibaCompletionDetails> PollForTokensAsync(CibaInitiationDetails initDetails)
{
var request = new ClientInitiatedBackchannelAuthorizationTokenRequest()
{
ClientId = _options.ClientId,
ClientSecret = _options.ClientSecret,
ClientAssertionSecurityKey = _options.ClientAssertionSecurityKey,
ClientAssertionSecurityKeyAlgorithm = _options.ClientAssertionSecurityKeyAlgorithm,
AuthRequestId = initDetails.AuthRequestId
};

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

return new CibaCompletionDetails
{
AccessToken = response.AccessToken,
IdToken = response.IdToken,
TokenType = response.TokenType,
Scope = response.Scope,
ExpiresIn = response.ExpiresIn,
RefreshToken = response.RefreshToken,
IsSuccessful = true,
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 ?? 5));
continue;
}

return new CibaCompletionDetails
{
IsAuthenticationPending = false,
Error = ex.ApiError.Error,
ErrorMessage = ex.ApiError.Message,
IsSuccessful = false
};
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Naive question: 🙂 Is this safe?
I'm always scared by while (true) 🙂 It doesn't explicitly communicate the termination criteria.
I suggest something like the following, but feel free to ignore my comment:

Suggested change
while (true)
{
_logger.LogDebug($"Polling CIBA token endpoint for auth_req_id: {initDetails.AuthRequestId} ");
try
{
var response = await _authenticationApiClient.GetTokenAsync(request);
return new CibaCompletionDetails
{
AccessToken = response.AccessToken,
IdToken = response.IdToken,
TokenType = response.TokenType,
Scope = response.Scope,
ExpiresIn = response.ExpiresIn,
RefreshToken = response.RefreshToken,
IsSuccessful = true,
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 ?? 5));
continue;
}
return new CibaCompletionDetails
{
IsAuthenticationPending = false,
Error = ex.ApiError.Error,
ErrorMessage = ex.ApiError.Message,
IsSuccessful = false
};
}
}
var cibaCompletionDetails = new CibaCompletionDetails
{
IsSuccessful = false,
IsAuthenticationPending = true,
};
while (!cibaCompletionDetails.IsSuccessful && cibaCompletionDetails.IsAuthenticationPending)
{
_logger.LogDebug($"Polling CIBA token endpoint for auth_req_id: {initDetails.AuthRequestId} ");
try
{
var response = await _authenticationApiClient.GetTokenAsync(request);
cibaCompletionDetails.AccessToken = response.AccessToken;
cibaCompletionDetails.IdToken = response.IdToken;
cibaCompletionDetails.TokenType = response.TokenType;
cibaCompletionDetails.Scope = response.Scope;
cibaCompletionDetails.ExpiresIn = response.ExpiresIn;
cibaCompletionDetails.RefreshToken = response.RefreshToken;
cibaCompletionDetails.IsSuccessful = true;
cibaCompletionDetails.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 ?? 5));
continue;
}
cibaCompletionDetails.IsAuthenticationPending = false;
cibaCompletionDetails.Error = ex.ApiError.Error;
cibaCompletionDetails.ErrorMessage = ex.ApiError.Message;
cibaCompletionDetails.IsSuccessful = false;
}
}
return cibaCompletionDetails;

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System.Collections.Generic;
using System.Threading.Tasks;

using Auth0.AuthenticationApi.Models.Ciba;

namespace Auth0.AspNetCore.Authentication.ClientInitiatedBackChannelAuthentication;

public class CibaInitiationDetails
{
public string? AuthRequestId { get; init; }
public int ExpiresIn { get; init; }
public int? Interval { get; init; }
public bool IsSuccessful { get; init; } = true;
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>
/// <returns>Details about the CIBA completion status or the retrieved tokens.</returns>
Task<CibaCompletionDetails> PollForTokensAsync(CibaInitiationDetails cibaInitiationDetails);
}
Loading
Loading