Skip to content

Account management pages - #2

Open
MackinnonBuck wants to merge 18 commits into
mainfrom
mbuck/account-management
Open

MackinnonBuck wants to merge 18 commits into
mainfrom
mbuck/account-management

Conversation

@MackinnonBuck

@MackinnonBuck MackinnonBuck commented Sep 9, 2023 •

Copy link
Copy Markdown
Collaborator
  • Layout and navigation menu
  • Profile
  • Email
  • Change password
    • Set password
  • External logins
  • Two-factor authentication
  • Personal data
  • Other loose ends

Comment on lines +94 to +106
if (HttpMethods.IsGet(HttpContext.Request.Method))
{
if (Action == LoginCallbackAction)
{
await OnLoginCallbackAsync();
return;
}

// We should only reach this page via the login callback, so redirect back to
// the login page if we get here some other way.
NavigationManager.NavigateTo("Identity/Account/Login");
return;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

There are some cases where we want to take explicit action if we're dealing with a GET request (i.e., not a form post). This was the best solution I could come up with, but I'm open to other ideas if others don't like it! 🙂

Comment on lines +95 to +96
Input ??= new();
ReturnUrl ??= "/";

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It's kind of a pain, but we need to set default values for [SupplyParameterFromQuery] and [SupplyParameterFromForm] properties in OnInitialize()/OnInitializeAsync() rather than upon component instance construction. That's because if the parameter is absent, it's assigned a null value when parameters get set. I think this still makes more sense than not assigning null values, because if you were to have a stateful, interactive component on the page, you need to be able to detect when query/form-supplied values get removed.

@MackinnonBuck

Copy link
Copy Markdown
Collaborator Author

I think I've implemented everything. I've tested as much functionality as I reasonably can, but we'll probably want to thoroughly verify all the edge cases.

Comment on lines +16 to +28
public static IEndpointConventionBuilder MapIdentityUI(this IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);

var loggerFactory = endpoints.ServiceProvider.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("IdentityUI");

var routeGroup = endpoints.MapGroup("/Identity");

routeGroup.MapPost("/Account/Manage/DownloadPersonalData", async (
HttpContext context,
[FromServices] UserManager<BlazorWebUser> userManager,
[FromServices] AuthenticationStateProvider authenticationStateProvider) =>

@MackinnonBuck MackinnonBuck Sep 18, 2023 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I added these endpoints for cases where the response is not rendered Razor component output (file downloads, challenge responses, etc.). It's not really idiomatic or practical to have Blazor component logic mess with the response content/status code except when redirecting to another page.

Comment on lines +98 to +114
routeGroup.MapPost("/Account/Logout", async (
[FromServices] SignInManager<BlazorWebUser> signInManager,
[FromForm] string returnUrl) =>
{
await signInManager.SignOutAsync();
logger.LogInformation("User logged out.");
if (returnUrl is not null)
{
return Results.LocalRedirect(returnUrl);
}
else
{
// This needs to be a redirect so that the browser performs a new
// request and the identity for the user gets updated.
return Results.LocalRedirect("/");
}
});

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This is one thing that I haven't tested yet.

Comment on lines +5 to +38
internal static class NavigationManagerExtensions
{
// These extension methods help make more concise the common case of redirecting to the same or different page
// with a fresh set of query parameters. An exception is thrown if the current page is not being rendered from
// an endpoint, because it's not possible to redirect in that case.

[DoesNotReturn]
public static void RedirectTo(this NavigationManager navigationManager, string uri)
{
// This works because either:
// [1] NavigateTo() throws NavigationException, which is handled by the framework as a redirect.
// [2] NavigateTo() throws some other exception, which gets treated as a normal unhandled exception.
// [3] NavigateTo() does not throw an exception, meaning we're not rendering from an endpoint, so we throw
// an InvalidOperationException to indicate that we can't redirect.
navigationManager.NavigateTo(uri);
throw new InvalidOperationException($"Can only redirect when rendering from an endpoint.");
}

[DoesNotReturn]
public static void RedirectTo(this NavigationManager navigationManager, string uri, Dictionary<string, object?> queryParameters)
{
var uriWithoutQuery = navigationManager.ToAbsoluteUri(uri).GetLeftPart(UriPartial.Path);
var newUri = navigationManager.GetUriWithQueryParameters(uriWithoutQuery, queryParameters);
navigationManager.RedirectTo(newUri);
}

[DoesNotReturn]
public static void RedirectToCurrentPage(this NavigationManager navigationManager)
=> navigationManager.RedirectTo(navigationManager.Uri);

[DoesNotReturn]
public static void RedirectToCurrentPage(this NavigationManager navigationManager, Dictionary<string, object?> queryParameters)
=> navigationManager.RedirectTo(navigationManager.Uri, queryParameters);
}

@MackinnonBuck MackinnonBuck Sep 18, 2023 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

We can have a discussion about whether these are really necessary. I added these because it's a very common requirement in Identity UI to need to redirect to another page and replace any existing query parameters with a new set of query parameters. The existing NavigationManger APIs aren't always ideal because:

  1. They don't guarantee a redirect, particularly if the component happens to be interactive. Our component logic might be relying on, for example, the authentication state getting updated by nature of a new request happening, and the component being completely reinitialized. Or the fact that NavigateTo() throws a NavigationException when rendering from an endpoint (that's how redirects work in Blazor). These helpers guarantee that either a redirect happens or we throw an exception if we can't perform a redirect.
  2. The NavigationManager.GetUriWithQueryParameters() method updates the existing set of query parameters rather than replacing them. This makes sense for a SPA, but not as much for static server rendering. We usually want to specify the full set of query parameters rather than expressing them as a diff.

Happy to update this if we don't think it's necessary, but it has made the code a lot nicer in some places. One argument for not adding these extension methods is that it basically guarantees that Identity UI pages can't be made interactive. But I don't think we would make them interactive anyway, and it should be noted that a lot else would have to change if we want them to work interactively.

Comment thread BlazorWeb/UserAccessor.cs
Comment on lines +7 to +28
internal sealed class UserAccessor(
IHttpContextAccessor httpContextAccessor,
UserManager<BlazorWebUser> userManager,
NavigationManager navigationManager)
{
public async Task<BlazorWebUser> GetRequiredUserAsync()
{
var principal = httpContextAccessor.HttpContext?.User ??
throw new InvalidOperationException($"{nameof(GetRequiredUserAsync)} requires access to an {nameof(HttpContext)}.");
var user = await userManager.GetUserAsync(principal);
if (user is null)
{
// Throws NavigationException, which is handled by the framework as a redirect.
navigationManager.RedirectTo("/Identity/Account/InvalidUser", new()
{
["Message"] = $"Error: Unable to load user with ID '{userManager.GetUserId(principal)}'.",
});
}

return user;
}
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

In the Razor pages implementation, almost every account management page would 404 with this error message if the user was invalid. It was a lot of duplicate logic and added up to probably a hundred lines of code.

This method automatically redirects to an InvalidUser page if the user could not be loaded for some reason. That way, components can call this method to retrieve the BlazorWebUser and guarantee that the user is valid for the rest of the component logic without requiring handling the "Invalid user" case themselves.

Comment on lines +33 to +34
[SupplyParameterFromQuery]
public string[] RecoveryCodes { get; set; } = default!;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

These are obtained from the query rather than TempData, because TempData doesn't exist in Blazor. I realize it pollutes the URI but I'm not sure of a better solution at the moment (rather than implementing TempData just for the identity pages).

Comment on lines +18 to +19
[SupplyParameterFromQuery(Name = "Message")]
public string? MessageFromQuery { get; set; }

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The status message can be set on any page that renders a StatusMessage by adding a Message query parameter. This is also due to the fact that we don't have TempData in Blazor. I believe the only drawback to this approach is that it pollutes the URL a bit (I don't think there are any negative security implications to this, but I'm not a security expert so maybe I'm wrong about this).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Another thought: The close button doesn't currently work. Some options to make this work are:

  1. A bit of JavaScript that reacts to the dismiss button and removes the alert.
  2. Have the button submit a form request that removes the Message from the query (probably less ideal)

halter73 added a commit to dotnet/aspnetcore that referenced this pull request Sep 18, 2023
MackinnonBuck pushed a commit to dotnet/aspnetcore that referenced this pull request Sep 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant