Browse Source

Preserve stored redirect URIs and custom types when saving admin UI applications

- Render the original redirect URI strings so saving the form keeps exact-match registrations intact
- Keep stored application, client and consent types not known by the admin UI
- Filter the token list by authorization and link to it from the authorization details
pull/2549/head
pieroviano 2 months ago
parent
commit
bf6768bbf7
  1. 16
      src/OpenIddict.Server.AspNetCore.AdminUI/Components/Pages/ApplicationEditorPage.razor
  2. 8
      src/OpenIddict.Server.AspNetCore.AdminUI/Components/Pages/AuthorizationDetailsPage.razor
  3. 15
      src/OpenIddict.Server.AspNetCore.AdminUI/Components/Pages/TokenListPage.razor
  4. 1
      src/OpenIddict.Server.AspNetCore.AdminUI/OpenIddictServerAspNetCoreAdminUIConstants.cs
  5. 37
      src/OpenIddict.Server.AspNetCore.AdminUI/OpenIddictServerAspNetCoreAdminUIEndpoints.cs
  6. 15
      src/OpenIddict.Server.AspNetCore.AdminUI/OpenIddictServerAspNetCoreAdminUIForms.cs
  7. 154
      test/OpenIddict.Server.AspNetCore.AdminUI.Tests/OpenIddictServerAspNetCoreAdminUITests.cs

16
src/OpenIddict.Server.AspNetCore.AdminUI/Components/Pages/ApplicationEditorPage.razor

@ -26,6 +26,10 @@
<label for="client_type">Client type</label>
<select id="client_type" name="@FormFields.ClientType">
<option value="" selected="@(Descriptor.ClientType is null)">(not specified)</option>
@if (Descriptor.ClientType is { Length: > 0 } customClientType && !OpenIddictServerAspNetCoreAdminUIForms.KnownClientTypes.Contains(customClientType))
{
<option value="@customClientType" selected>@customClientType</option>
}
@foreach (var value in OpenIddictServerAspNetCoreAdminUIForms.KnownClientTypes)
{
<option value="@value" selected="@(Descriptor.ClientType == value)">@value</option>
@ -35,6 +39,10 @@
<label for="application_type">Application type</label>
<select id="application_type" name="@FormFields.ApplicationType">
<option value="" selected="@(Descriptor.ApplicationType is null)">(not specified)</option>
@if (Descriptor.ApplicationType is { Length: > 0 } customApplicationType && !OpenIddictServerAspNetCoreAdminUIForms.KnownApplicationTypes.Contains(customApplicationType))
{
<option value="@customApplicationType" selected>@customApplicationType</option>
}
@foreach (var value in OpenIddictServerAspNetCoreAdminUIForms.KnownApplicationTypes)
{
<option value="@value" selected="@(Descriptor.ApplicationType == value)">@value</option>
@ -44,6 +52,10 @@
<label for="consent_type">Consent type</label>
<select id="consent_type" name="@FormFields.ConsentType">
<option value="" selected="@(Descriptor.ConsentType is null)">(not specified)</option>
@if (Descriptor.ConsentType is { Length: > 0 } customConsentType && !OpenIddictServerAspNetCoreAdminUIForms.KnownConsentTypes.Contains(customConsentType))
{
<option value="@customConsentType" selected>@customConsentType</option>
}
@foreach (var value in OpenIddictServerAspNetCoreAdminUIForms.KnownConsentTypes)
{
<option value="@value" selected="@(Descriptor.ConsentType == value)">@value</option>
@ -66,10 +78,10 @@
<legend>Redirect URIs</legend>
<label for="redirect_uris">Redirect URIs (one per line)</label>
<textarea id="redirect_uris" name="@FormFields.RedirectUris" value="@Lines(Descriptor.RedirectUris.Select(static uri => uri.AbsoluteUri))"></textarea>
<textarea id="redirect_uris" name="@FormFields.RedirectUris" value="@Lines(Descriptor.RedirectUris.Select(static uri => uri.OriginalString))"></textarea>
<label for="post_logout_redirect_uris">Post-logout redirect URIs (one per line)</label>
<textarea id="post_logout_redirect_uris" name="@FormFields.PostLogoutRedirectUris" value="@Lines(Descriptor.PostLogoutRedirectUris.Select(static uri => uri.AbsoluteUri))"></textarea>
<textarea id="post_logout_redirect_uris" name="@FormFields.PostLogoutRedirectUris" value="@Lines(Descriptor.PostLogoutRedirectUris.Select(static uri => uri.OriginalString))"></textarea>
</fieldset>
<fieldset>

8
src/OpenIddict.Server.AspNetCore.AdminUI/Components/Pages/AuthorizationDetailsPage.razor

@ -58,7 +58,7 @@
{
<p class="oi-muted" role="note">
More tokens are attached to this authorization: only the first @Tokens.Count tokens are displayed.
<a href="@TokensUrl">Show the tokens of this subject and client</a>
<a href="@TokensUrl">Show all the tokens of this authorization</a>
</p>
}
@ -91,11 +91,7 @@
[Parameter] public string? Notice { get; set; }
private string TokensUrl => Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(BasePath + "/" + Paths.Tokens,
new Dictionary<string, string?>
{
[QueryStringParameters.Subject] = Descriptor.Subject,
[QueryStringParameters.Client] = Descriptor.ApplicationId is { Length: > 0 } id && ClientIds.TryGetValue(id, out var client) ? client : Descriptor.ApplicationId
}.Where(static pair => !string.IsNullOrEmpty(pair.Value)));
QueryStringParameters.Authorization, Id);
private string ItemUrl => BasePath + "/" + Paths.Authorizations + "/" + Uri.EscapeDataString(Id);
}

15
src/OpenIddict.Server.AspNetCore.AdminUI/Components/Pages/TokenListPage.razor

@ -1,4 +1,4 @@
@* Lists the tokens (payloads are never rendered), optionally filtered by subject, client, status and type. *@
@* Lists the tokens (payloads are never rendered), optionally filtered by subject, client, status, type and authorization. *@
@using static OpenIddict.Server.AspNetCore.AdminUI.OpenIddictServerAspNetCoreAdminUIFormatting
<AdminLayout BasePath="@BasePath" Title="Tokens" Section="@Paths.Tokens" Notice="@Notice">
@ -25,6 +25,13 @@
<label for="type">Type</label>
<input id="type" type="search" name="@QueryStringParameters.Type" value="@Type" />
</div>
@if (Authorization is not null)
{
<div>
<label for="authorization">Authorization</label>
<input id="authorization" type="search" name="@QueryStringParameters.Authorization" value="@Authorization" />
</div>
}
<button type="submit" class="oi-secondary">Filter</button>
</form>
@ -80,7 +87,8 @@
[QueryStringParameters.Subject] = Subject,
[QueryStringParameters.Client] = Client,
[QueryStringParameters.Status] = Status,
[QueryStringParameters.Type] = Type
[QueryStringParameters.Type] = Type,
[QueryStringParameters.Authorization] = Authorization
})" />
</AdminLayout>
@ -106,6 +114,9 @@
/// <summary>Gets or sets the type filter, if any.</summary>
[Parameter] public string? Type { get; set; }
/// <summary>Gets or sets the authorization filter, if any.</summary>
[Parameter] public string? Authorization { get; set; }
/// <summary>Gets or sets the current page number.</summary>
[Parameter] public int PageNumber { get; set; } = 1;

1
src/OpenIddict.Server.AspNetCore.AdminUI/OpenIddictServerAspNetCoreAdminUIConstants.cs

@ -55,6 +55,7 @@ public static class OpenIddictServerAspNetCoreAdminUIConstants
public static class QueryStringParameters
{
public const string Authorization = "authorization";
public const string Client = "client";
public const string Notice = "notice";
public const string Page = "page";

37
src/OpenIddict.Server.AspNetCore.AdminUI/OpenIddictServerAspNetCoreAdminUIEndpoints.cs

@ -612,12 +612,13 @@ internal sealed class OpenIddictServerAspNetCoreAdminUIEndpoints
var client = GetQuery(context, QueryStringParameters.Client);
var status = GetQuery(context, QueryStringParameters.Status);
var type = GetQuery(context, QueryStringParameters.Type);
var authorization = GetQuery(context, QueryStringParameters.Authorization);
List<(string Id, OpenIddictTokenDescriptor Descriptor)> items = [];
var next = false;
var (found, application) = await ResolveApplicationIdAsync(applications, client, context.RequestAborted);
if (found)
if (found && authorization is null)
{
await foreach (var token in Operations.ListTokensAsync(manager,
subject, application, status, type, size + 1, offset, context.RequestAborted))
@ -632,6 +633,39 @@ internal sealed class OpenIddictServerAspNetCoreAdminUIEndpoints
}
}
// Note: the token stores can't combine the authorization filter with the other filters:
// when an authorization identifier is specified, the tokens attached to the authorization
// are retrieved and the other filters (and the pagination) are applied in memory.
else if (found)
{
var skipped = 0;
await foreach (var token in manager.FindByAuthorizationIdAsync(authorization!, context.RequestAborted))
{
var item = await DescribeTokenAsync(manager, token, context.RequestAborted);
if ((subject is not null && !string.Equals(item.Descriptor.Subject, subject, StringComparison.Ordinal)) ||
(application is not null && !string.Equals(item.Descriptor.ApplicationId, application, StringComparison.Ordinal)) ||
(status is not null && !string.Equals(item.Descriptor.Status, status, StringComparison.Ordinal)) ||
(type is not null && !string.Equals(item.Descriptor.Type, type, StringComparison.Ordinal)))
{
continue;
}
if (skipped++ < offset)
{
continue;
}
if (items.Count == size)
{
next = true;
break;
}
items.Add(item);
}
}
return Page<TokenListPage>(context, new()
{
[nameof(TokenListPage.Items)] = items,
@ -641,6 +675,7 @@ internal sealed class OpenIddictServerAspNetCoreAdminUIEndpoints
[nameof(TokenListPage.Client)] = client,
[nameof(TokenListPage.Status)] = status,
[nameof(TokenListPage.Type)] = type,
[nameof(TokenListPage.Authorization)] = authorization,
[nameof(TokenListPage.PageNumber)] = page,
[nameof(TokenListPage.HasNextPage)] = next,
[nameof(TokenListPage.Notice)] = GetQuery(context, QueryStringParameters.Notice)

15
src/OpenIddict.Server.AspNetCore.AdminUI/OpenIddictServerAspNetCoreAdminUIForms.cs

@ -87,9 +87,9 @@ internal static class OpenIddictServerAspNetCoreAdminUIForms
descriptor.ClientId = GetString(form, FormFields.ClientId);
descriptor.DisplayName = GetString(form, FormFields.DisplayName);
descriptor.ApplicationType = GetChoice(form, FormFields.ApplicationType, KnownApplicationTypes, errors);
descriptor.ClientType = GetChoice(form, FormFields.ClientType, KnownClientTypes, errors);
descriptor.ConsentType = GetChoice(form, FormFields.ConsentType, KnownConsentTypes, errors);
descriptor.ApplicationType = GetChoice(form, FormFields.ApplicationType, KnownApplicationTypes, descriptor.ApplicationType, errors);
descriptor.ClientType = GetChoice(form, FormFields.ClientType, KnownClientTypes, descriptor.ClientType, errors);
descriptor.ConsentType = GetChoice(form, FormFields.ConsentType, KnownConsentTypes, descriptor.ConsentType, errors);
ReadValues(form, FormFields.Permissions, FormFields.AdditionalPermissions, descriptor.Permissions);
ReadValues(form, FormFields.Requirements, FormFields.AdditionalRequirements, descriptor.Requirements);
@ -154,10 +154,15 @@ internal static class OpenIddictServerAspNetCoreAdminUIForms
public static string[] SplitLines(string? value)
=> value?.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? [];
private static string? GetChoice(IFormCollection form, string name, ImmutableArray<string> choices, List<string> errors)
private static string? GetChoice(IFormCollection form, string name,
ImmutableArray<string> choices, string? current, List<string> errors)
{
// Note: custom values (e.g application or consent types not known by the admin UI) can't be
// selected by the user, but are rendered as an additional option when they are already stored
// so that saving the form doesn't silently erase them: such values are always accepted as-is.
var value = GetString(form, name);
if (value is not null && !choices.Contains(value, StringComparer.Ordinal))
if (value is not null && !choices.Contains(value, StringComparer.Ordinal) &&
!string.Equals(value, current, StringComparison.Ordinal))
{
errors.Add(SR.FormatID2341(name));
return null;

154
test/OpenIddict.Server.AspNetCore.AdminUI.Tests/OpenIddictServerAspNetCoreAdminUITests.cs

@ -1150,10 +1150,162 @@ public partial class OpenIddictServerAspNetCoreAdminUITests
// Assert
Assert.Contains("only the first 2 tokens are displayed", html, StringComparison.Ordinal);
Assert.Contains("href=\"/openiddict/admin/tokens?subject=alice\"", html, StringComparison.Ordinal);
Assert.Contains("href=\"/openiddict/admin/tokens?authorization=authz-1\"", html, StringComparison.Ordinal);
Assert.Equal(2, Regex.Matches(html, "<code>token</code>", RegexOptions.None, TimeSpan.FromSeconds(1)).Count);
}
[Fact]
public async Task UpdateApplication_PreservesUnchangedRedirectUrisAndCustomTypesVerbatim()
{
// Arrange
var application = new object();
OpenIddictApplicationDescriptor? updated = null;
var manager = new Mock<IOpenIddictApplicationManager>();
manager.Setup(mock => mock.FindByIdAsync("1", It.IsAny<CancellationToken>())).ReturnsAsync(application);
manager.Setup(mock => mock.GetIdAsync(application, It.IsAny<CancellationToken>())).ReturnsAsync("1");
manager.Setup(mock => mock.PopulateAsync(It.IsAny<OpenIddictApplicationDescriptor>(), application, It.IsAny<CancellationToken>()))
.Callback((OpenIddictApplicationDescriptor descriptor, object _, CancellationToken _) =>
{
descriptor.ClientId = "fabrikam";
descriptor.ApplicationType = "custom_application_type";
descriptor.ConsentType = "custom_consent_type";
descriptor.RedirectUris.Add(new Uri("http://localhost:3000"));
descriptor.RedirectUris.Add(new Uri("https://Client.Example/cb?a=%7e"));
descriptor.PostLogoutRedirectUris.Add(new Uri("https://Client.Example"));
})
.Returns(ValueTask.CompletedTask);
manager.Setup(mock => mock.UpdateAsync(application, It.IsAny<OpenIddictApplicationDescriptor>(), It.IsAny<CancellationToken>()))
.Callback((object _, OpenIddictApplicationDescriptor descriptor, CancellationToken _) => updated = descriptor)
.Returns(ValueTask.CompletedTask);
using var host = await CreateHostAsync(services => services.AddSingleton(manager.Object));
using var client = CreateClient(host, role: "admin");
var html = await client.GetStringAsync("/openiddict/admin/applications/1");
var antiforgery = await GetAntiforgeryAsync(client, "/openiddict/admin/applications/1");
// Act: post the rendered values back unchanged, as a browser would.
var response = await PostAsync(client, antiforgery, "/openiddict/admin/applications/1",
[
new("client_id", "fabrikam"),
new("display_name", "Fabrikam (renamed)"),
new("application_type", GetSelectedOption(html, "application_type")),
new("client_type", GetSelectedOption(html, "client_type")),
new("consent_type", GetSelectedOption(html, "consent_type")),
new("redirect_uris", GetTextArea(html, "redirect_uris")),
new("post_logout_redirect_uris", GetTextArea(html, "post_logout_redirect_uris"))
]);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.NotNull(updated);
Assert.Equal("Fabrikam (renamed)", updated.DisplayName);
Assert.Equal("custom_application_type", updated.ApplicationType);
Assert.Equal("custom_consent_type", updated.ConsentType);
Assert.Null(updated.ClientType);
Assert.Equal(["http://localhost:3000", "https://Client.Example/cb?a=%7e"],
updated.RedirectUris.Select(static uri => uri.OriginalString).Order(StringComparer.Ordinal),
StringComparer.Ordinal);
Assert.Equal("https://Client.Example", Assert.Single(updated.PostLogoutRedirectUris).OriginalString);
static string GetTextArea(string html, string id)
{
var match = Regex.Match(html, $"<textarea id=\"{id}\"[^>]*>(?<value>[^<]*)</textarea>",
RegexOptions.None, TimeSpan.FromSeconds(1));
Assert.True(match.Success);
return WebUtility.HtmlDecode(match.Groups["value"].Value);
}
static string GetSelectedOption(string html, string id)
{
var select = Regex.Match(html, $"<select id=\"{id}\"[^>]*>(?<options>.*?)</select>",
RegexOptions.Singleline, TimeSpan.FromSeconds(1));
Assert.True(select.Success);
var option = Regex.Match(select.Groups["options"].Value, "<option value(?:=\"(?<value>[^\"]*)\")?[^>]*\\bselected",
RegexOptions.None, TimeSpan.FromSeconds(1));
Assert.True(option.Success, select.Value);
return WebUtility.HtmlDecode(option.Groups["value"].Value);
}
}
[Fact]
public async Task UpdateApplication_RejectsUnknownTypesThatAreNotStored()
{
// Arrange
var application = new object();
var manager = new Mock<IOpenIddictApplicationManager>();
manager.Setup(mock => mock.FindByIdAsync("1", It.IsAny<CancellationToken>())).ReturnsAsync(application);
manager.Setup(mock => mock.GetIdAsync(application, It.IsAny<CancellationToken>())).ReturnsAsync("1");
manager.Setup(mock => mock.PopulateAsync(It.IsAny<OpenIddictApplicationDescriptor>(), application, It.IsAny<CancellationToken>()))
.Callback((OpenIddictApplicationDescriptor descriptor, object _, CancellationToken _) =>
{
descriptor.ClientId = "fabrikam";
descriptor.ApplicationType = "custom_application_type";
})
.Returns(ValueTask.CompletedTask);
using var host = await CreateHostAsync(services => services.AddSingleton(manager.Object));
using var client = CreateClient(host, role: "admin");
var antiforgery = await GetAntiforgeryAsync(client, "/openiddict/admin/applications/1");
// Act
var response = await PostAsync(client, antiforgery, "/openiddict/admin/applications/1",
[
new("client_id", "fabrikam"),
new("application_type", "another_application_type")
]);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
manager.Verify(mock => mock.UpdateAsync(It.IsAny<object>(),
It.IsAny<OpenIddictApplicationDescriptor>(), It.IsAny<CancellationToken>()), Times.Never());
}
[Fact]
public async Task ListTokens_FiltersByAuthorization()
{
// Arrange
var (first, second, third) = (new object(), new object(), new object());
var applications = new Mock<IOpenIddictApplicationManager>();
var manager = new Mock<IOpenIddictTokenManager>();
manager.Setup(mock => mock.FindByAuthorizationIdAsync("authz-1", It.IsAny<CancellationToken>()))
.Returns(() => EnumerateAsync(first, second, third));
manager.Setup(mock => mock.GetIdAsync(first, It.IsAny<CancellationToken>())).ReturnsAsync("token-1");
manager.Setup(mock => mock.GetIdAsync(second, It.IsAny<CancellationToken>())).ReturnsAsync("token-2");
manager.Setup(mock => mock.GetIdAsync(third, It.IsAny<CancellationToken>())).ReturnsAsync("token-3");
manager.Setup(mock => mock.PopulateAsync(It.IsAny<OpenIddictTokenDescriptor>(), It.IsAny<object>(), It.IsAny<CancellationToken>()))
.Callback((OpenIddictTokenDescriptor descriptor, object token, CancellationToken _) =>
{
descriptor.Subject = "alice";
descriptor.Status = ReferenceEquals(token, second) ? Statuses.Revoked : Statuses.Valid;
})
.Returns(ValueTask.CompletedTask);
using var host = await CreateHostAsync(services => services
.AddSingleton(applications.Object)
.AddSingleton(manager.Object), configuration: options => options.PageSize = 1);
using var client = CreateClient(host, role: "admin");
// Act
var page1 = await client.GetStringAsync("/openiddict/admin/tokens?authorization=authz-1&status=valid");
var page2 = await client.GetStringAsync("/openiddict/admin/tokens?authorization=authz-1&status=valid&page=2");
// Assert
Assert.Contains("<code>token-1</code>", page1, StringComparison.Ordinal);
Assert.DoesNotContain("<code>token-2</code>", page1, StringComparison.Ordinal);
Assert.Contains("value=\"authz-1\"", page1, StringComparison.Ordinal);
Assert.Contains("authorization=authz-1&amp;page=2", page1, StringComparison.Ordinal);
Assert.Contains("<code>token-3</code>", page2, StringComparison.Ordinal);
Assert.DoesNotContain("<code>token-1</code>", page2, StringComparison.Ordinal);
manager.Verify(mock => mock.FindAsync(It.IsAny<(string?, string?, string?, string?)>(), It.IsAny<CancellationToken>()), Times.Never());
manager.Verify(mock => mock.ListAsync(It.IsAny<int?>(), It.IsAny<int?>(), It.IsAny<CancellationToken>()), Times.Never());
}
[Fact]
public async Task MapOpenIddictAdminUI_DetectsConflictingEndpoints()
{

Loading…
Cancel
Save