OnPostAsync(string? returnUrl = null, Cancellat
LogUserCreatedWithPassword(logger);
string userId = await userManager.GetUserIdAsync(user);
+ // The password chosen here stays usable only if the confirmation link is opened in this browser.
+ registrationBrowserBinding.Issue(HttpContext, userId);
string code = await userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
- string? callbackUrl = Url.Page(
+ string? callbackUrl = Url.EmailPageLink(
+ siteSettings.Value,
"/Account/ConfirmEmail",
- pageHandler: null,
- values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
- protocol: Request.Scheme);
+ values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl });
if (callbackUrl is null)
{
diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml b/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml
index 48869443..f1f8c4f7 100644
--- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml
+++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml
@@ -5,19 +5,6 @@
}
@ViewData["Title"]
-@{
- if (@Model.DisplayConfirmAccountLink)
-{
-
- This app does not currently have a real email sender registered, see these docs for how to configure a real email sender.
- Normally this would be emailed: Click here to confirm your account
-
- }
-else
-{
- Please check your email to confirm your account. If you can't find the email, please check your spam folder.
+ Please check your email to confirm your account. If you can't find the email, please check your spam folder.
- }
-}
-
diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs
index 1f840a4f..72bb7d40 100644
--- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs
+++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs
@@ -1,61 +1,24 @@
-using System.Text;
-using EssentialCSharp.Web.Areas.Identity.Data;
-using Microsoft.AspNetCore.Authorization;
-using Microsoft.AspNetCore.Identity;
-using Microsoft.AspNetCore.Identity.UI.Services;
+using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
-using Microsoft.AspNetCore.WebUtilities;
namespace EssentialCSharp.Web.Areas.Identity.Pages.Account;
[AllowAnonymous]
public class RegisterConfirmationModel : PageModel
{
- private readonly UserManager _UserManager;
- private readonly IEmailSender _Sender;
-
- public RegisterConfirmationModel(UserManager userManager, IEmailSender sender)
- {
- _UserManager = userManager;
- _Sender = sender;
- }
-
public string? Email { get; set; }
- public bool DisplayConfirmAccountLink { get; set; }
-
- public string? EmailConfirmationUrl { get; set; }
-
- public async Task OnGetAsync(string? email, string? returnUrl = null)
+ // The page is the same whether or not an account exists for the email, so it can't be used to find out
+ // which addresses are registered.
+ public IActionResult OnGet(string? email)
{
if (email is null)
{
return RedirectToPage("/Index");
}
- returnUrl ??= Url.Content("~/");
-
- EssentialCSharpWebUser? user = await _UserManager.FindByEmailAsync(email);
- if (user is null)
- {
- return NotFound($"Unable to load user with email '{email}'.");
- }
Email = email;
- // Once you add a real email sender, you should remove this code that lets you confirm the account
- DisplayConfirmAccountLink = false;
- if (DisplayConfirmAccountLink)
- {
- string userId = await _UserManager.GetUserIdAsync(user);
- string code = await _UserManager.GenerateEmailConfirmationTokenAsync(user);
- code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
- EmailConfirmationUrl = Url.Page(
- "/Account/ConfirmEmail",
- pageHandler: null,
- values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
- protocol: Request.Scheme);
- }
-
return Page();
}
}
diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResendEmailConfirmation.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResendEmailConfirmation.cshtml.cs
index 9c66441b..e5dda833 100644
--- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResendEmailConfirmation.cshtml.cs
+++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResendEmailConfirmation.cshtml.cs
@@ -2,6 +2,7 @@
using System.Text;
using System.Text.Encodings.Web;
using EssentialCSharp.Web.Areas.Identity.Data;
+using EssentialCSharp.Web.Extensions;
using EssentialCSharp.Web.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
@@ -14,7 +15,7 @@
namespace EssentialCSharp.Web.Areas.Identity.Pages.Account;
[AllowAnonymous]
-public partial class ResendEmailConfirmationModel(UserManager userManager, IEmailSender emailSender, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, ILogger logger) : PageModel
+public partial class ResendEmailConfirmationModel(UserManager userManager, IEmailSender emailSender, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, ILogger logger, IOptions siteSettings) : PageModel
{
[TempData]
public string? StatusMessage { get; set; }
@@ -76,11 +77,10 @@ public async Task OnPostAsync(CancellationToken cancellationToken
string userId = await userManager.GetUserIdAsync(user);
string code = await userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
- string? callbackUrl = Url.Page(
+ string? callbackUrl = Url.EmailPageLink(
+ siteSettings.Value,
"/Account/ConfirmEmail",
- pageHandler: null,
- values: new { userId = userId, code = code },
- protocol: Request.Scheme);
+ values: new { userId = userId, code = code });
if (callbackUrl is null)
{
diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs
index 19ebf68e..ada08142 100644
--- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs
+++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs
@@ -1,6 +1,7 @@
using System.ComponentModel.DataAnnotations;
using System.Text;
using EssentialCSharp.Web.Areas.Identity.Data;
+using EssentialCSharp.Web.Areas.Identity.Services;
using EssentialCSharp.Web.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
@@ -10,7 +11,7 @@
namespace EssentialCSharp.Web.Areas.Identity.Pages.Account;
-public class ResetPasswordModel(UserManager userManager, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor) : PageModel
+public class ResetPasswordModel(UserManager userManager, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, AccountOwnershipService accountOwnershipService) : PageModel
{
private InputModel? _Input;
[BindProperty]
@@ -103,6 +104,15 @@ public async Task OnPostAsync(CancellationToken cancellationToken
IdentityResult result = await userManager.ResetPasswordAsync(user, Input.Code, Input.Password);
if (result.Succeeded)
{
+ // The reset token proves control of the mailbox. External logins and MCP tokens on the account
+ // may have been added by someone else before that, so they don't survive the reset.
+ await accountOwnershipService.RemoveCredentialsAddedBeforeOwnershipProofAsync(user, cancellationToken);
+
+ // Failed password attempts by someone else shouldn't keep the owner locked out after they prove
+ // they own the account.
+ await userManager.SetLockoutEndDateAsync(user, null);
+ await userManager.ResetAccessFailedCountAsync(user);
+
return RedirectToPage("./ResetPasswordConfirmation");
}
diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml
index c52552f3..9cf9c8b8 100644
--- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml
+++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml
@@ -8,3 +8,7 @@
Your password has been reset. Please click here to log in.
+
+ To keep your account safe, external logins (such as GitHub or Microsoft) and MCP tokens that were connected to
+ this account have been removed. After you log in, you can link them again from your account settings.
+
diff --git a/EssentialCSharp.Web/Areas/Identity/Services/AccountOwnershipService.cs b/EssentialCSharp.Web/Areas/Identity/Services/AccountOwnershipService.cs
new file mode 100644
index 00000000..9cfcffe6
--- /dev/null
+++ b/EssentialCSharp.Web/Areas/Identity/Services/AccountOwnershipService.cs
@@ -0,0 +1,118 @@
+using System.Text.Json;
+using EssentialCSharp.Web.Areas.Identity.Data;
+using EssentialCSharp.Web.Services;
+using Microsoft.AspNetCore.Identity;
+
+namespace EssentialCSharp.Web.Areas.Identity.Services;
+
+///
+/// Keeps credentials off an account until the person adding them has proven they control the account's email
+/// address, and clears anything attached before that proof. Without this, someone who registers (or links an
+/// external login to) an address they don't own keeps a way in after the real owner confirms or resets it.
+///
+public sealed class AccountOwnershipService(
+ UserManager userManager,
+ McpApiTokenService mcpApiTokenService)
+{
+ // Stored in AspNetUserTokens. The bracketed provider name cannot collide with a real external provider.
+ internal const string PendingExternalLoginTokenProvider = "[EssentialCSharpPendingExternalLogin]";
+ internal const string PendingExternalLoginTokenName = "Login";
+
+ ///
+ /// Records the external login that asked to use this account. It is linked only by
+ /// , after the email is confirmed in a browser that still holds
+ /// the same external login.
+ ///
+ public Task SetPendingExternalLoginAsync(EssentialCSharpWebUser user, UserLoginInfo login)
+ {
+ ArgumentNullException.ThrowIfNull(login);
+ string value = JsonSerializer.Serialize(new PendingExternalLogin(login.LoginProvider, login.ProviderKey, login.ProviderDisplayName));
+ return userManager.SetAuthenticationTokenAsync(user, PendingExternalLoginTokenProvider, PendingExternalLoginTokenName, value);
+ }
+
+ /// Returns the display name of the provider whose login is waiting to be linked, if any.
+ public async Task GetPendingExternalLoginDisplayNameAsync(EssentialCSharpWebUser user)
+ {
+ PendingExternalLogin? pending = await GetPendingExternalLoginAsync(user);
+ return pending is null ? null : pending.ProviderDisplayName ?? pending.LoginProvider;
+ }
+
+ ///
+ /// Links to only when it is the login recorded by
+ /// . Call it only after the caller has proven control of the email.
+ ///
+ /// when the login was linked.
+ public async Task TryLinkPendingExternalLoginAsync(EssentialCSharpWebUser user, UserLoginInfo? login)
+ {
+ if (login is null)
+ {
+ return false;
+ }
+
+ PendingExternalLogin? pending = await GetPendingExternalLoginAsync(user);
+ if (pending is null
+ || !string.Equals(pending.LoginProvider, login.LoginProvider, StringComparison.Ordinal)
+ || !string.Equals(pending.ProviderKey, login.ProviderKey, StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ IdentityResult result = await userManager.AddLoginAsync(user, login);
+ if (!result.Succeeded)
+ {
+ return false;
+ }
+
+ await userManager.RemoveAuthenticationTokenAsync(user, PendingExternalLoginTokenProvider, PendingExternalLoginTokenName);
+ return true;
+ }
+
+ ///
+ /// Call when someone has just proven control of the account's email (first confirmation or a password reset).
+ /// Removes every external login and revokes every MCP token, because any of them may have been added by
+ /// someone else before that proof, then rotates the security stamp so existing sessions and tokens end.
+ ///
+ public async Task RemoveCredentialsAddedBeforeOwnershipProofAsync(EssentialCSharpWebUser user, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(user);
+
+ foreach (UserLoginInfo login in await userManager.GetLoginsAsync(user))
+ {
+ IdentityResult removed = await userManager.RemoveLoginAsync(user, login.LoginProvider, login.ProviderKey);
+ if (!removed.Succeeded)
+ {
+ throw new InvalidOperationException(
+ $"Could not remove the {login.LoginProvider} login: {string.Join("; ", removed.Errors.Select(e => e.Description))}");
+ }
+ }
+
+ await mcpApiTokenService.RevokeAllTokensAsync(user.Id, cancellationToken);
+
+ IdentityResult stampResult = await userManager.UpdateSecurityStampAsync(user);
+ if (!stampResult.Succeeded)
+ {
+ throw new InvalidOperationException(
+ $"Could not rotate the security stamp: {string.Join("; ", stampResult.Errors.Select(e => e.Description))}");
+ }
+ }
+
+ private async Task GetPendingExternalLoginAsync(EssentialCSharpWebUser user)
+ {
+ string? value = await userManager.GetAuthenticationTokenAsync(user, PendingExternalLoginTokenProvider, PendingExternalLoginTokenName);
+ if (string.IsNullOrEmpty(value))
+ {
+ return null;
+ }
+
+ try
+ {
+ return JsonSerializer.Deserialize(value);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+ }
+
+ private sealed record PendingExternalLogin(string LoginProvider, string ProviderKey, string? ProviderDisplayName);
+}
diff --git a/EssentialCSharp.Web/Areas/Identity/Services/RegistrationBrowserBinding.cs b/EssentialCSharp.Web/Areas/Identity/Services/RegistrationBrowserBinding.cs
new file mode 100644
index 00000000..efdd33e7
--- /dev/null
+++ b/EssentialCSharp.Web/Areas/Identity/Services/RegistrationBrowserBinding.cs
@@ -0,0 +1,74 @@
+using Microsoft.AspNetCore.DataProtection;
+using Microsoft.AspNetCore.Identity;
+using Microsoft.Extensions.Options;
+
+namespace EssentialCSharp.Web.Areas.Identity.Services;
+
+///
+/// Remembers, in a protected cookie, which account this browser just registered. The first email confirmation
+/// keeps the password chosen at registration only when the link is opened in that same browser; anywhere else,
+/// the person clicking proved only that they own the mailbox, so they are asked to choose their own password.
+///
+public sealed class RegistrationBrowserBinding(
+ IDataProtectionProvider dataProtectionProvider,
+ IOptions tokenOptions)
+{
+ internal const string CookieName = ".EssentialCSharp.RegistrationBinding";
+ private const string CookiePath = "/Identity/Account";
+ private const string Purpose = "EssentialCSharp.Web.RegistrationBrowserBinding.v1";
+
+ // Confirmation links are emailed with the default token provider, so the binding lasts as long as the link.
+ private TimeSpan Lifetime => tokenOptions.Value.TokenLifespan;
+
+ private ITimeLimitedDataProtector Protector =>
+ dataProtectionProvider.CreateProtector(Purpose).ToTimeLimitedDataProtector();
+
+ public void Issue(HttpContext httpContext, string userId)
+ {
+ ArgumentNullException.ThrowIfNull(httpContext);
+ ArgumentException.ThrowIfNullOrEmpty(userId);
+
+ string value = Protector.Protect(userId, Lifetime);
+ httpContext.Response.Cookies.Append(CookieName, value, CreateCookieOptions(httpContext, DateTimeOffset.UtcNow.Add(Lifetime)));
+ }
+
+ public bool IsBoundTo(HttpContext httpContext, string userId)
+ {
+ ArgumentNullException.ThrowIfNull(httpContext);
+
+ if (!httpContext.Request.Cookies.TryGetValue(CookieName, out string? value) || string.IsNullOrEmpty(value))
+ {
+ return false;
+ }
+
+ try
+ {
+ return string.Equals(Protector.Unprotect(value), userId, StringComparison.Ordinal);
+ }
+ catch (System.Security.Cryptography.CryptographicException)
+ {
+ // Expired, tampered with or protected with a key that no longer exists.
+ return false;
+ }
+ }
+
+ public void Clear(HttpContext httpContext)
+ {
+ ArgumentNullException.ThrowIfNull(httpContext);
+ if (httpContext.Request.Cookies.ContainsKey(CookieName))
+ {
+ httpContext.Response.Cookies.Delete(CookieName, CreateCookieOptions(httpContext, expires: null));
+ }
+ }
+
+ private static CookieOptions CreateCookieOptions(HttpContext httpContext, DateTimeOffset? expires) => new()
+ {
+ HttpOnly = true,
+ Secure = httpContext.Request.IsHttps,
+ // Lax so the cookie is sent when the user follows the emailed link (a top-level GET navigation).
+ SameSite = SameSiteMode.Lax,
+ Path = CookiePath,
+ IsEssential = true,
+ Expires = expires,
+ };
+}
diff --git a/EssentialCSharp.Web/Extensions/UrlHelperExtensions.cs b/EssentialCSharp.Web/Extensions/UrlHelperExtensions.cs
new file mode 100644
index 00000000..5121b510
--- /dev/null
+++ b/EssentialCSharp.Web/Extensions/UrlHelperExtensions.cs
@@ -0,0 +1,43 @@
+using EssentialCSharp.Web.Services;
+using Microsoft.AspNetCore.Mvc;
+
+namespace EssentialCSharp.Web.Extensions;
+
+public static class UrlHelperExtensions
+{
+ ///
+ /// Generates an absolute URL for a Razor page that is safe to put in an email. The origin comes from the
+ /// configured , never from the request's Host header, so a request
+ /// with a forged Host cannot make the app email a link (and its token) to another site.
+ ///
+ /// The absolute URL, or when the page cannot be resolved.
+ public static string? EmailPageLink(this IUrlHelper url, SiteSettings siteSettings, string pageName, object? values)
+ {
+ ArgumentNullException.ThrowIfNull(url);
+ ArgumentNullException.ThrowIfNull(siteSettings);
+
+ string? link = url.Page(pageName, pageHandler: null, values);
+ if (link is null)
+ {
+ return null;
+ }
+
+ if (!Uri.TryCreate(siteSettings.BaseUrl, UriKind.Absolute, out Uri? baseUri))
+ {
+ throw new InvalidOperationException(
+ $"{SiteSettings.SectionName}:{nameof(SiteSettings.BaseUrl)} must be an absolute URL to generate email links.");
+ }
+
+ // Keep only the path and query of whatever the URL helper produced, then attach the configured origin.
+ string pathAndQuery = Uri.TryCreate(link, UriKind.Absolute, out Uri? absolute)
+ && (absolute.Scheme == Uri.UriSchemeHttp || absolute.Scheme == Uri.UriSchemeHttps)
+ ? absolute.PathAndQuery
+ : link;
+ if (!pathAndQuery.StartsWith('/'))
+ {
+ pathAndQuery = "/" + pathAndQuery;
+ }
+
+ return baseUri.GetLeftPart(UriPartial.Authority) + pathAndQuery;
+ }
+}
diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs
index 4fffe529..b456b6ad 100644
--- a/EssentialCSharp.Web/Program.cs
+++ b/EssentialCSharp.Web/Program.cs
@@ -4,6 +4,7 @@
using ModelContextProtocol.Protocol;
using EssentialCSharp.Chat.Common.Extensions;
using EssentialCSharp.Web.Areas.Identity.Data;
+using EssentialCSharp.Web.Areas.Identity.Services;
using EssentialCSharp.Web.Areas.Identity.Services.PasswordValidators;
using EssentialCSharp.Web.Auth;
using EssentialCSharp.Web.Data;
@@ -193,6 +194,8 @@ private static void Main(string[] args)
// MCP server — always enabled, authenticated via opaque DB-backed tokens.
builder.Services.AddScoped();
+ builder.Services.AddScoped();
+ builder.Services.AddScoped();
builder.Services.AddMemoryCache();
builder.Services.AddSingleton(_ => new ResponseIdValidationService());
diff --git a/EssentialCSharp.Web/Services/McpApiTokenService.cs b/EssentialCSharp.Web/Services/McpApiTokenService.cs
index 3cdc4ee1..9d7b1756 100644
--- a/EssentialCSharp.Web/Services/McpApiTokenService.cs
+++ b/EssentialCSharp.Web/Services/McpApiTokenService.cs
@@ -98,6 +98,14 @@ public async Task RevokeTokenAsync(
return rows > 0;
}
+ /// Revokes every token the user still has. Returns the number of tokens revoked.
+ public Task RevokeAllTokensAsync(
+ string userId,
+ CancellationToken cancellationToken = default)
+ => db.McpApiTokens
+ .Where(t => t.UserId == userId && t.RevokedAt == null)
+ .ExecuteUpdateAsync(s => s.SetProperty(t => t.RevokedAt, DateTime.UtcNow), cancellationToken);
+
/// Returns the count of active (non-revoked, non-expired) tokens for the specified user.
public Task GetActiveTokenCountAsync(
string userId,