-
Notifications
You must be signed in to change notification settings - Fork 39
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
base: main
Are you sure you want to change the base?
Changes from 7 commits
7cfda3a
fb4ec7e
ac8f7f0
414fd03
bca3fc7
2af0fed
4050199
7808873
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -444,3 +444,97 @@ public class LogoutModel : PageModel | |||||
} | ||||||
} | ||||||
``` | ||||||
|
||||||
# Accessing Auth0.AuthenticationApi features | ||||||
`Auth0.AuthenticationApi` package is our standalone Authentication package that supports a wide range of | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
options for Authentication. We can access these features like below : | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just to give some context of what you are showing below.
Suggested change
|
||||||
|
||||||
```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 | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add a reference to this section in the table of contents at the top of this doc.
Suggested change
|
||||||
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"; | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Isn't this required too? 🤔 |
||||||
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://dx-sdks-testing.us.auth0.com/", | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we want to leave this URL here or indicate as follows:
Suggested change
|
||||||
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 |
---|---|---|
@@ -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); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add a reference to this section in the table of contents at the top of this doc.