Browse Source
- Cookie OnValidatePrincipal access token refresh (keyed single-flight, result retention, invalid_grant sign-out) - User/client access token DelegatingHandler and YARP transform (DPoP-aware) - MapOpenIddictBffEndpoints: login, logout (sid check), user (X-CSRF), callbacks, back-channel logout - Back-channel logout token validation + IOpenIddictClientAspNetCoreBffSessionStore / in-memory store - Store backchannel_access_token_type in ASP.NET Core and OWIN client hosts - Tests for refresh, CSRF, endpoints, logout, handlers and proxypull/2549/head
35 changed files with 3932 additions and 0 deletions
@ -0,0 +1,24 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using static OpenIddict.Client.AspNetCore.Bff.OpenIddictClientAspNetCoreBffModels; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Represents a handler invoked when a valid back-channel logout notification is received.
|
|||
/// All the registered handlers are invoked, in registration order.
|
|||
/// </summary>
|
|||
public interface IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler |
|||
{ |
|||
/// <summary>
|
|||
/// Handles the specified back-channel logout notification.
|
|||
/// </summary>
|
|||
/// <param name="notification">The back-channel logout notification.</param>
|
|||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
|
|||
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
|
|||
ValueTask HandleAsync(BackchannelLogoutNotification notification, CancellationToken cancellationToken); |
|||
} |
|||
@ -0,0 +1,29 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using Microsoft.AspNetCore.Authentication.Cookies; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Represents a server-side session store (<see cref="ITicketStore"/>) that supports removing
|
|||
/// sessions when a back-channel logout notification is received from an authorization server.
|
|||
/// </summary>
|
|||
public interface IOpenIddictClientAspNetCoreBffSessionStore : ITicketStore |
|||
{ |
|||
/// <summary>
|
|||
/// Removes the sessions matching the specified criteria. Only sessions whose principal contains a
|
|||
/// matching client registration identifier and, when specified, a matching subject ("sub")
|
|||
/// and session identifier ("sid") are removed.
|
|||
/// </summary>
|
|||
/// <param name="registrationId">The client registration identifier.</param>
|
|||
/// <param name="subject">The subject, if specified.</param>
|
|||
/// <param name="sessionId">The session identifier, if specified.</param>
|
|||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
|
|||
/// <returns>The number of sessions that were removed.</returns>
|
|||
ValueTask<int> RemoveSessionsAsync(string registrationId, string? subject, |
|||
string? sessionId, CancellationToken cancellationToken); |
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFrameworks>$(NetCoreTargetFrameworks)</TargetFrameworks> |
|||
</PropertyGroup> |
|||
|
|||
<PropertyGroup> |
|||
<Description>Backend-for-frontend (BFF) support for the OpenIddict client ASP.NET Core integration (token refresh, API proxying, session endpoints).</Description> |
|||
<PackageTags>$(PackageTags);client;aspnetcore;bff;yarp</PackageTags> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="..\OpenIddict.Client.AspNetCore\OpenIddict.Client.AspNetCore.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<FrameworkReference Include="Microsoft.AspNetCore.App" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Yarp.ReverseProxy" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<Using Include="Microsoft.AspNetCore.Authentication" /> |
|||
<Using Include="Microsoft.AspNetCore.Http" /> |
|||
<Using Include="OpenIddict.Abstractions" /> |
|||
<Using Include="OpenIddict.Abstractions.OpenIddictConstants" Static="true" /> |
|||
<Using Include="OpenIddict.Abstractions.OpenIddictResources" Alias="SR" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,96 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.Net; |
|||
using static OpenIddict.Client.AspNetCore.Bff.OpenIddictClientAspNetCoreBffModels; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Represents a <see cref="DelegatingHandler"/> attaching a user or client access token to outgoing requests.
|
|||
/// </summary>
|
|||
/// <remarks>
|
|||
/// DPoP-bound tokens are sent with a DPoP proof. If the resource server returns a "use_dpop_nonce" error,
|
|||
/// requests without content are sent again once with the nonce returned by the resource server.
|
|||
/// </remarks>
|
|||
public sealed class OpenIddictClientAspNetCoreBffAccessTokenHandler : DelegatingHandler |
|||
{ |
|||
private readonly IHttpContextAccessor _accessor; |
|||
private readonly OpenIddictClientAspNetCoreBffTokenManager _manager; |
|||
private readonly OpenIddictClientAspNetCoreBffTokenType _type; |
|||
private readonly ClientAccessTokenRequest? _request; |
|||
|
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="OpenIddictClientAspNetCoreBffAccessTokenHandler"/> class.
|
|||
/// </summary>
|
|||
/// <param name="accessor">The HTTP context accessor.</param>
|
|||
/// <param name="manager">The BFF token manager.</param>
|
|||
/// <param name="type">The type of access token to attach.</param>
|
|||
/// <param name="request">The client access token request, if applicable.</param>
|
|||
public OpenIddictClientAspNetCoreBffAccessTokenHandler( |
|||
IHttpContextAccessor accessor, |
|||
OpenIddictClientAspNetCoreBffTokenManager manager, |
|||
OpenIddictClientAspNetCoreBffTokenType type, |
|||
ClientAccessTokenRequest? request = null) |
|||
{ |
|||
_accessor = accessor ?? throw new ArgumentNullException(nameof(accessor)); |
|||
_manager = manager ?? throw new ArgumentNullException(nameof(manager)); |
|||
_type = type; |
|||
_request = request; |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(request); |
|||
|
|||
var token = await ResolveAccessTokenAsync(cancellationToken); |
|||
if (token is null) |
|||
{ |
|||
return await base.SendAsync(request, cancellationToken); |
|||
} |
|||
|
|||
await _manager.AttachAccessTokenAsync(request, token, cancellationToken: cancellationToken); |
|||
|
|||
var response = await base.SendAsync(request, cancellationToken); |
|||
|
|||
// If the resource server requires a DPoP nonce, send the request again with the returned nonce.
|
|||
// Note: requests with content are never sent again, as the content may not be re-readable.
|
|||
if (request.Content is null && response.StatusCode is HttpStatusCode.Unauthorized && |
|||
string.Equals(token.TokenType, TokenTypes.DPoP, StringComparison.OrdinalIgnoreCase) && |
|||
response.Headers.TryGetValues(OpenIddictClientAspNetCoreBffConstants.Headers.DPoPNonce, out var values) && |
|||
values.FirstOrDefault() is { Length: > 0 } nonce && |
|||
response.Headers.WwwAuthenticate.Any(static header => header.Parameter?.Contains( |
|||
Errors.UseDPoPNonce, StringComparison.Ordinal) is true)) |
|||
{ |
|||
response.Dispose(); |
|||
|
|||
await _manager.AttachAccessTokenAsync(request, token, nonce: nonce, cancellationToken: cancellationToken); |
|||
|
|||
response = await base.SendAsync(request, cancellationToken); |
|||
} |
|||
|
|||
return response; |
|||
} |
|||
|
|||
private async ValueTask<AccessToken?> ResolveAccessTokenAsync(CancellationToken cancellationToken) |
|||
{ |
|||
switch (_type) |
|||
{ |
|||
case OpenIddictClientAspNetCoreBffTokenType.User or OpenIddictClientAspNetCoreBffTokenType.OptionalUser: |
|||
return _accessor.HttpContext is HttpContext context ? await _manager.GetUserAccessTokenAsync(context) : null; |
|||
|
|||
case OpenIddictClientAspNetCoreBffTokenType.Client: |
|||
return await _manager.GetClientAccessTokenAsync(_request, cancellationToken); |
|||
|
|||
case OpenIddictClientAspNetCoreBffTokenType.UserOrClient: |
|||
return (_accessor.HttpContext is HttpContext value ? await _manager.GetUserAccessTokenAsync(value) : null) |
|||
?? await _manager.GetClientAccessTokenAsync(_request, cancellationToken); |
|||
|
|||
default: return null; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,20 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Represents the endpoint metadata marking a local endpoint as a BFF API endpoint: requests
|
|||
/// must contain the antiforgery header and unauthenticated calls receive 401 responses
|
|||
/// instead of being redirected to the login page.
|
|||
/// </summary>
|
|||
public sealed class OpenIddictClientAspNetCoreBffApiEndpointMetadata |
|||
{ |
|||
/// <summary>
|
|||
/// Gets or sets a boolean indicating whether the antiforgery header check is disabled.
|
|||
/// </summary>
|
|||
public bool DisableAntiforgeryCheck { get; init; } |
|||
} |
|||
@ -0,0 +1,187 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.ComponentModel; |
|||
using System.Diagnostics.CodeAnalysis; |
|||
using Microsoft.AspNetCore.Authentication.Cookies; |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using Microsoft.Extensions.Options; |
|||
using OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
namespace Microsoft.Extensions.DependencyInjection; |
|||
|
|||
/// <summary>
|
|||
/// Exposes the necessary methods required to configure the OpenIddict backend-for-frontend (BFF) components.
|
|||
/// </summary>
|
|||
public sealed class OpenIddictClientAspNetCoreBffBuilder |
|||
{ |
|||
/// <summary>
|
|||
/// Initializes a new instance of <see cref="OpenIddictClientAspNetCoreBffBuilder"/>.
|
|||
/// </summary>
|
|||
/// <param name="services">The services collection.</param>
|
|||
public OpenIddictClientAspNetCoreBffBuilder(IServiceCollection services) |
|||
=> Services = services ?? throw new ArgumentNullException(nameof(services)); |
|||
|
|||
/// <summary>
|
|||
/// Gets the services collection.
|
|||
/// </summary>
|
|||
[EditorBrowsable(EditorBrowsableState.Never)] |
|||
public IServiceCollection Services { get; } |
|||
|
|||
/// <summary>
|
|||
/// Enables validation of options during application startup.
|
|||
/// </summary>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder ValidateOnStart() |
|||
{ |
|||
Services.AddOptionsWithValidateOnStart<OpenIddictClientAspNetCoreBffOptions>(); |
|||
|
|||
return this; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Amends the default OpenIddict BFF configuration.
|
|||
/// </summary>
|
|||
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
|
|||
/// <remarks>This extension can be safely called multiple times.</remarks>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
[EditorBrowsable(EditorBrowsableState.Advanced)] |
|||
public OpenIddictClientAspNetCoreBffBuilder Configure(Action<OpenIddictClientAspNetCoreBffOptions> configuration) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(configuration); |
|||
|
|||
Services.Configure(configuration); |
|||
|
|||
return this; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Sets the cookie authentication scheme storing the user session and tokens.
|
|||
/// </summary>
|
|||
/// <param name="scheme">The authentication scheme.</param>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder SetCookieScheme(string scheme) |
|||
{ |
|||
ArgumentException.ThrowIfNullOrEmpty(scheme); |
|||
|
|||
return Configure(options => options.CookieScheme = scheme); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Disables the automatic refresh of the access tokens stored in the authentication cookie.
|
|||
/// </summary>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder DisableAutomaticTokenRefresh() |
|||
=> Configure(options => options.DisableAutomaticTokenRefresh = true); |
|||
|
|||
/// <summary>
|
|||
/// Sets the margin applied to the expiration date of access tokens when determining whether they must be refreshed.
|
|||
/// </summary>
|
|||
/// <param name="margin">The margin.</param>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder SetAccessTokenRefreshMargin(TimeSpan margin) |
|||
=> Configure(options => options.AccessTokenRefreshMargin = margin); |
|||
|
|||
/// <summary>
|
|||
/// Sets the period during which refresh token results are returned to requests carrying the same refresh token.
|
|||
/// </summary>
|
|||
/// <param name="period">The retention period (<see cref="TimeSpan.Zero"/> to disable retention).</param>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder SetTokenRefreshResultRetentionPeriod(TimeSpan period) |
|||
=> Configure(options => options.TokenRefreshResultRetentionPeriod = period); |
|||
|
|||
/// <summary>
|
|||
/// Sets the name and value of the antiforgery header required by the user and API endpoints.
|
|||
/// </summary>
|
|||
/// <param name="name">The header name.</param>
|
|||
/// <param name="value">The header value.</param>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder SetAntiforgeryHeader(string name, string value) |
|||
{ |
|||
ArgumentException.ThrowIfNullOrEmpty(name); |
|||
ArgumentException.ThrowIfNullOrEmpty(value); |
|||
|
|||
return Configure(options => |
|||
{ |
|||
options.AntiforgeryHeaderName = name; |
|||
options.AntiforgeryHeaderValue = value; |
|||
}); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Sets the paths of the BFF endpoints. Paths left <see langword="null"/> are not changed.
|
|||
/// </summary>
|
|||
/// <param name="login">The login endpoint path.</param>
|
|||
/// <param name="logout">The logout endpoint path.</param>
|
|||
/// <param name="user">The user endpoint path.</param>
|
|||
/// <param name="backchannelLogout">The back-channel logout endpoint path.</param>
|
|||
/// <param name="redirection">The redirection (login callback) endpoint path.</param>
|
|||
/// <param name="postLogoutRedirection">The post-logout redirection (logout callback) endpoint path.</param>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder SetEndpointPaths( |
|||
string? login = null, string? logout = null, string? user = null, |
|||
string? backchannelLogout = null, string? redirection = null, string? postLogoutRedirection = null) |
|||
=> Configure(options => |
|||
{ |
|||
options.LoginPath = login is not null ? new PathString(login) : options.LoginPath; |
|||
options.LogoutPath = logout is not null ? new PathString(logout) : options.LogoutPath; |
|||
options.UserPath = user is not null ? new PathString(user) : options.UserPath; |
|||
options.BackchannelLogoutPath = backchannelLogout is not null ? new PathString(backchannelLogout) : options.BackchannelLogoutPath; |
|||
options.RedirectionPath = redirection is not null ? new PathString(redirection) : options.RedirectionPath; |
|||
options.PostLogoutRedirectionPath = postLogoutRedirection is not null |
|||
? new PathString(postLogoutRedirection) : options.PostLogoutRedirectionPath; |
|||
}); |
|||
|
|||
/// <summary>
|
|||
/// Prevents the BFF callback paths from being added to the OpenIddict client options
|
|||
/// and the pass-through mode of the callback endpoints from being enabled.
|
|||
/// </summary>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder DisableAutomaticEndpointRegistration() |
|||
=> Configure(options => options.DisableAutomaticEndpointRegistration = true); |
|||
|
|||
/// <summary>
|
|||
/// Sets the default local return URL.
|
|||
/// </summary>
|
|||
/// <param name="url">The local URL.</param>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder SetDefaultReturnUrl(string url) |
|||
{ |
|||
ArgumentException.ThrowIfNullOrEmpty(url); |
|||
|
|||
return Configure(options => options.DefaultReturnUrl = url); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Registers an in-memory server-side session store supporting back-channel logout
|
|||
/// and attaches it to the BFF cookie scheme (or to all cookie schemes if no scheme was set).
|
|||
/// </summary>
|
|||
/// <remarks>Sessions are lost when the application restarts and are not shared between instances.</remarks>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder UseInMemorySessionStore() |
|||
{ |
|||
Services.TryAddSingleton<OpenIddictClientAspNetCoreBffMemorySessionStore>(); |
|||
|
|||
Services.TryAddEnumerable(ServiceDescriptor.Singleton< |
|||
IPostConfigureOptions<CookieAuthenticationOptions>, OpenIddictClientAspNetCoreBffSessionStoreConfiguration>()); |
|||
|
|||
return this; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Registers a handler invoked when a valid back-channel logout notification is received.
|
|||
/// </summary>
|
|||
/// <typeparam name="THandler">The handler type.</typeparam>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public OpenIddictClientAspNetCoreBffBuilder AddBackchannelLogoutHandler< |
|||
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] THandler>() |
|||
where THandler : class, IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler |
|||
{ |
|||
Services.TryAddEnumerable(ServiceDescriptor.Scoped<IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler, THandler>()); |
|||
|
|||
return this; |
|||
} |
|||
} |
|||
@ -0,0 +1,173 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.ComponentModel; |
|||
using Microsoft.AspNetCore.Authentication.Cookies; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Contains the methods required to ensure that the OpenIddict BFF configuration is valid.
|
|||
/// </summary>
|
|||
[EditorBrowsable(EditorBrowsableState.Advanced)] |
|||
public sealed class OpenIddictClientAspNetCoreBffConfiguration : IPostConfigureOptions<OpenIddictClientOptions>, |
|||
IPostConfigureOptions<OpenIddictClientAspNetCoreOptions>, |
|||
IPostConfigureOptions<CookieAuthenticationOptions>, |
|||
IValidateOptions<OpenIddictClientAspNetCoreBffOptions> |
|||
{ |
|||
private readonly IServiceProvider _provider; |
|||
|
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="OpenIddictClientAspNetCoreBffConfiguration"/> class.
|
|||
/// </summary>
|
|||
/// <param name="provider">The service provider.</param>
|
|||
public OpenIddictClientAspNetCoreBffConfiguration(IServiceProvider provider) |
|||
=> _provider = provider ?? throw new ArgumentNullException(nameof(provider)); |
|||
|
|||
/// <inheritdoc/>
|
|||
public void PostConfigure(string? name, OpenIddictClientOptions options) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(options); |
|||
|
|||
var settings = _provider.GetRequiredService<IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions>>().CurrentValue; |
|||
if (settings.DisableAutomaticEndpointRegistration) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
// Note: post-configuration is used to ensure the BFF endpoints are not removed
|
|||
// when the endpoint URIs are explicitly set using SetRedirectionEndpointUris().
|
|||
AddUri(options.RedirectionEndpointUris, settings.RedirectionPath); |
|||
AddUri(options.PostLogoutRedirectionEndpointUris, settings.PostLogoutRedirectionPath); |
|||
|
|||
static void AddUri(List<Uri> uris, PathString path) |
|||
{ |
|||
if (!path.HasValue) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
// Note: relative URIs are resolved against the base URI of the current request.
|
|||
var uri = new Uri(path.Value[1..], UriKind.Relative); |
|||
if (!uris.Contains(uri)) |
|||
{ |
|||
uris.Add(uri); |
|||
} |
|||
} |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public void PostConfigure(string? name, OpenIddictClientAspNetCoreOptions options) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(options); |
|||
|
|||
var settings = _provider.GetRequiredService<IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions>>().CurrentValue; |
|||
if (settings.DisableAutomaticEndpointRegistration) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
// The BFF callback endpoints are handled by the endpoints mapped by MapOpenIddictBffEndpoints().
|
|||
options.EnableRedirectionEndpointPassthrough = true; |
|||
options.EnablePostLogoutRedirectionEndpointPassthrough = true; |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public void PostConfigure(string? name, CookieAuthenticationOptions options) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(options); |
|||
|
|||
var settings = _provider.GetRequiredService<IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions>>().CurrentValue; |
|||
|
|||
// If an explicit cookie scheme was configured, only attach the BFF logic to that scheme.
|
|||
if (!string.IsNullOrEmpty(settings.CookieScheme) && !string.Equals(name, settings.CookieScheme, StringComparison.Ordinal)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
var events = options.Events ??= new CookieAuthenticationEvents(); |
|||
|
|||
var validate = events.OnValidatePrincipal; |
|||
events.OnValidatePrincipal = async context => |
|||
{ |
|||
await validate(context); |
|||
|
|||
if (context.Principal is not null) |
|||
{ |
|||
var manager = context.HttpContext.RequestServices.GetService<OpenIddictClientAspNetCoreBffTokenManager>() ?? |
|||
throw new InvalidOperationException(SR.GetResourceString(SR.ID0561)); |
|||
|
|||
await manager.ValidatePrincipalAsync(context); |
|||
} |
|||
}; |
|||
|
|||
// Return 401/403 responses instead of redirecting API calls to the login/access denied pages.
|
|||
var login = events.OnRedirectToLogin; |
|||
events.OnRedirectToLogin = context => |
|||
{ |
|||
if (OpenIddictClientAspNetCoreBffHelpers.IsBffApiRequest(context.HttpContext)) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
|||
|
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
return login(context); |
|||
}; |
|||
|
|||
var denied = events.OnRedirectToAccessDenied; |
|||
events.OnRedirectToAccessDenied = context => |
|||
{ |
|||
if (OpenIddictClientAspNetCoreBffHelpers.IsBffApiRequest(context.HttpContext)) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status403Forbidden; |
|||
|
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
return denied(context); |
|||
}; |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValidateOptionsResult Validate(string? name, OpenIddictClientAspNetCoreBffOptions options) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(options); |
|||
|
|||
var builder = new ValidateOptionsResultBuilder(); |
|||
|
|||
foreach (var (property, path) in new[] |
|||
{ |
|||
(nameof(options.LoginPath), options.LoginPath), |
|||
(nameof(options.LogoutPath), options.LogoutPath), |
|||
(nameof(options.UserPath), options.UserPath), |
|||
(nameof(options.BackchannelLogoutPath), options.BackchannelLogoutPath), |
|||
(nameof(options.RedirectionPath), options.RedirectionPath), |
|||
(nameof(options.PostLogoutRedirectionPath), options.PostLogoutRedirectionPath) |
|||
}) |
|||
{ |
|||
if (!path.HasValue || path.Value.Length is < 2) |
|||
{ |
|||
builder.AddError(SR.FormatID0559(property)); |
|||
} |
|||
} |
|||
|
|||
if (options.AccessTokenRefreshMargin < TimeSpan.Zero || options.TokenRefreshResultRetentionPeriod < TimeSpan.Zero || |
|||
options.LogoutTokenReplayCacheLifetime < TimeSpan.Zero) |
|||
{ |
|||
builder.AddError(SR.GetResourceString(SR.ID0560)); |
|||
} |
|||
|
|||
if (string.IsNullOrEmpty(options.AntiforgeryHeaderName) || string.IsNullOrEmpty(options.AntiforgeryHeaderValue)) |
|||
{ |
|||
builder.AddError(SR.GetResourceString(SR.ID0563)); |
|||
} |
|||
|
|||
return builder.Build(); |
|||
} |
|||
} |
|||
@ -0,0 +1,66 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Exposes common constants used by the OpenIddict backend-for-frontend (BFF) components.
|
|||
/// </summary>
|
|||
public static class OpenIddictClientAspNetCoreBffConstants |
|||
{ |
|||
public static class Claims |
|||
{ |
|||
public const string LogoutUrl = "bff:logout_url"; |
|||
public const string SessionExpiresIn = "bff:session_expires_in"; |
|||
} |
|||
|
|||
public static class Events |
|||
{ |
|||
public const string BackchannelLogout = "http://schemas.openid.net/event/backchannel-logout"; |
|||
} |
|||
|
|||
public static class Headers |
|||
{ |
|||
public const string Antiforgery = "X-CSRF"; |
|||
public const string CacheControl = "Cache-Control"; |
|||
public const string Cookie = "Cookie"; |
|||
public const string DPoP = "DPoP"; |
|||
public const string DPoPNonce = "DPoP-Nonce"; |
|||
public const string Pragma = "Pragma"; |
|||
public const string WwwAuthenticate = "WWW-Authenticate"; |
|||
} |
|||
|
|||
public static class Metadata |
|||
{ |
|||
/// <summary>
|
|||
/// Name of the YARP route metadata indicating the type of access token attached to proxied requests
|
|||
/// (see <see cref="OpenIddictClientAspNetCoreBffTokenType"/> for the supported values).
|
|||
/// </summary>
|
|||
public const string AccessToken = "OpenIddict.Bff.AccessToken"; |
|||
|
|||
/// <summary>
|
|||
/// Name of the YARP route metadata allowing to disable the antiforgery header check ("true" to disable).
|
|||
/// </summary>
|
|||
public const string DisableAntiforgeryCheck = "OpenIddict.Bff.DisableAntiforgeryCheck"; |
|||
|
|||
/// <summary>
|
|||
/// Name of the YARP route metadata containing the client registration used to get client access tokens.
|
|||
/// </summary>
|
|||
public const string RegistrationId = "OpenIddict.Bff.RegistrationId"; |
|||
|
|||
/// <summary>
|
|||
/// Name of the YARP route metadata containing the space-separated scopes requested for client access tokens.
|
|||
/// </summary>
|
|||
public const string Scopes = "OpenIddict.Bff.Scopes"; |
|||
} |
|||
|
|||
public static class QueryStringParameters |
|||
{ |
|||
public const string Provider = "provider"; |
|||
public const string ReturnUrl = "returnUrl"; |
|||
public const string SessionId = "sid"; |
|||
} |
|||
} |
|||
@ -0,0 +1,94 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using Microsoft.AspNetCore.Routing; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
using OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
namespace Microsoft.AspNetCore.Builder; |
|||
|
|||
/// <summary>
|
|||
/// Exposes extensions allowing to map the OpenIddict backend-for-frontend (BFF) endpoints and middleware.
|
|||
/// </summary>
|
|||
public static class OpenIddictClientAspNetCoreBffEndpointRouteBuilderExtensions |
|||
{ |
|||
/// <summary>
|
|||
/// Maps the login, logout, user, back-channel logout and callback BFF endpoints
|
|||
/// using the paths configured in <see cref="OpenIddictClientAspNetCoreBffOptions"/>.
|
|||
/// </summary>
|
|||
/// <param name="endpoints">The endpoint route builder.</param>
|
|||
/// <returns>A <see cref="IEndpointConventionBuilder"/> applying conventions to all the BFF endpoints.</returns>
|
|||
public static IEndpointConventionBuilder MapOpenIddictBffEndpoints(this IEndpointRouteBuilder endpoints) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(endpoints); |
|||
|
|||
var options = endpoints.ServiceProvider.GetService<IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions>>()?.CurrentValue ?? |
|||
throw new InvalidOperationException(SR.GetResourceString(SR.ID0561)); |
|||
|
|||
return new CompositeEndpointConventionBuilder( |
|||
[ |
|||
endpoints.MapGet(options.LoginPath, OpenIddictClientAspNetCoreBffEndpoints.LoginAsync), |
|||
endpoints.MapMethods(options.RedirectionPath, [HttpMethods.Get, HttpMethods.Post], OpenIddictClientAspNetCoreBffEndpoints.LoginCallbackAsync), |
|||
endpoints.MapGet(options.LogoutPath, OpenIddictClientAspNetCoreBffEndpoints.LogoutAsync), |
|||
endpoints.MapMethods(options.PostLogoutRedirectionPath, [HttpMethods.Get, HttpMethods.Post], OpenIddictClientAspNetCoreBffEndpoints.LogoutCallbackAsync), |
|||
endpoints.MapGet(options.UserPath, OpenIddictClientAspNetCoreBffEndpoints.UserAsync), |
|||
endpoints.MapPost(options.BackchannelLogoutPath, OpenIddictClientAspNetCoreBffEndpoints.BackchannelLogoutAsync) |
|||
]); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Marks the endpoint as a BFF API endpoint: requests must contain the antiforgery header (unless disabled)
|
|||
/// and unauthenticated requests receive 401 responses instead of being redirected to the login page.
|
|||
/// </summary>
|
|||
/// <remarks>This requires registering the BFF middleware using <see cref="UseOpenIddictBff(IApplicationBuilder)"/>.</remarks>
|
|||
/// <typeparam name="TBuilder">The type of the endpoint convention builder.</typeparam>
|
|||
/// <param name="builder">The endpoint convention builder.</param>
|
|||
/// <param name="disableAntiforgeryCheck">Whether the antiforgery header check should be disabled.</param>
|
|||
/// <returns>The endpoint convention builder.</returns>
|
|||
public static TBuilder AsOpenIddictBffApiEndpoint<TBuilder>(this TBuilder builder, bool disableAntiforgeryCheck = false) |
|||
where TBuilder : IEndpointConventionBuilder |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(builder); |
|||
|
|||
return builder.WithMetadata(new OpenIddictClientAspNetCoreBffApiEndpointMetadata |
|||
{ |
|||
DisableAntiforgeryCheck = disableAntiforgeryCheck |
|||
}); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Registers the BFF middleware enforcing the antiforgery header check on BFF API endpoints and YARP routes.
|
|||
/// </summary>
|
|||
/// <remarks>This middleware must be registered after <c>UseRouting()</c> and <c>UseAuthentication()</c>.</remarks>
|
|||
/// <param name="app">The application builder.</param>
|
|||
/// <returns>The <see cref="IApplicationBuilder"/> instance.</returns>
|
|||
public static IApplicationBuilder UseOpenIddictBff(this IApplicationBuilder app) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(app); |
|||
|
|||
return app.UseMiddleware<OpenIddictClientAspNetCoreBffMiddleware>(); |
|||
} |
|||
|
|||
private sealed class CompositeEndpointConventionBuilder(IEndpointConventionBuilder[] builders) : IEndpointConventionBuilder |
|||
{ |
|||
public void Add(Action<EndpointBuilder> convention) |
|||
{ |
|||
foreach (var builder in builders) |
|||
{ |
|||
builder.Add(convention); |
|||
} |
|||
} |
|||
|
|||
public void Finally(Action<EndpointBuilder> convention) |
|||
{ |
|||
foreach (var builder in builders) |
|||
{ |
|||
builder.Finally(convention); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,338 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.Globalization; |
|||
using System.Security.Claims; |
|||
using System.Text.Json; |
|||
using Microsoft.AspNetCore.WebUtilities; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Properties = OpenIddict.Client.AspNetCore.OpenIddictClientAspNetCoreConstants.Properties; |
|||
using Tokens = OpenIddict.Client.AspNetCore.OpenIddictClientAspNetCoreConstants.Tokens; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Contains the request delegates used by the OpenIddict backend-for-frontend (BFF) endpoints.
|
|||
/// </summary>
|
|||
internal static class OpenIddictClientAspNetCoreBffEndpoints |
|||
{ |
|||
/// <summary>
|
|||
/// Starts an interactive login flow: the user agent is redirected to the authorization server.
|
|||
/// </summary>
|
|||
public static async Task LoginAsync(HttpContext context) |
|||
{ |
|||
var options = OpenIddictClientAspNetCoreBffHelpers.GetOptions(context); |
|||
|
|||
if (!TryResolveReturnUrl(context, options, context.Request.Query[OpenIddictClientAspNetCoreBffConstants.QueryStringParameters.ReturnUrl], |
|||
out var url)) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status400BadRequest; |
|||
return; |
|||
} |
|||
|
|||
var properties = new AuthenticationProperties { RedirectUri = url }; |
|||
|
|||
var provider = (string?) context.Request.Query[OpenIddictClientAspNetCoreBffConstants.QueryStringParameters.Provider]; |
|||
if (!string.IsNullOrEmpty(provider)) |
|||
{ |
|||
// Validate the provider name before triggering the challenge to return a 400 response for unknown providers.
|
|||
try |
|||
{ |
|||
await context.RequestServices.GetRequiredService<OpenIddictClientService>() |
|||
.GetClientRegistrationByProviderNameAsync(provider, context.RequestAborted); |
|||
} |
|||
|
|||
catch (InvalidOperationException) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status400BadRequest; |
|||
return; |
|||
} |
|||
|
|||
properties.Items[Properties.ProviderName] = provider; |
|||
} |
|||
|
|||
await context.ChallengeAsync(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme, properties); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Handles the login callback: the authorization data is validated and the user is signed in.
|
|||
/// </summary>
|
|||
public static async Task LoginCallbackAsync(HttpContext context) |
|||
{ |
|||
var options = OpenIddictClientAspNetCoreBffHelpers.GetOptions(context); |
|||
|
|||
var result = await context.AuthenticateAsync(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme); |
|||
if (result is not { Succeeded: true, Principal: ClaimsPrincipal principal, Properties: AuthenticationProperties ticket }) |
|||
{ |
|||
await WriteErrorAsync(context, |
|||
GetItem(result.Properties, Properties.Error) ?? Errors.InvalidRequest, |
|||
GetItem(result.Properties, Properties.ErrorDescription)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
// Note: authorization servers that don't support OpenID Connect may not return any user claim, in which case
|
|||
// the identity is not authenticated: an authentication type is always set to allow creating a session.
|
|||
var identity = new ClaimsIdentity(principal.Claims, |
|||
authenticationType: principal.Identity?.AuthenticationType is { Length: > 0 } type ? type : OpenIddictClientAspNetCoreDefaults.AuthenticationScheme, |
|||
nameType: (principal.Identity as ClaimsIdentity)?.NameClaimType ?? Claims.Name, |
|||
roleType: (principal.Identity as ClaimsIdentity)?.RoleClaimType ?? Claims.Role); |
|||
|
|||
var properties = new AuthenticationProperties |
|||
{ |
|||
// Decorrelate the lifetime of the session from the lifetime of the state token.
|
|||
ExpiresUtc = null, |
|||
IsPersistent = false, |
|||
IssuedUtc = null |
|||
}; |
|||
|
|||
foreach (var name in (ReadOnlySpan<string>) [Properties.Issuer, Properties.ProviderName, Properties.RegistrationId]) |
|||
{ |
|||
if (GetItem(ticket, name) is string value) |
|||
{ |
|||
properties.Items[name] = value; |
|||
} |
|||
} |
|||
|
|||
// Only store the tokens required by the BFF components to limit the size of the ticket.
|
|||
properties.StoreTokens(ticket.GetTokens().Where(static token => token.Name is |
|||
Tokens.BackchannelAccessToken or |
|||
Tokens.BackchannelAccessTokenExpirationDate or |
|||
Tokens.BackchannelAccessTokenType or |
|||
Tokens.BackchannelIdentityToken or |
|||
Tokens.RefreshToken)); |
|||
|
|||
await context.SignInAsync(options.CookieScheme, new ClaimsPrincipal(identity), properties); |
|||
|
|||
context.Response.Redirect(TryResolveReturnUrl(context, options, ticket.RedirectUri, out var url) && url is not null |
|||
? url : ResolveUrl(context, options.DefaultReturnUrl)); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Removes the local session and, if supported by the authorization server, starts an end session flow.
|
|||
/// </summary>
|
|||
public static async Task LogoutAsync(HttpContext context) |
|||
{ |
|||
var options = OpenIddictClientAspNetCoreBffHelpers.GetOptions(context); |
|||
|
|||
if (!TryResolveReturnUrl(context, options, context.Request.Query[OpenIddictClientAspNetCoreBffConstants.QueryStringParameters.ReturnUrl], |
|||
out var url)) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status400BadRequest; |
|||
return; |
|||
} |
|||
|
|||
var result = await context.AuthenticateAsync(options.CookieScheme); |
|||
if (result is not { Succeeded: true, Principal: ClaimsPrincipal principal }) |
|||
{ |
|||
context.Response.Redirect(url); |
|||
return; |
|||
} |
|||
|
|||
// To mitigate logout CSRF attacks, the session identifier must be specified when the session has one.
|
|||
var session = principal.FindFirst(Claims.SessionId)?.Value; |
|||
if (!string.IsNullOrEmpty(session) && !string.Equals(session, context.Request.Query[ |
|||
OpenIddictClientAspNetCoreBffConstants.QueryStringParameters.SessionId], StringComparison.Ordinal)) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status400BadRequest; |
|||
return; |
|||
} |
|||
|
|||
await context.SignOutAsync(options.CookieScheme); |
|||
|
|||
var registration = OpenIddictClientAspNetCoreBffTokenManager.GetRegistrationId(principal, result.Properties); |
|||
if (!string.IsNullOrEmpty(registration)) |
|||
{ |
|||
var service = context.RequestServices.GetRequiredService<OpenIddictClientService>(); |
|||
|
|||
var configuration = await service.GetServerConfigurationByRegistrationIdAsync(registration, context.RequestAborted); |
|||
if (configuration.EndSessionEndpoint is not null) |
|||
{ |
|||
var properties = new AuthenticationProperties(new Dictionary<string, string?>(StringComparer.Ordinal) |
|||
{ |
|||
[Properties.RegistrationId] = registration, |
|||
[Properties.IdentityTokenHint] = result.Properties?.GetTokenValue(Tokens.BackchannelIdentityToken) |
|||
}) |
|||
{ |
|||
RedirectUri = url |
|||
}; |
|||
|
|||
await context.SignOutAsync(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme, properties); |
|||
return; |
|||
} |
|||
} |
|||
|
|||
context.Response.Redirect(url); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Handles the logout callback: the user agent is redirected to the return URL.
|
|||
/// </summary>
|
|||
public static async Task LogoutCallbackAsync(HttpContext context) |
|||
{ |
|||
var options = OpenIddictClientAspNetCoreBffHelpers.GetOptions(context); |
|||
|
|||
var result = await context.AuthenticateAsync(OpenIddictClientAspNetCoreDefaults.AuthenticationScheme); |
|||
|
|||
context.Response.Redirect(TryResolveReturnUrl(context, options, result.Properties?.RedirectUri, out var url) && url is not null |
|||
? url : ResolveUrl(context, options.DefaultReturnUrl)); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Returns the claims of the authenticated user (the antiforgery header is required).
|
|||
/// </summary>
|
|||
public static async Task UserAsync(HttpContext context) |
|||
{ |
|||
var options = OpenIddictClientAspNetCoreBffHelpers.GetOptions(context); |
|||
|
|||
SetNoCacheHeaders(context); |
|||
|
|||
if (!context.HasValidAntiforgeryHeader()) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
|||
return; |
|||
} |
|||
|
|||
var result = await context.AuthenticateAsync(options.CookieScheme); |
|||
if (result is not { Succeeded: true, Principal: ClaimsPrincipal principal }) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
|||
return; |
|||
} |
|||
|
|||
var url = context.Request.PathBase.Add(options.LogoutPath).Value!; |
|||
if (principal.FindFirst(Claims.SessionId)?.Value is { Length: > 0 } session) |
|||
{ |
|||
url = QueryHelpers.AddQueryString(url, OpenIddictClientAspNetCoreBffConstants.QueryStringParameters.SessionId, session); |
|||
} |
|||
|
|||
context.Response.ContentType = "application/json;charset=UTF-8"; |
|||
|
|||
await using var writer = new Utf8JsonWriter(context.Response.Body); |
|||
|
|||
writer.WriteStartArray(); |
|||
|
|||
foreach (var claim in principal.Claims) |
|||
{ |
|||
WriteClaim(writer, claim.Type, claim.Value); |
|||
} |
|||
|
|||
if (result.Properties?.ExpiresUtc is DateTimeOffset date) |
|||
{ |
|||
var provider = context.RequestServices.GetService<Microsoft.Extensions.Options.IOptionsMonitor<OpenIddictClientOptions>>() |
|||
?.CurrentValue.TimeProvider ?? TimeProvider.System; |
|||
|
|||
WriteClaim(writer, OpenIddictClientAspNetCoreBffConstants.Claims.SessionExpiresIn, |
|||
Math.Max(0, (long) (date - provider.GetUtcNow()).TotalSeconds).ToString(CultureInfo.InvariantCulture)); |
|||
} |
|||
|
|||
WriteClaim(writer, OpenIddictClientAspNetCoreBffConstants.Claims.LogoutUrl, url); |
|||
|
|||
writer.WriteEndArray(); |
|||
|
|||
await writer.FlushAsync(context.RequestAborted); |
|||
|
|||
static void WriteClaim(Utf8JsonWriter writer, string type, string value) |
|||
{ |
|||
writer.WriteStartObject(); |
|||
writer.WriteString("type", type); |
|||
writer.WriteString("value", value); |
|||
writer.WriteEndObject(); |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Handles back-channel logout notifications sent by authorization servers.
|
|||
/// </summary>
|
|||
public static async Task BackchannelLogoutAsync(HttpContext context) |
|||
{ |
|||
SetNoCacheHeaders(context); |
|||
|
|||
if (!HttpMethods.IsPost(context.Request.Method) || !context.Request.HasFormContentType) |
|||
{ |
|||
await WriteErrorAsync(context, Errors.InvalidRequest, SR.GetResourceString(SR.ID2239)); |
|||
return; |
|||
} |
|||
|
|||
var form = await context.Request.ReadFormAsync(context.RequestAborted); |
|||
|
|||
var token = (string?) form[Parameters.LogoutToken]; |
|||
if (string.IsNullOrEmpty(token)) |
|||
{ |
|||
await WriteErrorAsync(context, Errors.InvalidRequest, SR.GetResourceString(SR.ID2239)); |
|||
return; |
|||
} |
|||
|
|||
var validator = context.RequestServices.GetService<OpenIddictClientAspNetCoreBffLogoutTokenValidator>() ?? |
|||
throw new InvalidOperationException(SR.GetResourceString(SR.ID0561)); |
|||
|
|||
var notification = await validator.ValidateAsync(context, token); |
|||
if (notification is null) |
|||
{ |
|||
await WriteErrorAsync(context, Errors.InvalidRequest, SR.GetResourceString(SR.ID2240)); |
|||
return; |
|||
} |
|||
|
|||
foreach (var handler in context.RequestServices.GetServices<IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler>()) |
|||
{ |
|||
await handler.HandleAsync(notification, context.RequestAborted); |
|||
} |
|||
|
|||
context.Response.StatusCode = StatusCodes.Status200OK; |
|||
} |
|||
|
|||
private static string? GetItem(AuthenticationProperties? properties, string name) |
|||
=> properties?.Items.TryGetValue(name, out var value) is true && !string.IsNullOrEmpty(value) ? value : null; |
|||
|
|||
private static void SetNoCacheHeaders(HttpContext context) |
|||
{ |
|||
context.Response.Headers[OpenIddictClientAspNetCoreBffConstants.Headers.CacheControl] = "no-store"; |
|||
context.Response.Headers[OpenIddictClientAspNetCoreBffConstants.Headers.Pragma] = "no-cache"; |
|||
} |
|||
|
|||
private static string ResolveUrl(HttpContext context, string url) |
|||
=> url.StartsWith("~/", StringComparison.Ordinal) ? context.Request.PathBase.Add(url[1..]).Value! : url; |
|||
|
|||
private static bool TryResolveReturnUrl(HttpContext context, |
|||
OpenIddictClientAspNetCoreBffOptions options, string? value, out string url) |
|||
{ |
|||
if (string.IsNullOrEmpty(value)) |
|||
{ |
|||
url = ResolveUrl(context, options.DefaultReturnUrl); |
|||
return true; |
|||
} |
|||
|
|||
// Only allow local return URLs to prevent open redirect attacks.
|
|||
if (!OpenIddictClientAspNetCoreBffHelpers.IsLocalUrl(value)) |
|||
{ |
|||
url = string.Empty; |
|||
return false; |
|||
} |
|||
|
|||
url = ResolveUrl(context, value); |
|||
return true; |
|||
} |
|||
|
|||
private static async Task WriteErrorAsync(HttpContext context, string error, string? description) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status400BadRequest; |
|||
context.Response.ContentType = "application/json;charset=UTF-8"; |
|||
|
|||
await using var writer = new Utf8JsonWriter(context.Response.Body); |
|||
|
|||
writer.WriteStartObject(); |
|||
writer.WriteString(Parameters.Error, error); |
|||
|
|||
if (!string.IsNullOrEmpty(description)) |
|||
{ |
|||
writer.WriteString(Parameters.ErrorDescription, description); |
|||
} |
|||
|
|||
writer.WriteEndObject(); |
|||
|
|||
await writer.FlushAsync(context.RequestAborted); |
|||
} |
|||
} |
|||
@ -0,0 +1,127 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using Microsoft.AspNetCore.Authentication.Cookies; |
|||
using Microsoft.Extensions.DependencyInjection.Extensions; |
|||
using Microsoft.Extensions.Options; |
|||
using OpenIddict.Client; |
|||
using OpenIddict.Client.AspNetCore; |
|||
using OpenIddict.Client.AspNetCore.Bff; |
|||
using static OpenIddict.Client.AspNetCore.Bff.OpenIddictClientAspNetCoreBffModels; |
|||
|
|||
namespace Microsoft.Extensions.DependencyInjection; |
|||
|
|||
/// <summary>
|
|||
/// Exposes extensions allowing to register the OpenIddict backend-for-frontend (BFF) services.
|
|||
/// </summary>
|
|||
public static class OpenIddictClientAspNetCoreBffExtensions |
|||
{ |
|||
/// <summary>
|
|||
/// Registers the OpenIddict backend-for-frontend (BFF) services in the DI container.
|
|||
/// </summary>
|
|||
/// <param name="builder">The services builder used by OpenIddict to register new services.</param>
|
|||
/// <remarks>This extension can be safely called multiple times.</remarks>
|
|||
/// <returns>The <see cref="OpenIddictClientAspNetCoreBffBuilder"/> instance.</returns>
|
|||
public static OpenIddictClientAspNetCoreBffBuilder UseBff(this OpenIddictClientBuilder builder) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(builder); |
|||
|
|||
// The BFF components rely on the OpenIddict client ASP.NET Core integration.
|
|||
builder.UseAspNetCore(); |
|||
|
|||
builder.Services.AddHttpContextAccessor(); |
|||
|
|||
builder.Services.TryAddSingleton<OpenIddictClientAspNetCoreBffTokenManager>(); |
|||
builder.Services.TryAddSingleton<OpenIddictClientAspNetCoreBffLogoutTokenValidator>(); |
|||
|
|||
builder.Services.TryAddEnumerable(ServiceDescriptor.Scoped< |
|||
IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler, OpenIddictClientAspNetCoreBffSessionStoreLogoutHandler>()); |
|||
|
|||
// Note: TryAddEnumerable() is used here to ensure the initializers are only registered once.
|
|||
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< |
|||
IPostConfigureOptions<OpenIddictClientOptions>, OpenIddictClientAspNetCoreBffConfiguration>()); |
|||
|
|||
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< |
|||
IPostConfigureOptions<OpenIddictClientAspNetCoreOptions>, OpenIddictClientAspNetCoreBffConfiguration>()); |
|||
|
|||
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< |
|||
IPostConfigureOptions<CookieAuthenticationOptions>, OpenIddictClientAspNetCoreBffConfiguration>()); |
|||
|
|||
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< |
|||
IValidateOptions<OpenIddictClientAspNetCoreBffOptions>, OpenIddictClientAspNetCoreBffConfiguration>()); |
|||
|
|||
return new OpenIddictClientAspNetCoreBffBuilder(builder.Services); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Registers the OpenIddict backend-for-frontend (BFF) services in the DI container.
|
|||
/// </summary>
|
|||
/// <param name="builder">The services builder used by OpenIddict to register new services.</param>
|
|||
/// <param name="configuration">The configuration delegate used to configure the BFF services.</param>
|
|||
/// <remarks>This extension can be safely called multiple times.</remarks>
|
|||
/// <returns>The <see cref="OpenIddictClientBuilder"/> instance.</returns>
|
|||
public static OpenIddictClientBuilder UseBff( |
|||
this OpenIddictClientBuilder builder, Action<OpenIddictClientAspNetCoreBffBuilder> configuration) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(builder); |
|||
ArgumentNullException.ThrowIfNull(configuration); |
|||
|
|||
configuration(builder.UseBff()); |
|||
|
|||
return builder; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Adds a handler attaching the access token of the current user to the requests sent by the HTTP client.
|
|||
/// </summary>
|
|||
/// <param name="builder">The HTTP client builder.</param>
|
|||
/// <returns>The <see cref="IHttpClientBuilder"/> instance.</returns>
|
|||
public static IHttpClientBuilder AddOpenIddictBffUserAccessTokenHandler(this IHttpClientBuilder builder) |
|||
=> builder.AddOpenIddictBffAccessTokenHandler(OpenIddictClientAspNetCoreBffTokenType.User); |
|||
|
|||
/// <summary>
|
|||
/// Adds a handler attaching an access token obtained using the client
|
|||
/// credentials grant to the requests sent by the HTTP client.
|
|||
/// </summary>
|
|||
/// <param name="builder">The HTTP client builder.</param>
|
|||
/// <param name="request">The client access token request, if applicable.</param>
|
|||
/// <returns>The <see cref="IHttpClientBuilder"/> instance.</returns>
|
|||
public static IHttpClientBuilder AddOpenIddictBffClientAccessTokenHandler( |
|||
this IHttpClientBuilder builder, ClientAccessTokenRequest? request = null) |
|||
=> builder.AddOpenIddictBffAccessTokenHandler(OpenIddictClientAspNetCoreBffTokenType.Client, request); |
|||
|
|||
/// <summary>
|
|||
/// Adds a handler attaching the specified type of access token to the requests sent by the HTTP client.
|
|||
/// </summary>
|
|||
/// <param name="builder">The HTTP client builder.</param>
|
|||
/// <param name="type">The type of access token.</param>
|
|||
/// <param name="request">The client access token request, if applicable.</param>
|
|||
/// <returns>The <see cref="IHttpClientBuilder"/> instance.</returns>
|
|||
public static IHttpClientBuilder AddOpenIddictBffAccessTokenHandler(this IHttpClientBuilder builder, |
|||
OpenIddictClientAspNetCoreBffTokenType type, ClientAccessTokenRequest? request = null) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(builder); |
|||
|
|||
return builder.AddHttpMessageHandler(provider => new OpenIddictClientAspNetCoreBffAccessTokenHandler( |
|||
provider.GetRequiredService<IHttpContextAccessor>(), |
|||
provider.GetService<OpenIddictClientAspNetCoreBffTokenManager>() ?? |
|||
throw new InvalidOperationException(SR.GetResourceString(SR.ID0561)), |
|||
type, request)); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Registers the YARP transforms attaching the user or client access tokens to proxied requests
|
|||
/// (see <see cref="OpenIddictClientAspNetCoreBffConstants.Metadata.AccessToken"/>).
|
|||
/// </summary>
|
|||
/// <param name="builder">The reverse proxy builder.</param>
|
|||
/// <returns>The <see cref="IReverseProxyBuilder"/> instance.</returns>
|
|||
public static IReverseProxyBuilder AddOpenIddictBffTransforms(this IReverseProxyBuilder builder) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(builder); |
|||
|
|||
return builder.AddTransforms<OpenIddictClientAspNetCoreBffTransformProvider>(); |
|||
} |
|||
} |
|||
@ -0,0 +1,104 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
using Yarp.ReverseProxy.Configuration; |
|||
using Yarp.ReverseProxy.Model; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Exposes companion extensions for the OpenIddict backend-for-frontend (BFF) components.
|
|||
/// </summary>
|
|||
public static class OpenIddictClientAspNetCoreBffHelpers |
|||
{ |
|||
/// <summary>
|
|||
/// Determines whether the request contains the antiforgery header expected by the BFF components.
|
|||
/// </summary>
|
|||
/// <param name="context">The HTTP context.</param>
|
|||
/// <returns><see langword="true"/> if the antiforgery header is present and valid, <see langword="false"/> otherwise.</returns>
|
|||
public static bool HasValidAntiforgeryHeader(this HttpContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
var options = GetOptions(context); |
|||
|
|||
// Note: requiring a custom header forces cross-origin browsers to send a CORS preflight
|
|||
// request, which prevents cross-site request forgery attacks against the BFF endpoints.
|
|||
return context.Request.Headers.TryGetValue(options.AntiforgeryHeaderName, out var values) && |
|||
values.Count is 1 && string.Equals(values[0], options.AntiforgeryHeaderValue, StringComparison.Ordinal); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Determines whether the current request targets a BFF API endpoint (i.e a local endpoint marked using
|
|||
/// <c>AsOpenIddictBffApiEndpoint()</c> or a YARP route with an OpenIddict BFF access token metadata).
|
|||
/// </summary>
|
|||
/// <param name="context">The HTTP context.</param>
|
|||
/// <returns><see langword="true"/> if the request targets a BFF API endpoint, <see langword="false"/> otherwise.</returns>
|
|||
public static bool IsBffApiRequest(this HttpContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
var endpoint = context.GetEndpoint(); |
|||
if (endpoint is null) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
return endpoint.Metadata.GetMetadata<OpenIddictClientAspNetCoreBffApiEndpointMetadata>() is not null || |
|||
GetRouteConfig(context)?.Metadata?.ContainsKey(OpenIddictClientAspNetCoreBffConstants.Metadata.AccessToken) is true; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Resolves the YARP route configuration associated with the current request, if applicable.
|
|||
/// </summary>
|
|||
internal static RouteConfig? GetRouteConfig(HttpContext context) |
|||
=> context.GetEndpoint()?.Metadata.GetMetadata<RouteModel>()?.Config; |
|||
|
|||
/// <summary>
|
|||
/// Resolves the BFF options.
|
|||
/// </summary>
|
|||
internal static OpenIddictClientAspNetCoreBffOptions GetOptions(HttpContext context) |
|||
=> context.RequestServices.GetService<IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions>>()?.CurrentValue ?? |
|||
throw new InvalidOperationException(SR.GetResourceString(SR.ID0561)); |
|||
|
|||
/// <summary>
|
|||
/// Parses the specified BFF access token type.
|
|||
/// </summary>
|
|||
internal static bool TryParseTokenType(string? value, out OpenIddictClientAspNetCoreBffTokenType type) |
|||
{ |
|||
// Note: numeric values are deliberately not accepted.
|
|||
if (!string.IsNullOrEmpty(value) && !char.IsDigit(value[0]) && Enum.TryParse(value, ignoreCase: true, out type) && |
|||
Enum.IsDefined(type)) |
|||
{ |
|||
return true; |
|||
} |
|||
|
|||
type = OpenIddictClientAspNetCoreBffTokenType.None; |
|||
return false; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Determines whether the specified URL is a local URL (e.g "/path", but not "//host" or "/\host").
|
|||
/// </summary>
|
|||
internal static bool IsLocalUrl(string? url) => url switch |
|||
{ |
|||
null or { Length: 0 } => false, |
|||
|
|||
// "/" or "/path" but not "//" or "/\".
|
|||
['/'] => true, |
|||
['/', not ('/' or '\\'), ..] => !ContainsControlCharacters(url), |
|||
|
|||
// "~/" or "~/path" but not "~//" or "~/\".
|
|||
['~', '/'] => true, |
|||
['~', '/', not ('/' or '\\'), ..] => !ContainsControlCharacters(url), |
|||
|
|||
_ => false |
|||
}; |
|||
|
|||
private static bool ContainsControlCharacters(string value) => value.AsSpan().ContainsAnyInRange('\u0000', '\u001f'); |
|||
} |
|||
@ -0,0 +1,121 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.Collections.Concurrent; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Ensures a single asynchronous operation runs per key: concurrent callers using the same key share the same operation
|
|||
/// and, if a retention period is specified, successful results are returned to subsequent callers until it elapses.
|
|||
/// </summary>
|
|||
/// <typeparam name="TResult">The type of the result.</typeparam>
|
|||
internal sealed class OpenIddictClientAspNetCoreBffKeyedOperations<TResult> |
|||
{ |
|||
private readonly ConcurrentDictionary<string, Entry> _entries = new(StringComparer.Ordinal); |
|||
|
|||
/// <summary>
|
|||
/// Gets the number of tracked operations.
|
|||
/// </summary>
|
|||
public int Count => _entries.Count; |
|||
|
|||
/// <summary>
|
|||
/// Runs the operation associated with the specified key or joins the pending/retained operation, if applicable.
|
|||
/// </summary>
|
|||
/// <param name="key">The key.</param>
|
|||
/// <param name="factory">The operation factory.</param>
|
|||
/// <param name="retention">The period during which a successful result is retained.</param>
|
|||
/// <param name="provider">The time provider.</param>
|
|||
/// <returns>The result of the operation.</returns>
|
|||
public Task<TResult> RunAsync(string key, Func<Task<TResult>> factory, TimeSpan retention, TimeProvider provider) |
|||
{ |
|||
ArgumentException.ThrowIfNullOrEmpty(key); |
|||
ArgumentNullException.ThrowIfNull(factory); |
|||
ArgumentNullException.ThrowIfNull(provider); |
|||
|
|||
while (true) |
|||
{ |
|||
var now = provider.GetUtcNow(); |
|||
|
|||
if (_entries.TryGetValue(key, out var entry)) |
|||
{ |
|||
if (entry.ExpirationDate is not DateTimeOffset date || date > now) |
|||
{ |
|||
return entry.Operation.Value; |
|||
} |
|||
|
|||
// Remove the expired entry (unless it was already replaced by another caller) and try again.
|
|||
_entries.TryRemove(new KeyValuePair<string, Entry>(key, entry)); |
|||
continue; |
|||
} |
|||
|
|||
entry = new Entry(); |
|||
entry.Operation = new Lazy<Task<TResult>>(() => ExecuteAsync(key, entry, factory, retention, provider)); |
|||
|
|||
if (_entries.TryAdd(key, entry)) |
|||
{ |
|||
Purge(now); |
|||
|
|||
return entry.Operation.Value; |
|||
} |
|||
} |
|||
} |
|||
|
|||
private async Task<TResult> ExecuteAsync(string key, Entry entry, |
|||
Func<Task<TResult>> factory, TimeSpan retention, TimeProvider provider) |
|||
{ |
|||
try |
|||
{ |
|||
var result = await factory().ConfigureAwait(false); |
|||
|
|||
if (retention > TimeSpan.Zero) |
|||
{ |
|||
entry.ExpirationDate = provider.GetUtcNow() + retention; |
|||
} |
|||
|
|||
else |
|||
{ |
|||
_entries.TryRemove(new KeyValuePair<string, Entry>(key, entry)); |
|||
} |
|||
|
|||
return result; |
|||
} |
|||
|
|||
catch |
|||
{ |
|||
// Never retain failed operations so that subsequent callers can try again.
|
|||
_entries.TryRemove(new KeyValuePair<string, Entry>(key, entry)); |
|||
|
|||
throw; |
|||
} |
|||
} |
|||
|
|||
private void Purge(DateTimeOffset now) |
|||
{ |
|||
foreach (var entry in _entries) |
|||
{ |
|||
if (entry.Value.ExpirationDate is DateTimeOffset date && date <= now) |
|||
{ |
|||
_entries.TryRemove(entry); |
|||
} |
|||
} |
|||
} |
|||
|
|||
private sealed class Entry |
|||
{ |
|||
public Lazy<Task<TResult>> Operation { get; set; } = default!; |
|||
|
|||
private long _expiration; |
|||
|
|||
// Note: the expiration date is stored as UTC ticks (0 meaning "not completed or not retained")
|
|||
// to ensure it can be atomically read and written by concurrent threads.
|
|||
public DateTimeOffset? ExpirationDate |
|||
{ |
|||
get => Volatile.Read(ref _expiration) is long ticks and not 0 ? new DateTimeOffset(ticks, TimeSpan.Zero) : null; |
|||
set => Volatile.Write(ref _expiration, value?.UtcTicks ?? 0); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,172 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.Collections.Concurrent; |
|||
using System.Security.Claims; |
|||
using System.Text.Json; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Options; |
|||
using Microsoft.IdentityModel.JsonWebTokens; |
|||
using static OpenIddict.Client.AspNetCore.Bff.OpenIddictClientAspNetCoreBffModels; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Validates the logout tokens sent to the back-channel logout endpoint, as defined by
|
|||
/// <see href="https://openid.net/specs/openid-connect-backchannel-1_0.html#Validation">OpenID Connect Back-Channel Logout 1.0</see>.
|
|||
/// </summary>
|
|||
internal sealed class OpenIddictClientAspNetCoreBffLogoutTokenValidator |
|||
{ |
|||
private readonly ConcurrentDictionary<string, DateTimeOffset> _identifiers = new(StringComparer.Ordinal); |
|||
private readonly ILogger<OpenIddictClientAspNetCoreBffLogoutTokenValidator> _logger; |
|||
private readonly IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions> _options; |
|||
private readonly IOptionsMonitor<OpenIddictClientOptions> _clientOptions; |
|||
private readonly OpenIddictClientService _service; |
|||
|
|||
public OpenIddictClientAspNetCoreBffLogoutTokenValidator( |
|||
ILogger<OpenIddictClientAspNetCoreBffLogoutTokenValidator> logger, |
|||
IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions> options, |
|||
IOptionsMonitor<OpenIddictClientOptions> clientOptions, |
|||
OpenIddictClientService service) |
|||
{ |
|||
_logger = logger; |
|||
_options = options; |
|||
_clientOptions = clientOptions; |
|||
_service = service; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Validates the specified logout token.
|
|||
/// </summary>
|
|||
/// <param name="context">The HTTP context.</param>
|
|||
/// <param name="token">The logout token.</param>
|
|||
/// <returns>The back-channel logout notification, or <see langword="null"/> if the token is invalid.</returns>
|
|||
public async ValueTask<BackchannelLogoutNotification?> ValidateAsync(HttpContext context, string token) |
|||
{ |
|||
var handler = _clientOptions.CurrentValue.JsonWebTokenHandler; |
|||
if (!handler.CanReadToken(token)) |
|||
{ |
|||
return Fail("the token is not a JSON Web Token."); |
|||
} |
|||
|
|||
var unvalidated = handler.ReadJsonWebToken(token); |
|||
if (!Uri.TryCreate(unvalidated.Issuer, UriKind.Absolute, out var issuer)) |
|||
{ |
|||
return Fail("the issuer is missing or invalid."); |
|||
} |
|||
|
|||
// Resolve the client registration using the issuer and the audiences of the logout token.
|
|||
// Note: the audiences are used to disambiguate registrations sharing the same issuer.
|
|||
var audiences = unvalidated.Audiences.ToHashSet(StringComparer.Ordinal); |
|||
var registrations = (await _service.GetClientRegistrationsAsync(context.RequestAborted)) |
|||
.Where(registration => registration.Issuer is not null && !string.IsNullOrEmpty(registration.ClientId) && |
|||
string.Equals(registration.Issuer.AbsoluteUri.TrimEnd('/'), issuer.AbsoluteUri.TrimEnd('/'), StringComparison.Ordinal) && |
|||
audiences.Contains(registration.ClientId)) |
|||
.ToList(); |
|||
|
|||
if (registrations is not [OpenIddictClientRegistration registration]) |
|||
{ |
|||
return Fail("no unique client registration matches the issuer and audiences."); |
|||
} |
|||
|
|||
var configuration = await _service.GetServerConfigurationByRegistrationIdAsync( |
|||
registration.RegistrationId!, context.RequestAborted); |
|||
|
|||
var parameters = registration.TokenValidationParameters.Clone(); |
|||
var uri = (configuration.Issuer ?? registration.Issuer!).AbsoluteUri; |
|||
|
|||
parameters.ValidIssuers = [uri, uri.TrimEnd('/')]; |
|||
parameters.ValidateIssuer = true; |
|||
parameters.ValidAudiences = [registration.ClientId!]; |
|||
parameters.ValidateAudience = true; |
|||
parameters.IssuerSigningKeys = parameters.IssuerSigningKeys?.Concat(configuration.SigningKeys) ?? configuration.SigningKeys; |
|||
parameters.ValidTypes = |
|||
[ |
|||
JsonWebTokenTypes.LogoutToken, |
|||
JsonWebTokenTypes.Prefixes.Application + JsonWebTokenTypes.LogoutToken, |
|||
JsonWebTokenTypes.GenericJsonWebToken |
|||
]; |
|||
|
|||
// Note: "exp" was not required by early versions of the specification.
|
|||
parameters.RequireExpirationTime = false; |
|||
parameters.ValidateLifetime = true; |
|||
|
|||
var result = await handler.ValidateTokenAsync(token, parameters); |
|||
if (!result.IsValid || result.SecurityToken is not JsonWebToken jwt) |
|||
{ |
|||
return Fail(result.Exception?.Message ?? "the token cannot be validated."); |
|||
} |
|||
|
|||
if (!jwt.TryGetPayloadValue<JsonElement>(Claims.Events, out var events) || events.ValueKind is not JsonValueKind.Object || |
|||
!events.TryGetProperty(OpenIddictClientAspNetCoreBffConstants.Events.BackchannelLogout, out var value) || |
|||
value.ValueKind is not JsonValueKind.Object) |
|||
{ |
|||
return Fail("the events claim is missing or invalid."); |
|||
} |
|||
|
|||
if (jwt.TryGetPayloadValue<object>(Claims.Nonce, out _)) |
|||
{ |
|||
return Fail("the token contains a nonce claim."); |
|||
} |
|||
|
|||
if (!jwt.TryGetPayloadValue<long>(Claims.IssuedAt, out _)) |
|||
{ |
|||
return Fail("the iat claim is missing."); |
|||
} |
|||
|
|||
var subject = jwt.TryGetPayloadValue<string>(Claims.Subject, out var sub) && !string.IsNullOrEmpty(sub) ? sub : null; |
|||
var session = jwt.TryGetPayloadValue<string>(Claims.SessionId, out var sid) && !string.IsNullOrEmpty(sid) ? sid : null; |
|||
if (subject is null && session is null) |
|||
{ |
|||
return Fail("the sub and sid claims are both missing."); |
|||
} |
|||
|
|||
if (string.IsNullOrEmpty(jwt.Id)) |
|||
{ |
|||
return Fail("the jti claim is missing."); |
|||
} |
|||
|
|||
// Prevent replay attacks by rejecting logout tokens whose identifier was already seen.
|
|||
var now = _clientOptions.CurrentValue.TimeProvider.GetUtcNow(); |
|||
var expiration = now + _options.CurrentValue.LogoutTokenReplayCacheLifetime; |
|||
if (jwt.ValidTo > DateTime.MinValue && new DateTimeOffset(jwt.ValidTo, TimeSpan.Zero) > expiration) |
|||
{ |
|||
expiration = new DateTimeOffset(jwt.ValidTo, TimeSpan.Zero); |
|||
} |
|||
|
|||
foreach (var entry in _identifiers) |
|||
{ |
|||
if (entry.Value <= now) |
|||
{ |
|||
_identifiers.TryRemove(entry); |
|||
} |
|||
} |
|||
|
|||
if (!_identifiers.TryAdd(string.Concat(uri, "\n", jwt.Id), expiration)) |
|||
{ |
|||
return Fail("the token was already used."); |
|||
} |
|||
|
|||
_logger.LogInformation(6321, SR.GetResourceString(SR.ID6321), uri, subject, session); |
|||
|
|||
return new BackchannelLogoutNotification |
|||
{ |
|||
HttpContext = context, |
|||
Issuer = uri, |
|||
Principal = new ClaimsPrincipal(result.ClaimsIdentity), |
|||
Registration = registration, |
|||
SessionId = session, |
|||
Subject = subject |
|||
}; |
|||
|
|||
BackchannelLogoutNotification? Fail(string reason) |
|||
{ |
|||
_logger.LogInformation(6320, SR.GetResourceString(SR.ID6320), reason); |
|||
|
|||
return null; |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,156 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.Collections.Concurrent; |
|||
using System.Security.Claims; |
|||
using Microsoft.Extensions.Options; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Provides an in-memory server-side session store supporting back-channel logout.
|
|||
/// </summary>
|
|||
/// <remarks>
|
|||
/// Sessions are lost when the application restarts and are not shared between instances:
|
|||
/// multi-instance deployments must use a custom <see cref="IOpenIddictClientAspNetCoreBffSessionStore"/>.
|
|||
/// </remarks>
|
|||
public sealed class OpenIddictClientAspNetCoreBffMemorySessionStore : IOpenIddictClientAspNetCoreBffSessionStore |
|||
{ |
|||
private readonly ConcurrentDictionary<string, AuthenticationTicket> _tickets = new(StringComparer.Ordinal); |
|||
private readonly IOptionsMonitor<OpenIddictClientOptions> _options; |
|||
|
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="OpenIddictClientAspNetCoreBffMemorySessionStore"/> class.
|
|||
/// </summary>
|
|||
/// <param name="options">The OpenIddict client options.</param>
|
|||
public OpenIddictClientAspNetCoreBffMemorySessionStore(IOptionsMonitor<OpenIddictClientOptions> options) |
|||
=> _options = options ?? throw new ArgumentNullException(nameof(options)); |
|||
|
|||
/// <summary>
|
|||
/// Gets the number of sessions currently stored.
|
|||
/// </summary>
|
|||
public int Count => _tickets.Count; |
|||
|
|||
/// <inheritdoc/>
|
|||
public Task<string> StoreAsync(AuthenticationTicket ticket) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(ticket); |
|||
|
|||
var key = Guid.NewGuid().ToString("N"); |
|||
_tickets[key] = ticket; |
|||
|
|||
Purge(); |
|||
|
|||
return Task.FromResult(key); |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public Task RenewAsync(string key, AuthenticationTicket ticket) |
|||
{ |
|||
ArgumentException.ThrowIfNullOrEmpty(key); |
|||
ArgumentNullException.ThrowIfNull(ticket); |
|||
|
|||
// Note: sessions removed after a back-channel logout notification must not be resurrected.
|
|||
if (_tickets.TryGetValue(key, out var existing)) |
|||
{ |
|||
_tickets.TryUpdate(key, ticket, existing); |
|||
} |
|||
|
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public Task<AuthenticationTicket?> RetrieveAsync(string key) |
|||
{ |
|||
ArgumentException.ThrowIfNullOrEmpty(key); |
|||
|
|||
if (!_tickets.TryGetValue(key, out var ticket)) |
|||
{ |
|||
return Task.FromResult<AuthenticationTicket?>(null); |
|||
} |
|||
|
|||
if (IsExpired(ticket)) |
|||
{ |
|||
_tickets.TryRemove(new KeyValuePair<string, AuthenticationTicket>(key, ticket)); |
|||
|
|||
return Task.FromResult<AuthenticationTicket?>(null); |
|||
} |
|||
|
|||
return Task.FromResult<AuthenticationTicket?>(ticket); |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public Task RemoveAsync(string key) |
|||
{ |
|||
ArgumentException.ThrowIfNullOrEmpty(key); |
|||
|
|||
_tickets.TryRemove(key, out _); |
|||
|
|||
return Task.CompletedTask; |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public ValueTask<int> RemoveSessionsAsync(string registrationId, string? subject, |
|||
string? sessionId, CancellationToken cancellationToken) |
|||
{ |
|||
ArgumentException.ThrowIfNullOrEmpty(registrationId); |
|||
|
|||
if (string.IsNullOrEmpty(subject) && string.IsNullOrEmpty(sessionId)) |
|||
{ |
|||
return new(0); |
|||
} |
|||
|
|||
var count = 0; |
|||
|
|||
foreach (var entry in _tickets) |
|||
{ |
|||
cancellationToken.ThrowIfCancellationRequested(); |
|||
|
|||
if (Matches(entry.Value.Principal, registrationId, subject, sessionId) && _tickets.TryRemove(entry)) |
|||
{ |
|||
count++; |
|||
} |
|||
} |
|||
|
|||
return new(count); |
|||
} |
|||
|
|||
internal static bool Matches(ClaimsPrincipal principal, string registrationId, string? subject, string? sessionId) |
|||
{ |
|||
if (!string.Equals(principal.FindFirst(Claims.Private.RegistrationId)?.Value, registrationId, StringComparison.Ordinal)) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
if (!string.IsNullOrEmpty(subject) && !string.Equals(subject, (principal.FindFirst(Claims.Subject) ?? |
|||
principal.FindFirst(ClaimTypes.NameIdentifier))?.Value, StringComparison.Ordinal)) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
if (!string.IsNullOrEmpty(sessionId) && !string.Equals(sessionId, |
|||
principal.FindFirst(Claims.SessionId)?.Value, StringComparison.Ordinal)) |
|||
{ |
|||
return false; |
|||
} |
|||
|
|||
return true; |
|||
} |
|||
|
|||
private bool IsExpired(AuthenticationTicket ticket) => ticket.Properties.ExpiresUtc is DateTimeOffset date && |
|||
date <= _options.CurrentValue.TimeProvider.GetUtcNow(); |
|||
|
|||
private void Purge() |
|||
{ |
|||
foreach (var entry in _tickets) |
|||
{ |
|||
if (IsExpired(entry.Value)) |
|||
{ |
|||
_tickets.TryRemove(entry); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,74 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.ComponentModel; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Enforces the antiforgery header check on BFF API endpoints and rejects anonymous
|
|||
/// requests sent to YARP routes requiring a user access token.
|
|||
/// </summary>
|
|||
[EditorBrowsable(EditorBrowsableState.Advanced)] |
|||
public sealed class OpenIddictClientAspNetCoreBffMiddleware |
|||
{ |
|||
private readonly RequestDelegate _next; |
|||
|
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="OpenIddictClientAspNetCoreBffMiddleware"/> class.
|
|||
/// </summary>
|
|||
/// <param name="next">The next middleware in the pipeline.</param>
|
|||
public OpenIddictClientAspNetCoreBffMiddleware(RequestDelegate next) |
|||
=> _next = next ?? throw new ArgumentNullException(nameof(next)); |
|||
|
|||
/// <summary>
|
|||
/// Processes the request.
|
|||
/// </summary>
|
|||
/// <param name="context">The HTTP context.</param>
|
|||
/// <returns>A <see cref="Task"/> that can be used to monitor the asynchronous operation.</returns>
|
|||
public async Task InvokeAsync(HttpContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
var endpoint = context.GetEndpoint(); |
|||
if (endpoint is null) |
|||
{ |
|||
await _next(context); |
|||
return; |
|||
} |
|||
|
|||
var metadata = endpoint.Metadata.GetMetadata<OpenIddictClientAspNetCoreBffApiEndpointMetadata>(); |
|||
var route = OpenIddictClientAspNetCoreBffHelpers.GetRouteConfig(context)?.Metadata; |
|||
|
|||
var type = OpenIddictClientAspNetCoreBffTokenType.None; |
|||
var proxied = route is not null && route.TryGetValue(OpenIddictClientAspNetCoreBffConstants.Metadata.AccessToken, out var value) && |
|||
OpenIddictClientAspNetCoreBffHelpers.TryParseTokenType(value, out type); |
|||
|
|||
var check = (metadata is { DisableAntiforgeryCheck: false }) || (proxied && |
|||
!(route!.TryGetValue(OpenIddictClientAspNetCoreBffConstants.Metadata.DisableAntiforgeryCheck, out var disabled) && |
|||
bool.TryParse(disabled, out var result) && result)); |
|||
|
|||
if (check && !context.HasValidAntiforgeryHeader()) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
|||
return; |
|||
} |
|||
|
|||
if (proxied && type is OpenIddictClientAspNetCoreBffTokenType.User) |
|||
{ |
|||
var options = OpenIddictClientAspNetCoreBffHelpers.GetOptions(context); |
|||
|
|||
var authentication = await context.AuthenticateAsync(options.CookieScheme); |
|||
if (authentication is not { Succeeded: true }) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
|||
return; |
|||
} |
|||
} |
|||
|
|||
await _next(context); |
|||
} |
|||
} |
|||
@ -0,0 +1,98 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.Security.Claims; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Exposes the models used by the OpenIddict backend-for-frontend (BFF) components.
|
|||
/// </summary>
|
|||
public static class OpenIddictClientAspNetCoreBffModels |
|||
{ |
|||
/// <summary>
|
|||
/// Represents an access token that can be attached to requests sent to remote APIs.
|
|||
/// </summary>
|
|||
public sealed record class AccessToken |
|||
{ |
|||
/// <summary>
|
|||
/// Gets or sets the access token.
|
|||
/// </summary>
|
|||
public required string Value { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the type of the access token (e.g "Bearer" or "DPoP"), if available.
|
|||
/// </summary>
|
|||
public string? TokenType { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the expiration date of the access token, if available.
|
|||
/// </summary>
|
|||
public DateTimeOffset? ExpirationDate { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the identifier of the client registration used to obtain the access token, if available.
|
|||
/// </summary>
|
|||
public string? RegistrationId { get; init; } |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents a request for an access token obtained using the client credentials grant.
|
|||
/// </summary>
|
|||
public sealed record class ClientAccessTokenRequest |
|||
{ |
|||
/// <summary>
|
|||
/// Gets or sets the identifier of the client registration, if applicable.
|
|||
/// </summary>
|
|||
public string? RegistrationId { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the scopes, if applicable.
|
|||
/// </summary>
|
|||
public List<string>? Scopes { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the resources, if applicable.
|
|||
/// </summary>
|
|||
public List<string>? Resources { get; init; } |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents a validated back-channel logout notification.
|
|||
/// </summary>
|
|||
public sealed record class BackchannelLogoutNotification |
|||
{ |
|||
/// <summary>
|
|||
/// Gets or sets the HTTP context.
|
|||
/// </summary>
|
|||
public required HttpContext HttpContext { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the client registration associated with the issuer of the logout token.
|
|||
/// </summary>
|
|||
public required OpenIddictClientRegistration Registration { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the principal extracted from the validated logout token.
|
|||
/// </summary>
|
|||
public required ClaimsPrincipal Principal { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the issuer of the logout token.
|
|||
/// </summary>
|
|||
public required string Issuer { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the subject of the logout token, if available.
|
|||
/// </summary>
|
|||
public string? Subject { get; init; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the session identifier of the logout token, if available.
|
|||
/// </summary>
|
|||
public string? SessionId { get; init; } |
|||
} |
|||
} |
|||
@ -0,0 +1,99 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Provides various settings needed to configure the OpenIddict backend-for-frontend (BFF) components.
|
|||
/// </summary>
|
|||
public sealed class OpenIddictClientAspNetCoreBffOptions |
|||
{ |
|||
/// <summary>
|
|||
/// Gets or sets the name of the cookie authentication scheme storing the user session and tokens.
|
|||
/// If set to <see langword="null"/>, the default authentication/sign-in schemes are used and the
|
|||
/// automatic token refresh logic is attached to all the cookie authentication schemes.
|
|||
/// </summary>
|
|||
public string? CookieScheme { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets a boolean indicating whether the access tokens stored in the authentication cookie
|
|||
/// should NOT be automatically refreshed when they are about to expire.
|
|||
/// </summary>
|
|||
public bool DisableAutomaticTokenRefresh { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the margin applied to the expiration date of access tokens when determining
|
|||
/// whether they must be refreshed or renewed. By default, tokens are refreshed 1 minute before they expire.
|
|||
/// </summary>
|
|||
public TimeSpan AccessTokenRefreshMargin { get; set; } = TimeSpan.FromMinutes(1); |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the period during which the result of a refresh token request is kept in memory
|
|||
/// and returned to concurrent or subsequent requests still carrying the same refresh token
|
|||
/// (e.g requests sent by the browser before the renewed authentication cookie was received).
|
|||
/// By default, results are retained for 30 seconds. <see cref="TimeSpan.Zero"/> disables retention.
|
|||
/// </summary>
|
|||
public TimeSpan TokenRefreshResultRetentionPeriod { get; set; } = TimeSpan.FromSeconds(30); |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the name of the header that must be sent by the frontend application
|
|||
/// when calling the user endpoint and the API endpoints (as an antiforgery measure).
|
|||
/// </summary>
|
|||
public string AntiforgeryHeaderName { get; set; } = OpenIddictClientAspNetCoreBffConstants.Headers.Antiforgery; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the value of the antiforgery header.
|
|||
/// </summary>
|
|||
public string AntiforgeryHeaderValue { get; set; } = "1"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the path of the login endpoint.
|
|||
/// </summary>
|
|||
public PathString LoginPath { get; set; } = "/bff/login"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the path of the logout endpoint.
|
|||
/// </summary>
|
|||
public PathString LogoutPath { get; set; } = "/bff/logout"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the path of the user endpoint.
|
|||
/// </summary>
|
|||
public PathString UserPath { get; set; } = "/bff/user"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the path of the back-channel logout endpoint.
|
|||
/// </summary>
|
|||
public PathString BackchannelLogoutPath { get; set; } = "/bff/backchannel-logout"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the path of the redirection endpoint (login callback). Unless automatic
|
|||
/// endpoint registration is disabled, this path is added to the redirection endpoint URIs.
|
|||
/// </summary>
|
|||
public PathString RedirectionPath { get; set; } = "/bff/callback/login"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the path of the post-logout redirection endpoint (logout callback). Unless automatic
|
|||
/// endpoint registration is disabled, this path is added to the post-logout redirection endpoint URIs.
|
|||
/// </summary>
|
|||
public PathString PostLogoutRedirectionPath { get; set; } = "/bff/callback/logout"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets a boolean indicating whether the redirection and post-logout redirection paths should NOT be
|
|||
/// automatically added to the OpenIddict client options (and their pass-through mode automatically enabled).
|
|||
/// </summary>
|
|||
public bool DisableAutomaticEndpointRegistration { get; set; } |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the default return URL used when no local return URL was specified.
|
|||
/// </summary>
|
|||
public string DefaultReturnUrl { get; set; } = "/"; |
|||
|
|||
/// <summary>
|
|||
/// Gets or sets the lifetime of the logout token identifiers kept in memory to prevent replay attacks.
|
|||
/// </summary>
|
|||
public TimeSpan LogoutTokenReplayCacheLifetime { get; set; } = TimeSpan.FromMinutes(5); |
|||
} |
|||
@ -0,0 +1,36 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using Microsoft.AspNetCore.Authentication.Cookies; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Options; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Attaches the in-memory session store to the BFF cookie scheme (or to all the cookie schemes if no scheme was set).
|
|||
/// </summary>
|
|||
internal sealed class OpenIddictClientAspNetCoreBffSessionStoreConfiguration : IPostConfigureOptions<CookieAuthenticationOptions> |
|||
{ |
|||
private readonly IServiceProvider _provider; |
|||
|
|||
public OpenIddictClientAspNetCoreBffSessionStoreConfiguration(IServiceProvider provider) |
|||
=> _provider = provider ?? throw new ArgumentNullException(nameof(provider)); |
|||
|
|||
/// <inheritdoc/>
|
|||
public void PostConfigure(string? name, CookieAuthenticationOptions options) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(options); |
|||
|
|||
var scheme = _provider.GetRequiredService<IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions>>().CurrentValue.CookieScheme; |
|||
if (!string.IsNullOrEmpty(scheme) && !string.Equals(name, scheme, StringComparison.Ordinal)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
options.SessionStore ??= _provider.GetRequiredService<OpenIddictClientAspNetCoreBffMemorySessionStore>(); |
|||
} |
|||
} |
|||
@ -0,0 +1,67 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using Microsoft.AspNetCore.Authentication.Cookies; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Options; |
|||
using static OpenIddict.Client.AspNetCore.Bff.OpenIddictClientAspNetCoreBffModels; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Removes the sessions matching a back-channel logout notification from the session
|
|||
/// store attached to the BFF cookie scheme, when it implements <see cref="IOpenIddictClientAspNetCoreBffSessionStore"/>.
|
|||
/// </summary>
|
|||
public sealed class OpenIddictClientAspNetCoreBffSessionStoreLogoutHandler : IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler |
|||
{ |
|||
private readonly ILogger<OpenIddictClientAspNetCoreBffSessionStoreLogoutHandler> _logger; |
|||
private readonly IOptionsMonitor<CookieAuthenticationOptions> _cookieOptions; |
|||
private readonly IAuthenticationSchemeProvider _schemes; |
|||
private readonly IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions> _options; |
|||
|
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="OpenIddictClientAspNetCoreBffSessionStoreLogoutHandler"/> class.
|
|||
/// </summary>
|
|||
/// <param name="logger">The logger.</param>
|
|||
/// <param name="cookieOptions">The cookie authentication options.</param>
|
|||
/// <param name="schemes">The authentication scheme provider.</param>
|
|||
/// <param name="options">The BFF options.</param>
|
|||
public OpenIddictClientAspNetCoreBffSessionStoreLogoutHandler( |
|||
ILogger<OpenIddictClientAspNetCoreBffSessionStoreLogoutHandler> logger, |
|||
IOptionsMonitor<CookieAuthenticationOptions> cookieOptions, |
|||
IAuthenticationSchemeProvider schemes, |
|||
IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions> options) |
|||
{ |
|||
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
|||
_cookieOptions = cookieOptions ?? throw new ArgumentNullException(nameof(cookieOptions)); |
|||
_schemes = schemes ?? throw new ArgumentNullException(nameof(schemes)); |
|||
_options = options ?? throw new ArgumentNullException(nameof(options)); |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public async ValueTask HandleAsync(BackchannelLogoutNotification notification, CancellationToken cancellationToken) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(notification); |
|||
|
|||
var scheme = _options.CurrentValue.CookieScheme ?? (await _schemes.GetDefaultAuthenticateSchemeAsync())?.Name; |
|||
if (string.IsNullOrEmpty(scheme) || string.IsNullOrEmpty(notification.Registration.RegistrationId)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
if (_cookieOptions.Get(scheme).SessionStore is not IOpenIddictClientAspNetCoreBffSessionStore store) |
|||
{ |
|||
_logger.LogWarning(6322, SR.GetResourceString(SR.ID6322), scheme); |
|||
|
|||
return; |
|||
} |
|||
|
|||
var count = await store.RemoveSessionsAsync(notification.Registration.RegistrationId, |
|||
notification.Subject, notification.SessionId, cancellationToken); |
|||
|
|||
_logger.LogInformation(6323, SR.GetResourceString(SR.ID6323), count, scheme); |
|||
} |
|||
} |
|||
@ -0,0 +1,343 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using System.Collections.Concurrent; |
|||
using System.Globalization; |
|||
using System.Net.Http.Headers; |
|||
using System.Security.Claims; |
|||
using System.Security.Cryptography; |
|||
using System.Text; |
|||
using Microsoft.AspNetCore.Authentication.Cookies; |
|||
using Microsoft.Extensions.Logging; |
|||
using Microsoft.Extensions.Options; |
|||
using Microsoft.IdentityModel.Tokens; |
|||
using static OpenIddict.Abstractions.OpenIddictExceptions; |
|||
using static OpenIddict.Client.AspNetCore.Bff.OpenIddictClientAspNetCoreBffModels; |
|||
using Properties = OpenIddict.Client.AspNetCore.OpenIddictClientAspNetCoreConstants.Properties; |
|||
using Tokens = OpenIddict.Client.AspNetCore.OpenIddictClientAspNetCoreConstants.Tokens; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Manages the user and client access tokens used by the OpenIddict backend-for-frontend (BFF) components.
|
|||
/// </summary>
|
|||
public class OpenIddictClientAspNetCoreBffTokenManager |
|||
{ |
|||
private readonly ConcurrentDictionary<string, AccessToken> _clientTokens = new(StringComparer.Ordinal); |
|||
private readonly OpenIddictClientAspNetCoreBffKeyedOperations<AccessToken> _clientOperations = new(); |
|||
private readonly OpenIddictClientAspNetCoreBffKeyedOperations<RefreshResult> _refreshOperations = new(); |
|||
private readonly ILogger<OpenIddictClientAspNetCoreBffTokenManager> _logger; |
|||
private readonly IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions> _options; |
|||
private readonly IOptionsMonitor<OpenIddictClientOptions> _clientOptions; |
|||
private readonly OpenIddictClientService _service; |
|||
|
|||
/// <summary>
|
|||
/// Creates a new instance of the <see cref="OpenIddictClientAspNetCoreBffTokenManager"/> class.
|
|||
/// </summary>
|
|||
/// <param name="logger">The logger.</param>
|
|||
/// <param name="options">The BFF options.</param>
|
|||
/// <param name="clientOptions">The OpenIddict client options.</param>
|
|||
/// <param name="service">The OpenIddict client service.</param>
|
|||
public OpenIddictClientAspNetCoreBffTokenManager( |
|||
ILogger<OpenIddictClientAspNetCoreBffTokenManager> logger, |
|||
IOptionsMonitor<OpenIddictClientAspNetCoreBffOptions> options, |
|||
IOptionsMonitor<OpenIddictClientOptions> clientOptions, |
|||
OpenIddictClientService service) |
|||
{ |
|||
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
|||
_options = options ?? throw new ArgumentNullException(nameof(options)); |
|||
_clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions)); |
|||
_service = service ?? throw new ArgumentNullException(nameof(service)); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Refreshes the access token stored in the authentication ticket if it is about to expire and a refresh token
|
|||
/// is available. When the refresh token is rejected by the authorization server, the principal is rejected.
|
|||
/// </summary>
|
|||
/// <remarks>
|
|||
/// This method is automatically invoked by the cookie authentication handler, unless
|
|||
/// <see cref="AuthenticationSchemeOptions.EventsType"/> is used, in which case
|
|||
/// it must be manually called from <see cref="CookieAuthenticationEvents.ValidatePrincipal"/>.
|
|||
/// </remarks>
|
|||
/// <param name="context">The cookie validation context.</param>
|
|||
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
|
|||
public virtual async ValueTask ValidatePrincipalAsync(CookieValidatePrincipalContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
var options = _options.CurrentValue; |
|||
if (options.DisableAutomaticTokenRefresh || context.Principal is null) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
var token = context.Properties.GetTokenValue(Tokens.RefreshToken); |
|||
if (string.IsNullOrEmpty(token)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
// Only refresh the access token if it is missing or about to expire. If the access token
|
|||
// is present but its expiration date is unknown, it is assumed to still be valid.
|
|||
if (!string.IsNullOrEmpty(context.Properties.GetTokenValue(Tokens.BackchannelAccessToken))) |
|||
{ |
|||
if (!TryParseDate(context.Properties.GetTokenValue(Tokens.BackchannelAccessTokenExpirationDate), out var date) || |
|||
date - options.AccessTokenRefreshMargin > _clientOptions.CurrentValue.TimeProvider.GetUtcNow()) |
|||
{ |
|||
return; |
|||
} |
|||
} |
|||
|
|||
_logger.LogDebug(6317, SR.GetResourceString(SR.ID6317)); |
|||
|
|||
var registration = GetRegistrationId(context.Principal, context.Properties); |
|||
|
|||
RefreshResult result; |
|||
|
|||
try |
|||
{ |
|||
// Note: the operation is keyed by the hash of the refresh token so that concurrent requests
|
|||
// carrying the same authentication cookie share the same token request (which is required
|
|||
// when the authorization server uses rolling refresh tokens) without keeping the raw token.
|
|||
result = await _refreshOperations.RunAsync( |
|||
key: ComputeHash(token), |
|||
factory: () => RefreshAsync(token, registration), |
|||
retention: options.TokenRefreshResultRetentionPeriod, |
|||
provider: _clientOptions.CurrentValue.TimeProvider).WaitAsync(context.HttpContext.RequestAborted); |
|||
} |
|||
|
|||
catch (ProtocolException exception) when (string.Equals(exception.Error, Errors.InvalidGrant, StringComparison.Ordinal)) |
|||
{ |
|||
_logger.LogInformation(6318, SR.GetResourceString(SR.ID6318), exception.Error, exception.ErrorDescription); |
|||
|
|||
context.RejectPrincipal(); |
|||
await context.HttpContext.SignOutAsync(context.Scheme.Name); |
|||
|
|||
return; |
|||
} |
|||
|
|||
catch (Exception exception) when (exception is not OperationCanceledException) |
|||
{ |
|||
_logger.LogWarning(6319, exception, SR.GetResourceString(SR.ID6319)); |
|||
|
|||
return; |
|||
} |
|||
|
|||
var tokens = context.Properties.GetTokens().ToList(); |
|||
|
|||
SetToken(tokens, Tokens.BackchannelAccessToken, result.AccessToken); |
|||
SetToken(tokens, Tokens.BackchannelAccessTokenExpirationDate, |
|||
result.ExpirationDate?.ToString("o", CultureInfo.InvariantCulture)); |
|||
SetToken(tokens, Tokens.BackchannelAccessTokenType, result.TokenType); |
|||
|
|||
// Only replace the refresh and identity tokens if new tokens were returned (and, for identity
|
|||
// tokens, if an identity token was initially stored in the ticket, to avoid increasing its size).
|
|||
if (!string.IsNullOrEmpty(result.RefreshToken)) |
|||
{ |
|||
SetToken(tokens, Tokens.RefreshToken, result.RefreshToken); |
|||
} |
|||
|
|||
if (!string.IsNullOrEmpty(result.IdentityToken) && |
|||
tokens.Exists(static token => string.Equals(token.Name, Tokens.BackchannelIdentityToken, StringComparison.Ordinal))) |
|||
{ |
|||
SetToken(tokens, Tokens.BackchannelIdentityToken, result.IdentityToken); |
|||
} |
|||
|
|||
context.Properties.StoreTokens(tokens); |
|||
context.ShouldRenew = true; |
|||
|
|||
static void SetToken(List<AuthenticationToken> tokens, string name, string? value) |
|||
{ |
|||
tokens.RemoveAll(token => string.Equals(token.Name, name, StringComparison.Ordinal)); |
|||
|
|||
if (!string.IsNullOrEmpty(value)) |
|||
{ |
|||
tokens.Add(new AuthenticationToken { Name = name, Value = value }); |
|||
} |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Sends a refresh token request and returns the resulting tokens.
|
|||
/// </summary>
|
|||
/// <param name="token">The refresh token.</param>
|
|||
/// <param name="registration">The client registration identifier, if available.</param>
|
|||
/// <returns>The result of the refresh operation.</returns>
|
|||
private async Task<RefreshResult> RefreshAsync(string token, string? registration) |
|||
{ |
|||
// Note: the operation may be shared by multiple requests: the cancellation
|
|||
// token of the request that initiated it is deliberately not flowed.
|
|||
var result = await _service.AuthenticateWithRefreshTokenAsync(new() |
|||
{ |
|||
DisableUserInfo = true, |
|||
RefreshToken = token, |
|||
RegistrationId = registration |
|||
}); |
|||
|
|||
return new RefreshResult( |
|||
AccessToken: result.AccessToken, |
|||
ExpirationDate: result.AccessTokenExpirationDate, |
|||
TokenType: result.TokenResponse.TokenType, |
|||
RefreshToken: result.RefreshToken, |
|||
IdentityToken: result.IdentityToken); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Resolves the access token of the user authenticated using the BFF cookie scheme, if available.
|
|||
/// If the access token is about to expire, it is automatically refreshed by the cookie handler.
|
|||
/// </summary>
|
|||
/// <param name="context">The HTTP context.</param>
|
|||
/// <returns>The access token, or <see langword="null"/> if no user access token is available.</returns>
|
|||
public virtual async ValueTask<AccessToken?> GetUserAccessTokenAsync(HttpContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
var result = await context.AuthenticateAsync(_options.CurrentValue.CookieScheme); |
|||
if (result is not { Succeeded: true, Properties: AuthenticationProperties properties }) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
var token = properties.GetTokenValue(Tokens.BackchannelAccessToken); |
|||
if (string.IsNullOrEmpty(token)) |
|||
{ |
|||
return null; |
|||
} |
|||
|
|||
return new AccessToken |
|||
{ |
|||
ExpirationDate = TryParseDate(properties.GetTokenValue(Tokens.BackchannelAccessTokenExpirationDate), out var date) ? date : null, |
|||
RegistrationId = GetRegistrationId(result.Principal, properties), |
|||
TokenType = properties.GetTokenValue(Tokens.BackchannelAccessTokenType), |
|||
Value = token |
|||
}; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Resolves an access token using the client credentials grant. Tokens are cached in memory
|
|||
/// until they are about to expire and concurrent requests share the same token request.
|
|||
/// </summary>
|
|||
/// <param name="request">The client access token request.</param>
|
|||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
|
|||
/// <returns>The access token.</returns>
|
|||
public virtual async ValueTask<AccessToken> GetClientAccessTokenAsync( |
|||
ClientAccessTokenRequest? request = null, CancellationToken cancellationToken = default) |
|||
{ |
|||
request ??= new(); |
|||
|
|||
var key = string.Join("\n", |
|||
request.RegistrationId ?? string.Empty, |
|||
string.Join(' ', (IEnumerable<string>?) request.Scopes?.Order(StringComparer.Ordinal) ?? []), |
|||
string.Join(' ', (IEnumerable<string>?) request.Resources?.Order(StringComparer.Ordinal) ?? [])); |
|||
|
|||
var provider = _clientOptions.CurrentValue.TimeProvider; |
|||
|
|||
if (_clientTokens.TryGetValue(key, out var token) && !IsExpiring(token)) |
|||
{ |
|||
return token; |
|||
} |
|||
|
|||
return await _clientOperations.RunAsync(key, async () => |
|||
{ |
|||
var result = await _service.AuthenticateWithClientCredentialsAsync(new() |
|||
{ |
|||
RegistrationId = request.RegistrationId, |
|||
Resources = request.Resources, |
|||
Scopes = request.Scopes |
|||
}); |
|||
|
|||
var token = new AccessToken |
|||
{ |
|||
ExpirationDate = result.AccessTokenExpirationDate, |
|||
RegistrationId = request.RegistrationId, |
|||
TokenType = result.TokenResponse.TokenType, |
|||
Value = result.AccessToken |
|||
}; |
|||
|
|||
// Tokens whose expiration date is unknown are never cached.
|
|||
if (token.ExpirationDate is not null) |
|||
{ |
|||
_clientTokens[key] = token; |
|||
} |
|||
|
|||
return token; |
|||
}, retention: TimeSpan.Zero, provider).WaitAsync(cancellationToken); |
|||
|
|||
bool IsExpiring(AccessToken token) => token.ExpirationDate is not DateTimeOffset date || |
|||
date - _options.CurrentValue.AccessTokenRefreshMargin <= provider.GetUtcNow(); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Attaches the specified access token to the HTTP request, using the "DPoP" authentication
|
|||
/// scheme and a DPoP proof when the token is a DPoP-bound token, or the "Bearer" scheme otherwise.
|
|||
/// </summary>
|
|||
/// <param name="request">The HTTP request.</param>
|
|||
/// <param name="token">The access token.</param>
|
|||
/// <param name="uri">The absolute target URI, if different from <see cref="HttpRequestMessage.RequestUri"/>.</param>
|
|||
/// <param name="nonce">The DPoP nonce returned by the resource server, if applicable.</param>
|
|||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
|
|||
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
|
|||
public virtual async ValueTask AttachAccessTokenAsync(HttpRequestMessage request, AccessToken token, |
|||
Uri? uri = null, string? nonce = null, CancellationToken cancellationToken = default) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(request); |
|||
ArgumentNullException.ThrowIfNull(token); |
|||
|
|||
request.Headers.Remove(OpenIddictClientAspNetCoreBffConstants.Headers.DPoP); |
|||
|
|||
if (!string.Equals(token.TokenType, TokenTypes.DPoP, StringComparison.OrdinalIgnoreCase)) |
|||
{ |
|||
request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.Bearer, token.Value); |
|||
|
|||
return; |
|||
} |
|||
|
|||
uri ??= request.RequestUri; |
|||
|
|||
if (uri is not { IsAbsoluteUri: true }) |
|||
{ |
|||
throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof(uri)); |
|||
} |
|||
|
|||
var registration = !string.IsNullOrEmpty(token.RegistrationId) |
|||
? await _service.GetClientRegistrationByIdAsync(token.RegistrationId, cancellationToken) |
|||
: (await _service.GetClientRegistrationsAsync(cancellationToken)) switch |
|||
{ |
|||
[OpenIddictClientRegistration value] => value, |
|||
[] => throw new InvalidOperationException(SR.GetResourceString(SR.ID0304)), |
|||
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0305)) |
|||
}; |
|||
|
|||
var proof = await _service.CreateDPoPProofAsync(registration, request.Method.Method, |
|||
uri, token.Value, nonce, cancellationToken); |
|||
|
|||
request.Headers.Authorization = new AuthenticationHeaderValue(Schemes.DPoP, token.Value); |
|||
request.Headers.TryAddWithoutValidation(OpenIddictClientAspNetCoreBffConstants.Headers.DPoP, proof); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Resolves the client registration identifier associated with the specified ticket.
|
|||
/// </summary>
|
|||
internal static string? GetRegistrationId(ClaimsPrincipal? principal, AuthenticationProperties? properties) |
|||
=> principal?.FindFirst(Claims.Private.RegistrationId)?.Value is { Length: > 0 } identifier ? identifier : |
|||
properties?.Items.TryGetValue(Properties.RegistrationId, out var value) is true && !string.IsNullOrEmpty(value) ? value : null; |
|||
|
|||
private static bool TryParseDate(string? value, out DateTimeOffset date) |
|||
=> DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out date); |
|||
|
|||
private static string ComputeHash(string token) |
|||
=> Base64UrlEncoder.Encode(SHA256.HashData(Encoding.UTF8.GetBytes(token))); |
|||
|
|||
/// <summary>
|
|||
/// Represents the result of a refresh token request.
|
|||
/// </summary>
|
|||
private sealed record class RefreshResult( |
|||
string AccessToken, |
|||
DateTimeOffset? ExpirationDate, |
|||
string? TokenType, |
|||
string? RefreshToken, |
|||
string? IdentityToken); |
|||
} |
|||
@ -0,0 +1,39 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Represents the type of access token attached to requests sent to remote APIs.
|
|||
/// </summary>
|
|||
public enum OpenIddictClientAspNetCoreBffTokenType |
|||
{ |
|||
/// <summary>
|
|||
/// No access token is attached.
|
|||
/// </summary>
|
|||
None = 0, |
|||
|
|||
/// <summary>
|
|||
/// The access token of the authenticated user is attached. Anonymous requests are rejected.
|
|||
/// </summary>
|
|||
User = 1, |
|||
|
|||
/// <summary>
|
|||
/// The access token of the authenticated user is attached, if available. Anonymous requests are allowed.
|
|||
/// </summary>
|
|||
OptionalUser = 2, |
|||
|
|||
/// <summary>
|
|||
/// An access token obtained by the client application using the client credentials grant is attached.
|
|||
/// </summary>
|
|||
Client = 3, |
|||
|
|||
/// <summary>
|
|||
/// The access token of the authenticated user is attached, if available.
|
|||
/// Otherwise, an access token obtained using the client credentials grant is attached.
|
|||
/// </summary>
|
|||
UserOrClient = 4 |
|||
} |
|||
@ -0,0 +1,114 @@ |
|||
/* |
|||
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
|
|||
* See https://github.com/openiddict/openiddict-core for more information concerning
|
|||
* the license and the contributors participating to this project. |
|||
*/ |
|||
|
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Net.Http.Headers; |
|||
using Yarp.ReverseProxy.Forwarder; |
|||
using Yarp.ReverseProxy.Transforms; |
|||
using Yarp.ReverseProxy.Transforms.Builder; |
|||
using static OpenIddict.Client.AspNetCore.Bff.OpenIddictClientAspNetCoreBffModels; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff; |
|||
|
|||
/// <summary>
|
|||
/// Represents a YARP transform provider attaching the user or client access token to the requests
|
|||
/// proxied through the routes whose <see cref="OpenIddictClientAspNetCoreBffConstants.Metadata.AccessToken"/>
|
|||
/// metadata is set, and removing the cookies sent by the browser from these requests.
|
|||
/// </summary>
|
|||
public sealed class OpenIddictClientAspNetCoreBffTransformProvider : ITransformProvider |
|||
{ |
|||
/// <inheritdoc/>
|
|||
public void ValidateRoute(TransformRouteValidationContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
if (context.Route.Metadata?.TryGetValue(OpenIddictClientAspNetCoreBffConstants.Metadata.AccessToken, out var value) is true && |
|||
!OpenIddictClientAspNetCoreBffHelpers.TryParseTokenType(value, out _)) |
|||
{ |
|||
context.Errors.Add(new InvalidOperationException(SR.FormatID0562( |
|||
OpenIddictClientAspNetCoreBffConstants.Metadata.AccessToken, context.Route.RouteId, value))); |
|||
} |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public void ValidateCluster(TransformClusterValidationContext context) |
|||
{ |
|||
} |
|||
|
|||
/// <inheritdoc/>
|
|||
public void Apply(TransformBuilderContext context) |
|||
{ |
|||
ArgumentNullException.ThrowIfNull(context); |
|||
|
|||
var metadata = context.Route.Metadata; |
|||
if (metadata is null || !metadata.TryGetValue(OpenIddictClientAspNetCoreBffConstants.Metadata.AccessToken, out var value) || |
|||
!OpenIddictClientAspNetCoreBffHelpers.TryParseTokenType(value, out var type)) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
// Never forward the cookies (that include the authentication cookie) to the remote API.
|
|||
context.AddRequestHeaderRemove(OpenIddictClientAspNetCoreBffConstants.Headers.Cookie); |
|||
|
|||
if (type is OpenIddictClientAspNetCoreBffTokenType.None) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
var request = new ClientAccessTokenRequest |
|||
{ |
|||
RegistrationId = metadata.TryGetValue(OpenIddictClientAspNetCoreBffConstants.Metadata.RegistrationId, out var registration) && |
|||
!string.IsNullOrEmpty(registration) ? registration : null, |
|||
Scopes = metadata.TryGetValue(OpenIddictClientAspNetCoreBffConstants.Metadata.Scopes, out var scopes) && |
|||
!string.IsNullOrEmpty(scopes) ? [.. scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries)] : null |
|||
}; |
|||
|
|||
context.AddRequestTransform(context => ApplyAccessTokenAsync(context, type, request)); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Attaches the access token to the proxied request.
|
|||
/// </summary>
|
|||
/// <param name="context">The request transform context.</param>
|
|||
/// <param name="type">The type of access token.</param>
|
|||
/// <param name="request">The client access token request.</param>
|
|||
/// <returns>A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.</returns>
|
|||
internal static async ValueTask ApplyAccessTokenAsync(RequestTransformContext context, |
|||
OpenIddictClientAspNetCoreBffTokenType type, ClientAccessTokenRequest request) |
|||
{ |
|||
var manager = context.HttpContext.RequestServices.GetService<OpenIddictClientAspNetCoreBffTokenManager>() ?? |
|||
throw new InvalidOperationException(SR.GetResourceString(SR.ID0561)); |
|||
|
|||
// Remove the authorization header potentially sent by the browser.
|
|||
RequestTransform.RemoveHeader(context, HeaderNames.Authorization); |
|||
|
|||
var token = type switch |
|||
{ |
|||
OpenIddictClientAspNetCoreBffTokenType.User or OpenIddictClientAspNetCoreBffTokenType.OptionalUser |
|||
=> await manager.GetUserAccessTokenAsync(context.HttpContext), |
|||
|
|||
OpenIddictClientAspNetCoreBffTokenType.Client |
|||
=> await manager.GetClientAccessTokenAsync(request, context.CancellationToken), |
|||
|
|||
OpenIddictClientAspNetCoreBffTokenType.UserOrClient |
|||
=> await manager.GetUserAccessTokenAsync(context.HttpContext) ?? |
|||
await manager.GetClientAccessTokenAsync(request, context.CancellationToken), |
|||
|
|||
_ => null |
|||
}; |
|||
|
|||
if (token is null) |
|||
{ |
|||
return; |
|||
} |
|||
|
|||
// Note: the request URI is computed by YARP after the request transforms are applied.
|
|||
var uri = context.ProxyRequest.RequestUri is { IsAbsoluteUri: true } value ? value : |
|||
RequestUtilities.MakeDestinationAddress(context.DestinationPrefix, context.Path, context.Query.QueryString); |
|||
|
|||
await manager.AttachAccessTokenAsync(context.ProxyRequest, token, uri, cancellationToken: context.CancellationToken); |
|||
} |
|||
} |
|||
@ -0,0 +1,21 @@ |
|||
<Project Sdk="Microsoft.NET.Sdk"> |
|||
|
|||
<PropertyGroup> |
|||
<TargetFrameworks>$(NetCoreTargetFrameworks)</TargetFrameworks> |
|||
</PropertyGroup> |
|||
|
|||
<ItemGroup> |
|||
<ProjectReference Include="..\..\src\OpenIddict.Client.AspNetCore.Bff\OpenIddict.Client.AspNetCore.Bff.csproj" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<PackageReference Include="Microsoft.AspNetCore.TestHost" /> |
|||
</ItemGroup> |
|||
|
|||
<ItemGroup> |
|||
<Using Include="OpenIddict.Abstractions" /> |
|||
<Using Include="OpenIddict.Abstractions.OpenIddictConstants" Static="true" /> |
|||
<Using Include="OpenIddict.Abstractions.OpenIddictResources" Alias="SR" /> |
|||
</ItemGroup> |
|||
|
|||
</Project> |
|||
@ -0,0 +1,655 @@ |
|||
using System.Net; |
|||
using System.Net.Http.Headers; |
|||
using System.Text.Json; |
|||
using Microsoft.AspNetCore.Builder; |
|||
using Microsoft.AspNetCore.Http; |
|||
using Microsoft.AspNetCore.WebUtilities; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.IdentityModel.JsonWebTokens; |
|||
using Microsoft.IdentityModel.Tokens; |
|||
using Xunit; |
|||
using Yarp.ReverseProxy.Configuration; |
|||
using Yarp.ReverseProxy.Forwarder; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff.Tests; |
|||
|
|||
public class OpenIddictClientAspNetCoreBffEndpointTests |
|||
{ |
|||
[Fact] |
|||
public async Task UserEndpoint_MissingAntiforgeryHeaderIsRejected() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddHours(1)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/bff/user", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); |
|||
Assert.Equal("no-store", response.Headers.CacheControl?.ToString()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task UserEndpoint_InvalidAntiforgeryHeaderValueIsRejected() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddHours(1)); |
|||
|
|||
using var request = new HttpRequestMessage(HttpMethod.Get, "/bff/user"); |
|||
request.Headers.Add("Cookie", cookie); |
|||
request.Headers.Add("X-CSRF", "0"); |
|||
|
|||
// Act
|
|||
using var response = await host.Client.SendAsync(request); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task UserEndpoint_CustomAntiforgeryHeaderIsHonored() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
bff: options => options.SetAntiforgeryHeader("X-Requested-With", "fetch")); |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddHours(1)); |
|||
|
|||
using var request = new HttpRequestMessage(HttpMethod.Get, "/bff/user"); |
|||
request.Headers.Add("Cookie", cookie); |
|||
request.Headers.Add("X-Requested-With", "fetch"); |
|||
|
|||
// Act
|
|||
using var response = await host.Client.SendAsync(request); |
|||
using var legacy = await host.SendAsync(HttpMethod.Get, "/bff/user", cookie, antiforgery: true); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); |
|||
Assert.Equal(HttpStatusCode.Unauthorized, legacy.StatusCode); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task UserEndpoint_AnonymousRequestIsRejected() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/bff/user", cookie: null, antiforgery: true); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task UserEndpoint_ClaimsAndLogoutUrlAreReturned() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddHours(1)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/bff/user", cookie, antiforgery: true); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); |
|||
|
|||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); |
|||
var claims = document.RootElement.EnumerateArray().ToDictionary( |
|||
static claim => claim.GetProperty("type").GetString()!, |
|||
static claim => claim.GetProperty("value").GetString(), StringComparer.Ordinal); |
|||
|
|||
Assert.Equal("Bob", claims[Claims.Subject]); |
|||
Assert.Equal("/bff/logout?sid=session", claims[OpenIddictClientAspNetCoreBffConstants.Claims.LogoutUrl]); |
|||
|
|||
// Tokens must never be returned to the browser.
|
|||
Assert.DoesNotContain(claims.Values, static value => value is "old_access_token" or "old_refresh_token"); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ApiEndpoint_AntiforgeryHeaderIsRequired() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(endpoints: routes => |
|||
{ |
|||
routes.MapGet("/api/data", static () => "data").AsOpenIddictBffApiEndpoint(); |
|||
routes.MapGet("/api/unprotected", static () => "data").AsOpenIddictBffApiEndpoint(disableAntiforgeryCheck: true); |
|||
}); |
|||
|
|||
// Act
|
|||
using var missing = await host.SendAsync(HttpMethod.Get, "/api/data", cookie: null); |
|||
using var valid = await host.SendAsync(HttpMethod.Get, "/api/data", cookie: null, antiforgery: true); |
|||
using var unprotected = await host.SendAsync(HttpMethod.Get, "/api/unprotected", cookie: null); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Unauthorized, missing.StatusCode); |
|||
Assert.Equal(HttpStatusCode.OK, valid.StatusCode); |
|||
Assert.Equal(HttpStatusCode.OK, unprotected.StatusCode); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ApiEndpoint_UnauthenticatedRequestReturns401InsteadOfRedirecting() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(endpoints: routes => |
|||
{ |
|||
routes.MapGet("/api/secure", static () => "data").RequireAuthorization().AsOpenIddictBffApiEndpoint(); |
|||
routes.MapGet("/page", static () => "data").RequireAuthorization(); |
|||
}); |
|||
|
|||
// Act
|
|||
using var api = await host.SendAsync(HttpMethod.Get, "/api/secure", cookie: null, antiforgery: true); |
|||
using var page = await host.SendAsync(HttpMethod.Get, "/page", cookie: null); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Unauthorized, api.StatusCode); |
|||
Assert.Equal(HttpStatusCode.Redirect, page.StatusCode); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task LoginEndpoint_UserAgentIsRedirectedToTheAuthorizationEndpoint() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/bff/login?provider=Contoso&returnUrl=%2Fapp", cookie: null); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); |
|||
|
|||
var location = response.Headers.Location!; |
|||
Assert.Equal("https://contoso.com/connect/authorize", location.GetLeftPart(UriPartial.Path)); |
|||
|
|||
var parameters = QueryHelpers.ParseQuery(location.Query); |
|||
Assert.Equal("Fabrikam", parameters[Parameters.ClientId]); |
|||
Assert.Equal("http://localhost/bff/callback/login", parameters[Parameters.RedirectUri]); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task LoginCallbackEndpoint_UserIsSignedInWithTheReturnedTokens() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(endpoints: routes => |
|||
routes.MapGet("/test/token_type", static async (HttpContext context, OpenIddictClientAspNetCoreBffTokenManager manager) => |
|||
(await manager.GetUserAccessTokenAsync(context))?.TokenType)); |
|||
|
|||
using var challenge = await host.SendAsync(HttpMethod.Get, "/bff/login?returnUrl=%2Fapp", cookie: null); |
|||
Assert.Equal(HttpStatusCode.Redirect, challenge.StatusCode); |
|||
|
|||
var parameters = QueryHelpers.ParseQuery(challenge.Headers.Location!.Query); |
|||
|
|||
host.Endpoint.Handler = request => |
|||
{ |
|||
Assert.Equal(GrantTypes.AuthorizationCode, request.GrantType); |
|||
Assert.Equal("authorization_code", request.Code); |
|||
|
|||
var now = DateTime.UtcNow; |
|||
|
|||
return Task.FromResult(new OpenIddictResponse |
|||
{ |
|||
AccessToken = "access_token", |
|||
ExpiresIn = 3600, |
|||
IdToken = parameters.TryGetValue(Parameters.Nonce, out var nonce) ? new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor |
|||
{ |
|||
Audience = "Fabrikam", |
|||
Claims = new Dictionary<string, object>(StringComparer.Ordinal) |
|||
{ |
|||
[Claims.Nonce] = nonce.ToString(), |
|||
[Claims.SessionId] = "session", |
|||
[Claims.Subject] = "Bob" |
|||
}, |
|||
Expires = now.AddMinutes(5), |
|||
IssuedAt = now, |
|||
Issuer = OpenIddictClientAspNetCoreBffTestHost.Issuer.AbsoluteUri, |
|||
SigningCredentials = new SigningCredentials(host.SigningKey, SecurityAlgorithms.RsaSha256) |
|||
}) : null, |
|||
RefreshToken = "refresh_token", |
|||
TokenType = TokenTypes.Bearer |
|||
}); |
|||
}; |
|||
|
|||
using var callback = new HttpRequestMessage(HttpMethod.Get, "/bff/callback/login?code=authorization_code&state=" + |
|||
Uri.EscapeDataString(parameters[Parameters.State]!)); |
|||
|
|||
foreach (var value in challenge.Headers.GetValues("Set-Cookie")) |
|||
{ |
|||
callback.Headers.Add("Cookie", value.Split(';')[0]); |
|||
} |
|||
|
|||
// Act
|
|||
using var response = await host.Client.SendAsync(callback); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); |
|||
Assert.Equal("/app", response.Headers.Location?.OriginalString); |
|||
|
|||
var cookie = OpenIddictClientAspNetCoreBffTestHost.GetCookie(response); |
|||
Assert.NotNull(cookie); |
|||
|
|||
using var token = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
using var type = await host.SendAsync(HttpMethod.Get, "/test/token_type", cookie); |
|||
using var refresh = await host.SendAsync(HttpMethod.Get, "/test/refresh_token", cookie); |
|||
using var user = await host.SendAsync(HttpMethod.Get, "/bff/user", cookie, antiforgery: true); |
|||
|
|||
Assert.Equal("access_token", await token.Content.ReadAsStringAsync()); |
|||
Assert.Equal(TokenTypes.Bearer, await type.Content.ReadAsStringAsync()); |
|||
Assert.Equal("refresh_token", await refresh.Content.ReadAsStringAsync()); |
|||
|
|||
using var document = JsonDocument.Parse(await user.Content.ReadAsStringAsync()); |
|||
var claims = document.RootElement.EnumerateArray().ToDictionary( |
|||
static claim => claim.GetProperty("type").GetString()!, |
|||
static claim => claim.GetProperty("value").GetString(), StringComparer.Ordinal); |
|||
|
|||
Assert.Equal("Bob", claims[Claims.Subject]); |
|||
Assert.Equal("Contoso", claims[Claims.Private.RegistrationId]); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData("/bff/login?returnUrl=https%3A%2F%2Fevil.com")] |
|||
[InlineData("/bff/login?returnUrl=%2F%2Fevil.com")] |
|||
[InlineData("/bff/login?returnUrl=%2F%5Cevil.com")] |
|||
[InlineData("/bff/login?provider=Unknown")] |
|||
[InlineData("/bff/logout?returnUrl=https%3A%2F%2Fevil.com")] |
|||
public async Task Endpoints_InvalidParametersAreRejected(string uri) |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, uri, cookie: null); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task LogoutEndpoint_SessionIdentifierIsRequired() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddHours(1)); |
|||
|
|||
// Act
|
|||
using var missing = await host.SendAsync(HttpMethod.Get, "/bff/logout", cookie); |
|||
using var invalid = await host.SendAsync(HttpMethod.Get, "/bff/logout?sid=other", cookie); |
|||
using var valid = await host.SendAsync(HttpMethod.Get, "/bff/logout?sid=session&returnUrl=%2Fbye", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.BadRequest, missing.StatusCode); |
|||
Assert.Equal(HttpStatusCode.BadRequest, invalid.StatusCode); |
|||
|
|||
Assert.Equal(HttpStatusCode.Redirect, valid.StatusCode); |
|||
Assert.Equal("/bye", valid.Headers.Location?.OriginalString); |
|||
Assert.Contains(valid.Headers.GetValues("Set-Cookie"), static value => |
|||
value.StartsWith(".AspNetCore.Cookies=;", StringComparison.Ordinal)); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task BackchannelLogoutEndpoint_MatchingSessionsAreRemovedFromTheSessionStore() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
bff: options => options.UseInMemorySessionStore()); |
|||
|
|||
var store = host.Services.GetRequiredService<OpenIddictClientAspNetCoreBffMemorySessionStore>(); |
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddHours(1)); |
|||
|
|||
Assert.Equal(1, store.Count); |
|||
|
|||
// Act
|
|||
using var response = await SendLogoutTokenAsync(host, CreateLogoutToken(host, sid: "session")); |
|||
using var token = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); |
|||
Assert.Equal(0, store.Count); |
|||
Assert.Equal(HttpStatusCode.Unauthorized, token.StatusCode); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task BackchannelLogoutEndpoint_NonMatchingSessionsAreKept() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
bff: options => options.UseInMemorySessionStore()); |
|||
|
|||
var store = host.Services.GetRequiredService<OpenIddictClientAspNetCoreBffMemorySessionStore>(); |
|||
await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddHours(1)); |
|||
|
|||
// Act
|
|||
using var response = await SendLogoutTokenAsync(host, CreateLogoutToken(host, sub: "Alice")); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); |
|||
Assert.Equal(1, store.Count); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task BackchannelLogoutEndpoint_CustomHandlersAreInvoked() |
|||
{ |
|||
// Arrange
|
|||
var handler = new RecordingLogoutHandler(); |
|||
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(services: services => |
|||
services.AddSingleton<IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler>(handler)); |
|||
|
|||
// Act
|
|||
using var response = await SendLogoutTokenAsync(host, CreateLogoutToken(host, sub: "Bob", sid: "session")); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); |
|||
|
|||
var notification = Assert.Single(handler.Notifications); |
|||
Assert.Equal("Bob", notification.Subject); |
|||
Assert.Equal("session", notification.SessionId); |
|||
Assert.Equal("Contoso", notification.Registration.RegistrationId); |
|||
} |
|||
|
|||
public static IEnumerable<object[]> InvalidLogoutTokens => |
|||
[ |
|||
["missing_events"], |
|||
["nonce"], |
|||
["no_subject"], |
|||
["wrong_audience"], |
|||
["wrong_key"], |
|||
["expired"], |
|||
["replayed"], |
|||
["not_a_jwt"] |
|||
]; |
|||
|
|||
[Theory] |
|||
[MemberData(nameof(InvalidLogoutTokens))] |
|||
public async Task BackchannelLogoutEndpoint_InvalidLogoutTokensAreRejected(string scenario) |
|||
{ |
|||
// Arrange
|
|||
var handler = new RecordingLogoutHandler(); |
|||
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(services: services => |
|||
services.AddSingleton<IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler>(handler)); |
|||
|
|||
var token = scenario switch |
|||
{ |
|||
"missing_events" => CreateLogoutToken(host, sid: "session", events: false), |
|||
"nonce" => CreateLogoutToken(host, sid: "session", nonce: true), |
|||
"no_subject" => CreateLogoutToken(host), |
|||
"wrong_audience" => CreateLogoutToken(host, sid: "session", audience: "Other"), |
|||
"wrong_key" => CreateLogoutToken(host, sid: "session", key: new RsaSecurityKey(System.Security.Cryptography.RSA.Create(2048))), |
|||
"expired" => CreateLogoutToken(host, sid: "session", expiration: DateTime.UtcNow.AddMinutes(-5)), |
|||
"replayed" => CreateLogoutToken(host, sid: "session", identifier: "replayed"), |
|||
_ => "not_a_jwt" |
|||
}; |
|||
|
|||
if (scenario is "replayed") |
|||
{ |
|||
using var first = await SendLogoutTokenAsync(host, token); |
|||
Assert.Equal(HttpStatusCode.OK, first.StatusCode); |
|||
handler.Notifications.Clear(); |
|||
} |
|||
|
|||
// Act
|
|||
using var response = await SendLogoutTokenAsync(host, token); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); |
|||
|
|||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); |
|||
Assert.Equal(Errors.InvalidRequest, document.RootElement.GetProperty(Parameters.Error).GetString()); |
|||
Assert.Empty(handler.Notifications); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task BackchannelLogoutEndpoint_MissingLogoutTokenIsRejected() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
|
|||
// Act
|
|||
using var response = await host.Client.PostAsync("/bff/backchannel-logout", new FormUrlEncodedContent([])); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); |
|||
|
|||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); |
|||
Assert.Equal(SR.GetResourceString(SR.ID2239), document.RootElement.GetProperty(Parameters.ErrorDescription).GetString()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task AccessTokenHandler_UserAccessTokenIsAttached() |
|||
{ |
|||
// Arrange
|
|||
var backend = new RecordingHandler(); |
|||
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
services: services => services.AddHttpClient("api") |
|||
.AddOpenIddictBffUserAccessTokenHandler() |
|||
.ConfigurePrimaryHttpMessageHandler(() => backend), |
|||
endpoints: routes => routes.MapGet("/test/call", static async (HttpContext context, IHttpClientFactory factory) => |
|||
{ |
|||
using var client = factory.CreateClient("api"); |
|||
using var response = await client.GetAsync(new Uri("https://api.contoso.com/resource")); |
|||
return (int) response.StatusCode; |
|||
})); |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddSeconds(10)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/call", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); |
|||
|
|||
// The access token was about to expire and must have been refreshed before being attached.
|
|||
var request = Assert.Single(backend.Requests); |
|||
Assert.Equal(new AuthenticationHeaderValue(Schemes.Bearer, "new_access_token"), request.Authorization); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task AccessTokenHandler_ClientAccessTokenIsAttachedAndCached() |
|||
{ |
|||
// Arrange
|
|||
var backend = new RecordingHandler(); |
|||
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
services: services => services.AddHttpClient("api") |
|||
.AddOpenIddictBffClientAccessTokenHandler(new() { Scopes = ["api"] }) |
|||
.ConfigurePrimaryHttpMessageHandler(() => backend)); |
|||
|
|||
var factory = host.Services.GetRequiredService<IHttpClientFactory>(); |
|||
|
|||
// Act
|
|||
for (var index = 0; index < 3; index++) |
|||
{ |
|||
using var client = factory.CreateClient("api"); |
|||
using var response = await client.GetAsync(new Uri("https://api.contoso.com/resource")); |
|||
} |
|||
|
|||
// Assert
|
|||
Assert.Equal(3, backend.Requests.Count); |
|||
Assert.All(backend.Requests, static request => |
|||
Assert.Equal(new AuthenticationHeaderValue(Schemes.Bearer, "new_access_token"), request.Authorization)); |
|||
|
|||
var token = Assert.Single(host.Endpoint.Requests); |
|||
Assert.Equal(GrantTypes.ClientCredentials, token.GrantType); |
|||
Assert.Equal("api", token.Scope); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ReverseProxy_UserAccessTokenIsAttachedAndCookiesAreRemoved() |
|||
{ |
|||
// Arrange
|
|||
var backend = new RecordingHandler(); |
|||
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
services: services => |
|||
{ |
|||
services.AddSingleton<IForwarderHttpClientFactory>(new RecordingForwarderFactory(backend)); |
|||
services.AddReverseProxy() |
|||
.LoadFromMemory( |
|||
[ |
|||
new RouteConfig |
|||
{ |
|||
RouteId = "user", |
|||
ClusterId = "api", |
|||
Match = new RouteMatch { Path = "/proxy/user/{**catch-all}" }, |
|||
Metadata = new Dictionary<string, string>(StringComparer.Ordinal) |
|||
{ |
|||
[OpenIddictClientAspNetCoreBffConstants.Metadata.AccessToken] = nameof(OpenIddictClientAspNetCoreBffTokenType.User) |
|||
} |
|||
}, |
|||
new RouteConfig |
|||
{ |
|||
RouteId = "anonymous", |
|||
ClusterId = "api", |
|||
Match = new RouteMatch { Path = "/proxy/anonymous/{**catch-all}" } |
|||
} |
|||
], |
|||
[ |
|||
new ClusterConfig |
|||
{ |
|||
ClusterId = "api", |
|||
Destinations = new Dictionary<string, DestinationConfig>(StringComparer.Ordinal) |
|||
{ |
|||
["api"] = new DestinationConfig { Address = "https://api.contoso.com/" } |
|||
} |
|||
} |
|||
]) |
|||
.AddOpenIddictBffTransforms(); |
|||
}, |
|||
endpoints: routes => routes.MapReverseProxy()); |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddHours(1)); |
|||
|
|||
// Act
|
|||
using var missing = await host.SendAsync(HttpMethod.Get, "/proxy/user/resource", cookie); |
|||
using var anonymous = await host.SendAsync(HttpMethod.Get, "/proxy/user/resource", cookie: null, antiforgery: true); |
|||
using var response = await host.SendAsync(HttpMethod.Get, "/proxy/user/resource?value=1", cookie, antiforgery: true); |
|||
using var other = await host.SendAsync(HttpMethod.Get, "/proxy/anonymous/resource", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Unauthorized, missing.StatusCode); |
|||
Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode); |
|||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); |
|||
Assert.Equal(HttpStatusCode.OK, other.StatusCode); |
|||
|
|||
Assert.Equal(2, backend.Requests.Count); |
|||
|
|||
var proxied = backend.Requests[0]; |
|||
Assert.Equal("https://api.contoso.com/proxy/user/resource?value=1", proxied.Uri); |
|||
Assert.Equal(new AuthenticationHeaderValue(Schemes.Bearer, "old_access_token"), proxied.Authorization); |
|||
Assert.False(proxied.HasCookies); |
|||
|
|||
// Routes without the BFF metadata are not affected by the BFF transforms.
|
|||
Assert.Null(backend.Requests[1].Authorization); |
|||
Assert.True(backend.Requests[1].HasCookies); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData("/")] |
|||
[InlineData("/path?query=value")] |
|||
[InlineData("~/path")] |
|||
public void IsLocalUrl_LocalUrlsAreAccepted(string url) |
|||
=> Assert.True(IsLocalUrl(url)); |
|||
|
|||
[Theory] |
|||
[InlineData("")] |
|||
[InlineData("//evil.com")] |
|||
[InlineData("/\\evil.com")] |
|||
[InlineData("~//evil.com")] |
|||
[InlineData("https://evil.com/")] |
|||
[InlineData("/path\r\nLocation: https://evil.com")] |
|||
public void IsLocalUrl_NonLocalUrlsAreRejected(string url) |
|||
=> Assert.False(IsLocalUrl(url)); |
|||
|
|||
private static bool IsLocalUrl(string url) |
|||
=> (bool) typeof(OpenIddictClientAspNetCoreBffHelpers) |
|||
.GetMethod("IsLocalUrl", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)! |
|||
.Invoke(obj: null, [url])!; |
|||
|
|||
private static string CreateLogoutToken(OpenIddictClientAspNetCoreBffTestHost host, string? sub = null, string? sid = null, |
|||
bool events = true, bool nonce = false, string audience = "Fabrikam", SecurityKey? key = null, |
|||
DateTime? expiration = null, string? identifier = null) |
|||
{ |
|||
var claims = new Dictionary<string, object>(StringComparer.Ordinal) |
|||
{ |
|||
[Claims.JwtId] = identifier ?? Guid.NewGuid().ToString() |
|||
}; |
|||
|
|||
if (sub is not null) |
|||
{ |
|||
claims[Claims.Subject] = sub; |
|||
} |
|||
|
|||
if (sid is not null) |
|||
{ |
|||
claims[Claims.SessionId] = sid; |
|||
} |
|||
|
|||
if (events) |
|||
{ |
|||
claims[Claims.Events] = new Dictionary<string, object>(StringComparer.Ordinal) |
|||
{ |
|||
[OpenIddictClientAspNetCoreBffConstants.Events.BackchannelLogout] = new Dictionary<string, object>(StringComparer.Ordinal) |
|||
}; |
|||
} |
|||
|
|||
if (nonce) |
|||
{ |
|||
claims[Claims.Nonce] = "nonce"; |
|||
} |
|||
|
|||
var now = DateTime.UtcNow; |
|||
|
|||
return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor |
|||
{ |
|||
Audience = audience, |
|||
Claims = claims, |
|||
Expires = expiration ?? now.AddMinutes(2), |
|||
IssuedAt = (expiration ?? now.AddMinutes(2)).AddMinutes(-2), |
|||
NotBefore = (expiration ?? now.AddMinutes(2)).AddMinutes(-2), |
|||
Issuer = OpenIddictClientAspNetCoreBffTestHost.Issuer.AbsoluteUri, |
|||
SigningCredentials = new SigningCredentials(key ?? host.SigningKey, SecurityAlgorithms.RsaSha256), |
|||
TokenType = JsonWebTokenTypes.LogoutToken |
|||
}); |
|||
} |
|||
|
|||
private static Task<HttpResponseMessage> SendLogoutTokenAsync(OpenIddictClientAspNetCoreBffTestHost host, string token) |
|||
=> host.Client.PostAsync("/bff/backchannel-logout", new FormUrlEncodedContent( |
|||
[new KeyValuePair<string, string>(Parameters.LogoutToken, token)])); |
|||
|
|||
private sealed class RecordingLogoutHandler : IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler |
|||
{ |
|||
public List<OpenIddictClientAspNetCoreBffModels.BackchannelLogoutNotification> Notifications { get; } = []; |
|||
|
|||
public ValueTask HandleAsync(OpenIddictClientAspNetCoreBffModels.BackchannelLogoutNotification notification, CancellationToken cancellationToken) |
|||
{ |
|||
Notifications.Add(notification); |
|||
return ValueTask.CompletedTask; |
|||
} |
|||
} |
|||
|
|||
private sealed record class RecordedRequest(string Uri, AuthenticationHeaderValue? Authorization, bool HasCookies); |
|||
|
|||
private sealed class RecordingHandler : HttpMessageHandler |
|||
{ |
|||
public List<RecordedRequest> Requests { get; } = []; |
|||
|
|||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
|||
{ |
|||
lock (Requests) |
|||
{ |
|||
Requests.Add(new RecordedRequest(request.RequestUri!.AbsoluteUri, request.Headers.Authorization, |
|||
request.Headers.Contains("Cookie"))); |
|||
} |
|||
|
|||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }); |
|||
} |
|||
} |
|||
|
|||
private sealed class RecordingForwarderFactory(HttpMessageHandler handler) : IForwarderHttpClientFactory |
|||
{ |
|||
public HttpMessageInvoker CreateClient(ForwarderHttpClientContext context) => new(handler, disposeHandler: false); |
|||
} |
|||
} |
|||
@ -0,0 +1,258 @@ |
|||
using System.Collections.Concurrent; |
|||
using System.Globalization; |
|||
using System.Security.Claims; |
|||
using System.Security.Cryptography; |
|||
using Microsoft.AspNetCore.Authentication; |
|||
using Microsoft.AspNetCore.Authentication.Cookies; |
|||
using Microsoft.AspNetCore.Builder; |
|||
using Microsoft.AspNetCore.Hosting; |
|||
using Microsoft.AspNetCore.Http; |
|||
using Microsoft.AspNetCore.Routing; |
|||
using Microsoft.AspNetCore.TestHost; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.Extensions.Hosting; |
|||
using Microsoft.IdentityModel.Tokens; |
|||
using static OpenIddict.Client.OpenIddictClientEvents; |
|||
using Tokens = OpenIddict.Client.AspNetCore.OpenIddictClientAspNetCoreConstants.Tokens; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff.Tests; |
|||
|
|||
/// <summary>
|
|||
/// Hosts a BFF application backed by a mocked authorization server token endpoint.
|
|||
/// </summary>
|
|||
public sealed class OpenIddictClientAspNetCoreBffTestHost : IAsyncDisposable |
|||
{ |
|||
public static readonly Uri Issuer = new("https://contoso.com/", UriKind.Absolute); |
|||
|
|||
private OpenIddictClientAspNetCoreBffTestHost(IHost host, TokenEndpoint endpoint, SecurityKey key) |
|||
{ |
|||
Host = host; |
|||
Endpoint = endpoint; |
|||
SigningKey = key; |
|||
Client = host.GetTestClient(); |
|||
} |
|||
|
|||
public IHost Host { get; } |
|||
|
|||
public HttpClient Client { get; } |
|||
|
|||
public TokenEndpoint Endpoint { get; } |
|||
|
|||
public SecurityKey SigningKey { get; } |
|||
|
|||
public IServiceProvider Services => Host.Services; |
|||
|
|||
public static async Task<OpenIddictClientAspNetCoreBffTestHost> CreateAsync( |
|||
Action<OpenIddictClientBuilder>? client = null, |
|||
Action<OpenIddictClientAspNetCoreBffBuilder>? bff = null, |
|||
Action<IServiceCollection>? services = null, |
|||
Action<IEndpointRouteBuilder>? endpoints = null) |
|||
{ |
|||
var endpoint = new TokenEndpoint(); |
|||
var key = new RsaSecurityKey(RSA.Create(2048)) { KeyId = "signing_key" }; |
|||
|
|||
var builder = new HostBuilder(); |
|||
|
|||
builder.ConfigureServices(collection => |
|||
{ |
|||
collection.AddRouting(); |
|||
collection.AddAuthorization(); |
|||
|
|||
collection.AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme) |
|||
.AddCookie(); |
|||
|
|||
collection.AddOpenIddict() |
|||
.AddClient(options => |
|||
{ |
|||
options.AllowAuthorizationCodeFlow() |
|||
.AllowClientCredentialsFlow() |
|||
.AllowRefreshTokenFlow(); |
|||
|
|||
options.DisableTokenStorage(); |
|||
|
|||
options.AddEphemeralEncryptionKey() |
|||
.AddEphemeralSigningKey(); |
|||
|
|||
options.AddRegistration(new OpenIddictClientRegistration |
|||
{ |
|||
ClientId = "Fabrikam", |
|||
ClientSecret = "7Fjfp0ZBr1KtDRbnfVdmIw", |
|||
Configuration = new OpenIddictConfiguration |
|||
{ |
|||
AuthorizationEndpoint = new Uri("https://contoso.com/connect/authorize", UriKind.Absolute), |
|||
CodeChallengeMethodsSupported = { CodeChallengeMethods.Sha256 }, |
|||
GrantTypesSupported = { GrantTypes.AuthorizationCode, GrantTypes.ClientCredentials, GrantTypes.RefreshToken }, |
|||
Issuer = Issuer, |
|||
ResponseModesSupported = { ResponseModes.Query }, |
|||
ResponseTypesSupported = { ResponseTypes.Code }, |
|||
SigningKeys = { key }, |
|||
TokenEndpoint = new Uri("https://contoso.com/connect/token", UriKind.Absolute), |
|||
TokenEndpointAuthMethodsSupported = { ClientAuthenticationMethods.ClientSecretPost } |
|||
}, |
|||
Issuer = Issuer, |
|||
ProviderName = "Contoso", |
|||
RedirectUri = new Uri("bff/callback/login", UriKind.Relative), |
|||
RegistrationId = "Contoso", |
|||
Scopes = { Scopes.OpenId } |
|||
}); |
|||
|
|||
options.UseAspNetCore() |
|||
.DisableTransportSecurityRequirement(); |
|||
|
|||
options.AddEventHandler<ExtractTokenResponseContext>(handler => handler.UseInlineHandler(endpoint.HandleAsync)); |
|||
|
|||
var host = options.UseBff(); |
|||
bff?.Invoke(host); |
|||
|
|||
client?.Invoke(options); |
|||
}); |
|||
|
|||
services?.Invoke(collection); |
|||
}); |
|||
|
|||
builder.ConfigureWebHost(options => |
|||
{ |
|||
options.UseTestServer(); |
|||
options.Configure(app => |
|||
{ |
|||
app.UseRouting(); |
|||
app.UseAuthentication(); |
|||
app.UseOpenIddictBff(); |
|||
app.UseAuthorization(); |
|||
|
|||
app.UseEndpoints(routes => |
|||
{ |
|||
routes.MapOpenIddictBffEndpoints(); |
|||
|
|||
// Signs in a user whose tokens are specified in the query string.
|
|||
routes.MapGet("/test/signin", async context => |
|||
{ |
|||
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, Claims.Name, Claims.Role); |
|||
identity.AddClaim(new Claim(Claims.Subject, "Bob")); |
|||
identity.AddClaim(new Claim(Claims.Name, "Bob le Magnifique")); |
|||
identity.AddClaim(new Claim(Claims.SessionId, "session")); |
|||
identity.AddClaim(new Claim(Claims.Private.RegistrationId, "Contoso")); |
|||
|
|||
var properties = new AuthenticationProperties(); |
|||
var tokens = new List<AuthenticationToken>(); |
|||
|
|||
foreach (var name in (string[]) [Tokens.BackchannelAccessToken, Tokens.BackchannelAccessTokenExpirationDate, |
|||
Tokens.BackchannelAccessTokenType, Tokens.RefreshToken]) |
|||
{ |
|||
if (!string.IsNullOrEmpty(context.Request.Query[name])) |
|||
{ |
|||
tokens.Add(new AuthenticationToken { Name = name, Value = context.Request.Query[name]! }); |
|||
} |
|||
} |
|||
|
|||
properties.StoreTokens(tokens); |
|||
|
|||
await context.SignInAsync(new ClaimsPrincipal(identity), properties); |
|||
}); |
|||
|
|||
// Returns the user access token or 401 if no token is available.
|
|||
routes.MapGet("/test/token", async context => |
|||
{ |
|||
var manager = context.RequestServices.GetRequiredService<OpenIddictClientAspNetCoreBffTokenManager>(); |
|||
|
|||
var token = await manager.GetUserAccessTokenAsync(context); |
|||
if (token is null) |
|||
{ |
|||
context.Response.StatusCode = StatusCodes.Status401Unauthorized; |
|||
return; |
|||
} |
|||
|
|||
await context.Response.WriteAsync(token.Value); |
|||
}); |
|||
|
|||
// Returns the refresh token stored in the ticket.
|
|||
routes.MapGet("/test/refresh_token", async context => |
|||
{ |
|||
var result = await context.AuthenticateAsync(); |
|||
await context.Response.WriteAsync(result.Properties?.GetTokenValue(Tokens.RefreshToken) ?? string.Empty); |
|||
}); |
|||
|
|||
endpoints?.Invoke(routes); |
|||
}); |
|||
}); |
|||
}); |
|||
|
|||
return new OpenIddictClientAspNetCoreBffTestHost(await builder.StartAsync(), endpoint, key); |
|||
} |
|||
|
|||
public static string FormatDate(DateTimeOffset date) => date.ToString("o", CultureInfo.InvariantCulture); |
|||
|
|||
/// <summary>
|
|||
/// Signs in a user and returns the authentication cookie.
|
|||
/// </summary>
|
|||
public async Task<string> SignInAsync(string? accessToken = "old_access_token", DateTimeOffset? expiration = null, |
|||
string? refreshToken = "old_refresh_token", string? type = null) |
|||
{ |
|||
var query = new Dictionary<string, string?>(StringComparer.Ordinal) |
|||
{ |
|||
[Tokens.BackchannelAccessToken] = accessToken, |
|||
[Tokens.BackchannelAccessTokenExpirationDate] = expiration is DateTimeOffset date ? FormatDate(date) : null, |
|||
[Tokens.BackchannelAccessTokenType] = type, |
|||
[Tokens.RefreshToken] = refreshToken |
|||
}; |
|||
|
|||
using var response = await Client.GetAsync(Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString("/test/signin", query)); |
|||
response.EnsureSuccessStatusCode(); |
|||
|
|||
return GetCookie(response) ?? throw new InvalidOperationException("No cookie was returned."); |
|||
} |
|||
|
|||
public static string? GetCookie(HttpResponseMessage response) |
|||
=> response.Headers.TryGetValues("Set-Cookie", out var values) |
|||
? values.Select(static value => value.Split(';')[0]) |
|||
.FirstOrDefault(static value => value.StartsWith(".AspNetCore.Cookies=", StringComparison.Ordinal)) |
|||
: null; |
|||
|
|||
public Task<HttpResponseMessage> SendAsync(HttpMethod method, string uri, string? cookie, bool antiforgery = false) |
|||
{ |
|||
var request = new HttpRequestMessage(method, uri); |
|||
|
|||
if (!string.IsNullOrEmpty(cookie)) |
|||
{ |
|||
request.Headers.Add("Cookie", cookie); |
|||
} |
|||
|
|||
if (antiforgery) |
|||
{ |
|||
request.Headers.Add("X-CSRF", "1"); |
|||
} |
|||
|
|||
return Client.SendAsync(request); |
|||
} |
|||
|
|||
public async ValueTask DisposeAsync() |
|||
{ |
|||
Client.Dispose(); |
|||
await Host.StopAsync(); |
|||
Host.Dispose(); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Represents the mocked token endpoint of the authorization server.
|
|||
/// </summary>
|
|||
public sealed class TokenEndpoint |
|||
{ |
|||
public ConcurrentQueue<OpenIddictRequest> Requests { get; } = new(); |
|||
|
|||
public Func<OpenIddictRequest, Task<OpenIddictResponse>> Handler { get; set; } = static request => |
|||
Task.FromResult(new OpenIddictResponse |
|||
{ |
|||
AccessToken = "new_access_token", |
|||
ExpiresIn = 3600, |
|||
RefreshToken = "new_refresh_token", |
|||
TokenType = TokenTypes.Bearer |
|||
}); |
|||
|
|||
public async ValueTask HandleAsync(ExtractTokenResponseContext context) |
|||
{ |
|||
Requests.Enqueue(context.Request); |
|||
|
|||
context.Response = await Handler(context.Request); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,319 @@ |
|||
using System.Net; |
|||
using Microsoft.Extensions.DependencyInjection; |
|||
using Microsoft.IdentityModel.Tokens; |
|||
using Xunit; |
|||
using static OpenIddict.Client.AspNetCore.Bff.OpenIddictClientAspNetCoreBffModels; |
|||
|
|||
namespace OpenIddict.Client.AspNetCore.Bff.Tests; |
|||
|
|||
public class OpenIddictClientAspNetCoreBffTokenRefreshTests |
|||
{ |
|||
[Fact] |
|||
public async Task ValidatePrincipal_ExpiringAccessTokenIsRefreshedAndTicketIsRenewed() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddSeconds(30)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.OK, response.StatusCode); |
|||
Assert.Equal("new_access_token", await response.Content.ReadAsStringAsync()); |
|||
|
|||
var request = Assert.Single(host.Endpoint.Requests); |
|||
Assert.Equal(GrantTypes.RefreshToken, request.GrantType); |
|||
Assert.Equal("old_refresh_token", request.RefreshToken); |
|||
|
|||
// The renewed cookie must contain the new access and refresh tokens and must not trigger another refresh.
|
|||
var renewed = OpenIddictClientAspNetCoreBffTestHost.GetCookie(response); |
|||
Assert.NotNull(renewed); |
|||
|
|||
using var token = await host.SendAsync(HttpMethod.Get, "/test/token", renewed); |
|||
using var refresh = await host.SendAsync(HttpMethod.Get, "/test/refresh_token", renewed); |
|||
|
|||
Assert.Equal("new_access_token", await token.Content.ReadAsStringAsync()); |
|||
Assert.Equal("new_refresh_token", await refresh.Content.ReadAsStringAsync()); |
|||
Assert.Single(host.Endpoint.Requests); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ValidatePrincipal_MissingAccessTokenIsRefreshed() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var cookie = await host.SignInAsync(accessToken: null); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal("new_access_token", await response.Content.ReadAsStringAsync()); |
|||
Assert.Single(host.Endpoint.Requests); |
|||
} |
|||
|
|||
[Theory] |
|||
[InlineData(true)] |
|||
[InlineData(false)] |
|||
public async Task ValidatePrincipal_ValidAccessTokenIsNotRefreshed(bool expiration) |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var cookie = await host.SignInAsync(expiration: expiration ? DateTimeOffset.UtcNow.AddHours(1) : null); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal("old_access_token", await response.Content.ReadAsStringAsync()); |
|||
Assert.Null(OpenIddictClientAspNetCoreBffTestHost.GetCookie(response)); |
|||
Assert.Empty(host.Endpoint.Requests); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ValidatePrincipal_AccessTokenIsNotRefreshedWithoutRefreshToken() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddMinutes(-5), refreshToken: null); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal("old_access_token", await response.Content.ReadAsStringAsync()); |
|||
Assert.Empty(host.Endpoint.Requests); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ValidatePrincipal_AccessTokenIsNotRefreshedWhenAutomaticRefreshIsDisabled() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
bff: options => options.DisableAutomaticTokenRefresh()); |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddMinutes(-5)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal("old_access_token", await response.Content.ReadAsStringAsync()); |
|||
Assert.Empty(host.Endpoint.Requests); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ValidatePrincipal_RefreshMarginIsHonored() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
bff: options => options.SetAccessTokenRefreshMargin(TimeSpan.FromMinutes(10))); |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddMinutes(5)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal("new_access_token", await response.Content.ReadAsStringAsync()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ValidatePrincipal_ConcurrentRequestsShareASingleRefreshTokenRequest() |
|||
{ |
|||
// Arrange
|
|||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
|||
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
host.Endpoint.Handler = async request => |
|||
{ |
|||
await release.Task; |
|||
|
|||
return new OpenIddictResponse |
|||
{ |
|||
AccessToken = "new_access_token", |
|||
ExpiresIn = 3600, |
|||
RefreshToken = "new_refresh_token", |
|||
TokenType = TokenTypes.Bearer |
|||
}; |
|||
}; |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddSeconds(-1)); |
|||
|
|||
// Act
|
|||
var tasks = Enumerable.Range(0, 8).Select(_ => host.SendAsync(HttpMethod.Get, "/test/token", cookie)).ToList(); |
|||
|
|||
await WaitUntilAsync(() => !host.Endpoint.Requests.IsEmpty); |
|||
await Task.Delay(100); |
|||
release.SetResult(); |
|||
|
|||
var responses = await Task.WhenAll(tasks); |
|||
|
|||
// Assert
|
|||
Assert.Single(host.Endpoint.Requests); |
|||
|
|||
foreach (var response in responses) |
|||
{ |
|||
Assert.Equal("new_access_token", await response.Content.ReadAsStringAsync()); |
|||
response.Dispose(); |
|||
} |
|||
|
|||
// Requests still carrying the old cookie shortly after the refresh reuse the retained result.
|
|||
using var late = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
Assert.Equal("new_access_token", await late.Content.ReadAsStringAsync()); |
|||
Assert.Single(host.Endpoint.Requests); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ValidatePrincipal_RejectedRefreshTokenSignsOutTheUser() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
host.Endpoint.Handler = static request => Task.FromResult(new OpenIddictResponse |
|||
{ |
|||
Error = Errors.InvalidGrant, |
|||
ErrorDescription = "The refresh token is no longer valid." |
|||
}); |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddSeconds(-1)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); |
|||
Assert.Contains(response.Headers.GetValues("Set-Cookie"), static value => |
|||
value.StartsWith(".AspNetCore.Cookies=;", StringComparison.Ordinal)); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ValidatePrincipal_TransientRefreshErrorKeepsThePrincipal() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
host.Endpoint.Handler = static request => Task.FromResult(new OpenIddictResponse |
|||
{ |
|||
Error = Errors.ServerError |
|||
}); |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddSeconds(-1)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
using var retry = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
|
|||
// Assert
|
|||
Assert.Equal("old_access_token", await response.Content.ReadAsStringAsync()); |
|||
Assert.Equal("old_access_token", await retry.Content.ReadAsStringAsync()); |
|||
|
|||
// Failed refresh operations are never retained.
|
|||
Assert.Equal(2, host.Endpoint.Requests.Count); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task ValidatePrincipal_DPoPTokenTypeIsStored() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
host.Endpoint.Handler = static request => Task.FromResult(new OpenIddictResponse |
|||
{ |
|||
AccessToken = "dpop_access_token", |
|||
ExpiresIn = 3600, |
|||
TokenType = TokenTypes.DPoP |
|||
}); |
|||
|
|||
var cookie = await host.SignInAsync(expiration: DateTimeOffset.UtcNow.AddSeconds(-1)); |
|||
|
|||
// Act
|
|||
using var response = await host.SendAsync(HttpMethod.Get, "/test/token", cookie); |
|||
var renewed = OpenIddictClientAspNetCoreBffTestHost.GetCookie(response); |
|||
|
|||
using var refresh = await host.SendAsync(HttpMethod.Get, "/test/refresh_token", renewed); |
|||
|
|||
// Assert
|
|||
Assert.Equal("dpop_access_token", await response.Content.ReadAsStringAsync()); |
|||
|
|||
// The refresh token is preserved when no new refresh token is returned.
|
|||
Assert.Equal("old_refresh_token", await refresh.Content.ReadAsStringAsync()); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task GetClientAccessTokenAsync_TokensAreCachedUntilTheyExpire() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var manager = host.Services.GetRequiredService<OpenIddictClientAspNetCoreBffTokenManager>(); |
|||
|
|||
// Act
|
|||
var first = await manager.GetClientAccessTokenAsync(new ClientAccessTokenRequest { Scopes = ["api"] }); |
|||
var second = await manager.GetClientAccessTokenAsync(new ClientAccessTokenRequest { Scopes = ["api"] }); |
|||
var other = await manager.GetClientAccessTokenAsync(new ClientAccessTokenRequest { Scopes = ["other"] }); |
|||
|
|||
// Assert
|
|||
Assert.Equal("new_access_token", first.Value); |
|||
Assert.Same(first, second); |
|||
Assert.NotSame(first, other); |
|||
Assert.Equal(2, host.Endpoint.Requests.Count); |
|||
Assert.All(host.Endpoint.Requests, static request => Assert.Equal(GrantTypes.ClientCredentials, request.GrantType)); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task AttachAccessTokenAsync_BearerTokenIsAttached() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync(); |
|||
var manager = host.Services.GetRequiredService<OpenIddictClientAspNetCoreBffTokenManager>(); |
|||
|
|||
using var request = new HttpRequestMessage(HttpMethod.Get, "https://api.contoso.com/resource"); |
|||
|
|||
// Act
|
|||
await manager.AttachAccessTokenAsync(request, new AccessToken { Value = "access_token", TokenType = TokenTypes.Bearer }); |
|||
|
|||
// Assert
|
|||
Assert.Equal(Schemes.Bearer, request.Headers.Authorization?.Scheme); |
|||
Assert.Equal("access_token", request.Headers.Authorization?.Parameter); |
|||
Assert.False(request.Headers.Contains("DPoP")); |
|||
} |
|||
|
|||
[Fact] |
|||
public async Task AttachAccessTokenAsync_DPoPProofIsAttachedToDPoPBoundTokens() |
|||
{ |
|||
// Arrange
|
|||
await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( |
|||
client: options => options.EnableDPoPTokenBinding()); |
|||
|
|||
var manager = host.Services.GetRequiredService<OpenIddictClientAspNetCoreBffTokenManager>(); |
|||
|
|||
using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.contoso.com/resource?query=value"); |
|||
|
|||
// Act
|
|||
await manager.AttachAccessTokenAsync(request, new AccessToken |
|||
{ |
|||
RegistrationId = "Contoso", |
|||
TokenType = TokenTypes.DPoP, |
|||
Value = "access_token" |
|||
}); |
|||
|
|||
// Assert
|
|||
Assert.Equal(Schemes.DPoP, request.Headers.Authorization?.Scheme); |
|||
Assert.Equal("access_token", request.Headers.Authorization?.Parameter); |
|||
|
|||
var proof = new Microsoft.IdentityModel.JsonWebTokens.JsonWebToken(Assert.Single(request.Headers.GetValues("DPoP"))); |
|||
Assert.Equal(JsonWebTokenTypes.DPoPProof, proof.Typ); |
|||
Assert.Equal("POST", proof.GetPayloadValue<string>(Claims.HttpMethod)); |
|||
Assert.Equal("https://api.contoso.com/resource", proof.GetPayloadValue<string>(Claims.HttpUri)); |
|||
Assert.Equal(Base64UrlEncoder.Encode(System.Security.Cryptography.SHA256.HashData("access_token"u8)), |
|||
proof.GetPayloadValue<string>(Claims.DPoPAccessTokenHash)); |
|||
} |
|||
|
|||
private static async Task WaitUntilAsync(Func<bool> condition) |
|||
{ |
|||
for (var attempt = 0; attempt < 500 && !condition(); attempt++) |
|||
{ |
|||
await Task.Delay(10); |
|||
} |
|||
|
|||
Assert.True(condition()); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue