|
| 1 | +using System.Security.Claims; |
| 2 | +using System.Text.Json; |
| 3 | +using BlazorAppAuthentication.Components.Account.Pages; |
| 4 | +using BlazorAppAuthentication.Components.Account.Pages.Manage; |
| 5 | +using BlazorAppAuthentication.Data; |
| 6 | +using Microsoft.AspNetCore.Authentication; |
| 7 | +using Microsoft.AspNetCore.Components.Authorization; |
| 8 | +using Microsoft.AspNetCore.Http.Extensions; |
| 9 | +using Microsoft.AspNetCore.Identity; |
| 10 | +using Microsoft.AspNetCore.Mvc; |
| 11 | +using Microsoft.Extensions.Primitives; |
| 12 | + |
| 13 | +namespace Microsoft.AspNetCore.Routing |
| 14 | +{ |
| 15 | + internal static class IdentityComponentsEndpointRouteBuilderExtensions |
| 16 | + { |
| 17 | + // These endpoints are required by the Identity Razor components defined in the /Components/Account/Pages directory of this project. |
| 18 | + public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEndpointRouteBuilder endpoints) |
| 19 | + { |
| 20 | + ArgumentNullException.ThrowIfNull(endpoints); |
| 21 | + |
| 22 | + var accountGroup = endpoints.MapGroup("/Account"); |
| 23 | + |
| 24 | + accountGroup.MapPost("/PerformExternalLogin", ( |
| 25 | + HttpContext context, |
| 26 | + [FromServices] SignInManager<ApplicationUser> signInManager, |
| 27 | + [FromForm] string provider, |
| 28 | + [FromForm] string returnUrl) => |
| 29 | + { |
| 30 | + IEnumerable<KeyValuePair<string, StringValues>> query = [ |
| 31 | + new("ReturnUrl", returnUrl), |
| 32 | + new("Action", ExternalLogin.LoginCallbackAction)]; |
| 33 | + |
| 34 | + var redirectUrl = UriHelper.BuildRelative( |
| 35 | + context.Request.PathBase, |
| 36 | + "/Account/ExternalLogin", |
| 37 | + QueryString.Create(query)); |
| 38 | + |
| 39 | + var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); |
| 40 | + return TypedResults.Challenge(properties, [provider]); |
| 41 | + }); |
| 42 | + |
| 43 | + accountGroup.MapPost("/Logout", async ( |
| 44 | + ClaimsPrincipal user, |
| 45 | + [FromServices] SignInManager<ApplicationUser> signInManager, |
| 46 | + [FromForm] string returnUrl) => |
| 47 | + { |
| 48 | + await signInManager.SignOutAsync(); |
| 49 | + return TypedResults.LocalRedirect($"~/{returnUrl}"); |
| 50 | + }); |
| 51 | + |
| 52 | + var manageGroup = accountGroup.MapGroup("/Manage").RequireAuthorization(); |
| 53 | + |
| 54 | + manageGroup.MapPost("/LinkExternalLogin", async ( |
| 55 | + HttpContext context, |
| 56 | + [FromServices] SignInManager<ApplicationUser> signInManager, |
| 57 | + [FromForm] string provider) => |
| 58 | + { |
| 59 | + // Clear the existing external cookie to ensure a clean login process |
| 60 | + await context.SignOutAsync(IdentityConstants.ExternalScheme); |
| 61 | + |
| 62 | + var redirectUrl = UriHelper.BuildRelative( |
| 63 | + context.Request.PathBase, |
| 64 | + "/Account/Manage/ExternalLogins", |
| 65 | + QueryString.Create("Action", ExternalLogins.LinkLoginCallbackAction)); |
| 66 | + |
| 67 | + var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, signInManager.UserManager.GetUserId(context.User)); |
| 68 | + return TypedResults.Challenge(properties, [provider]); |
| 69 | + }); |
| 70 | + |
| 71 | + var loggerFactory = endpoints.ServiceProvider.GetRequiredService<ILoggerFactory>(); |
| 72 | + var downloadLogger = loggerFactory.CreateLogger("DownloadPersonalData"); |
| 73 | + |
| 74 | + manageGroup.MapPost("/DownloadPersonalData", async ( |
| 75 | + HttpContext context, |
| 76 | + [FromServices] UserManager<ApplicationUser> userManager, |
| 77 | + [FromServices] AuthenticationStateProvider authenticationStateProvider) => |
| 78 | + { |
| 79 | + var user = await userManager.GetUserAsync(context.User); |
| 80 | + if (user is null) |
| 81 | + { |
| 82 | + return Results.NotFound($"Unable to load user with ID '{userManager.GetUserId(context.User)}'."); |
| 83 | + } |
| 84 | + |
| 85 | + var userId = await userManager.GetUserIdAsync(user); |
| 86 | + downloadLogger.LogInformation("User with ID '{UserId}' asked for their personal data.", userId); |
| 87 | + |
| 88 | + // Only include personal data for download |
| 89 | + var personalData = new Dictionary<string, string>(); |
| 90 | + var personalDataProps = typeof(ApplicationUser).GetProperties().Where( |
| 91 | + prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute))); |
| 92 | + foreach (var p in personalDataProps) |
| 93 | + { |
| 94 | + personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null"); |
| 95 | + } |
| 96 | + |
| 97 | + var logins = await userManager.GetLoginsAsync(user); |
| 98 | + foreach (var l in logins) |
| 99 | + { |
| 100 | + personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey); |
| 101 | + } |
| 102 | + |
| 103 | + personalData.Add("Authenticator Key", (await userManager.GetAuthenticatorKeyAsync(user))!); |
| 104 | + var fileBytes = JsonSerializer.SerializeToUtf8Bytes(personalData); |
| 105 | + |
| 106 | + context.Response.Headers.TryAdd("Content-Disposition", "attachment; filename=PersonalData.json"); |
| 107 | + return TypedResults.File(fileBytes, contentType: "application/json", fileDownloadName: "PersonalData.json"); |
| 108 | + }); |
| 109 | + |
| 110 | + return accountGroup; |
| 111 | + } |
| 112 | + } |
| 113 | +} |
0 commit comments