fix(website): open redirect, dead auth pages, stale rate-limit attribute
- /auth/challenge: validate returnUrl with IsLocalUrl before passing to
Keycloak redirect — blocks open-redirect phishing flows
- Dead local-auth pages (Login, Register, ForgotPassword, ResetPassword,
VerifyEmail) all injected SignInManager which is no longer registered;
replaced page models with simple redirects to /auth/challenge
- Stubbed their .cshtml views so the Razor compiler doesn't error on
missing model properties
- Added belt-and-suspenders MapGet guards in Program.cs for /auth/login,
/auth/register, /auth/forgot-password, /auth/reset-password
- Removed [EnableRateLimiting("auth-login")] dead attribute (Keycloak
handles brute-force; AddRateLimiter was never wired in this project)
Stored-HTML XSS (NewsPost / HowToPlay) is accepted by policy: content is
admin-only and the existing CSP (script-src 'self', no inline/eval) blocks
script injection.
Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -1,42 +1,3 @@
|
||||
@page
|
||||
@model ForgotPasswordModel
|
||||
@{
|
||||
ViewData["Title"] = "Forgot Password";
|
||||
}
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
<h1 class="auth-title">Reset Password</h1>
|
||||
|
||||
@if (Model.EmailSent)
|
||||
{
|
||||
<div class="alert alert-success" role="status">
|
||||
If an account exists with that email, you'll receive a reset link shortly.
|
||||
Check your spam folder if it doesn't arrive within a few minutes.
|
||||
</div>
|
||||
<a href="/auth/login" class="btn btn-ghost btn-block">Back to Login</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Enter your account email and we'll send you a reset link.</p>
|
||||
|
||||
<form method="post" novalidate>
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.Email">Email</label>
|
||||
<input asp-for="Input.Email"
|
||||
type="email"
|
||||
autocomplete="email"
|
||||
autofocus
|
||||
class="form-control"
|
||||
placeholder="you@example.com">
|
||||
<span asp-validation-for="Input.Email" class="field-error"></span>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary btn-block">Send Reset Link</button>
|
||||
</form>
|
||||
|
||||
<div class="auth-links">
|
||||
<a href="/auth/login">Back to Login</a>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@model SOR.Website.Pages.Auth.ForgotPasswordModel
|
||||
@* This page is not rendered — the model redirects to /auth/challenge immediately. *@
|
||||
|
||||
@@ -1,74 +1,15 @@
|
||||
namespace SOR.Website.Pages.Auth;
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using SOR.Database.Entities.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Initiates password reset by sending a reset link to the supplied email.
|
||||
///
|
||||
/// Security controls:
|
||||
/// - [EnableRateLimiting]: 3 attempts per IP per 15 minutes — limits reset spam.
|
||||
/// - Anti-enumeration: ALWAYS shows the same success message regardless of whether
|
||||
/// the email is registered. An attacker cannot probe which emails have accounts.
|
||||
/// - Reset token generated by ASP.NET Core Identity's built-in TOTP token provider
|
||||
/// (time-limited, single-use). The raw token is sent in the email link only.
|
||||
/// - TODO: wire up an actual email provider. Until then the reset link is logged
|
||||
/// (only in Development) so developers can test the flow.
|
||||
/// Local account management is no longer handled by this site — Keycloak owns all
|
||||
/// registration, password reset, and email verification flows.
|
||||
/// Redirects to the Keycloak-hosted login/registration page.
|
||||
/// </summary>
|
||||
[EnableRateLimiting("auth-reset")]
|
||||
public sealed class ForgotPasswordModel(
|
||||
UserManager<Account> userManager,
|
||||
ILogger<ForgotPasswordModel> logger) : PageModel
|
||||
public sealed class ForgotPasswordModel : PageModel
|
||||
{
|
||||
[BindProperty]
|
||||
public InputModel Input { get; set; } = new();
|
||||
|
||||
public bool EmailSent { get; private set; }
|
||||
|
||||
public sealed class InputModel
|
||||
{
|
||||
[Required(ErrorMessage = "Email is required.")]
|
||||
[EmailAddress(ErrorMessage = "Enter a valid email address.")]
|
||||
[MaxLength(254)]
|
||||
public string Email { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public void OnGet() { }
|
||||
|
||||
public async Task<IActionResult> OnPostAsync()
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return Page();
|
||||
|
||||
// Look up the user — but do not reveal whether the email is registered.
|
||||
var user = await userManager.FindByEmailAsync(Input.Email);
|
||||
|
||||
if (user is not null && !user.IsAi)
|
||||
{
|
||||
var token = await userManager.GeneratePasswordResetTokenAsync(user);
|
||||
var resetLink = Url.Page(
|
||||
"/Auth/ResetPassword",
|
||||
pageHandler: null,
|
||||
values: new { token, email = Input.Email },
|
||||
protocol: Request.Scheme);
|
||||
|
||||
// TODO: send resetLink via email provider.
|
||||
// Log in development only so the link is accessible for manual testing.
|
||||
if (HttpContext.RequestServices
|
||||
.GetRequiredService<IWebHostEnvironment>()
|
||||
.IsDevelopment())
|
||||
{
|
||||
logger.LogWarning("DEV ONLY — password reset link for {Email}: {Link}",
|
||||
Input.Email, resetLink);
|
||||
}
|
||||
}
|
||||
|
||||
// Always show the same message — anti-enumeration.
|
||||
EmailSent = true;
|
||||
return Page();
|
||||
}
|
||||
public IActionResult OnGet() => Redirect("/auth/challenge");
|
||||
public IActionResult OnPost() => Redirect("/auth/challenge");
|
||||
}
|
||||
|
||||
@@ -1,55 +1,3 @@
|
||||
@page
|
||||
@model LoginModel
|
||||
@{
|
||||
ViewData["Title"] = "Log In";
|
||||
}
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
<h1 class="auth-title">Log In</h1>
|
||||
|
||||
@if (Model.ErrorMessage is not null)
|
||||
{
|
||||
<div class="alert alert-error" role="alert">@Model.ErrorMessage</div>
|
||||
}
|
||||
|
||||
@* asp-page-handler is omitted — Razor Pages routes POST to OnPostAsync by default.
|
||||
The form tag helper automatically injects the anti-forgery hidden field. *@
|
||||
<form method="post" novalidate>
|
||||
<input type="hidden" asp-for="ReturnUrl">
|
||||
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.UsernameOrEmail">Username or Email</label>
|
||||
<input asp-for="Input.UsernameOrEmail"
|
||||
type="text"
|
||||
autocomplete="username"
|
||||
autofocus
|
||||
class="form-control"
|
||||
placeholder="your handle or email">
|
||||
<span asp-validation-for="Input.UsernameOrEmail" class="field-error"></span>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.Password">Password</label>
|
||||
<input asp-for="Input.Password"
|
||||
type="password"
|
||||
autocomplete="current-password"
|
||||
class="form-control">
|
||||
<span asp-validation-for="Input.Password" class="field-error"></span>
|
||||
</div>
|
||||
|
||||
<div class="form-group form-check">
|
||||
<input asp-for="Input.RememberMe" type="checkbox" class="form-check-input" id="remember-me">
|
||||
<label for="remember-me" class="form-check-label">Keep me signed in</label>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-block">Log In</button>
|
||||
</form>
|
||||
|
||||
<div class="auth-links">
|
||||
<a href="/auth/forgot-password">Forgot password?</a>
|
||||
<span class="auth-sep" aria-hidden="true">·</span>
|
||||
<a href="/auth/register">Create an account</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@model SOR.Website.Pages.Auth.LoginModel
|
||||
@* This page is not rendered — the model redirects to /auth/challenge immediately. *@
|
||||
|
||||
@@ -1,116 +1,15 @@
|
||||
namespace SOR.Website.Pages.Auth;
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Entities.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Handles player login via email + password.
|
||||
///
|
||||
/// Security controls:
|
||||
/// - [EnableRateLimiting]: 10 attempts per IP per 5 minutes.
|
||||
/// - lockoutOnFailure: true in PasswordSignInAsync — Identity locks the account
|
||||
/// after 5 failures, defeating unlimited brute-force.
|
||||
/// - ReturnUrl validated with Url.IsLocalUrl before redirect — no open redirect.
|
||||
/// - Anti-forgery token validated by Razor Pages on every POST (default behavior).
|
||||
/// - Generic error message: does NOT confirm whether the email exists (no enumeration).
|
||||
/// - SignInWithClaimsAsync adds the display_name custom claim so the nav bar can
|
||||
/// show the player's handle without a DB round-trip per request.
|
||||
/// Local password login is no longer used — all authentication is handled by Keycloak.
|
||||
/// This page model exists only to redirect any bookmarked /auth/login URLs gracefully.
|
||||
/// Program.cs also maps GET /auth/login → /auth/challenge as a belt-and-suspenders guard.
|
||||
/// </summary>
|
||||
[EnableRateLimiting("auth-login")]
|
||||
public sealed class LoginModel(
|
||||
SignInManager<Account> signInManager,
|
||||
UserManager<Account> userManager) : PageModel
|
||||
public sealed class LoginModel : PageModel
|
||||
{
|
||||
[BindProperty]
|
||||
public InputModel Input { get; set; } = new();
|
||||
|
||||
// returnUrl is injected by ASP.NET Core's cookie auth middleware when it
|
||||
// redirects an unauthenticated request to the login page.
|
||||
[BindProperty(SupportsGet = true)]
|
||||
public string? ReturnUrl { get; set; }
|
||||
|
||||
public string? ErrorMessage { get; private set; }
|
||||
|
||||
public sealed class InputModel
|
||||
{
|
||||
// Accepts either an email address or the player's in-game display name (handle).
|
||||
[Required(ErrorMessage = "Username or email is required.")]
|
||||
[MaxLength(254)]
|
||||
public string UsernameOrEmail { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "Password is required.")]
|
||||
[DataType(DataType.Password)]
|
||||
[MaxLength(128)]
|
||||
public string Password { get; set; } = string.Empty;
|
||||
|
||||
public bool RememberMe { get; set; }
|
||||
}
|
||||
|
||||
public IActionResult OnGet()
|
||||
{
|
||||
// Already signed in — send them where they were going.
|
||||
if (User.Identity?.IsAuthenticated == true)
|
||||
return SafeRedirect(ReturnUrl);
|
||||
|
||||
return Page();
|
||||
}
|
||||
|
||||
public async Task<IActionResult> OnPostAsync()
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return Page();
|
||||
|
||||
// Resolve account: try email first, then fall back to display name.
|
||||
// We look up the user explicitly so we can use the TUser overload of
|
||||
// PasswordSignInAsync — this lets us pass lockoutOnFailure correctly
|
||||
// regardless of which identifier the player used.
|
||||
var input = Input.UsernameOrEmail.Trim();
|
||||
var user = await userManager.FindByEmailAsync(input)
|
||||
?? await userManager.Users
|
||||
.FirstOrDefaultAsync(u => u.DisplayName == input);
|
||||
|
||||
if (user is not null)
|
||||
{
|
||||
var result = await signInManager.PasswordSignInAsync(
|
||||
user,
|
||||
Input.Password,
|
||||
Input.RememberMe,
|
||||
lockoutOnFailure: true);
|
||||
|
||||
if (result.Succeeded)
|
||||
{
|
||||
// Embed display_name in the cookie so the nav bar shows the
|
||||
// player's handle without a DB round-trip on every request.
|
||||
var extraClaims = new[]
|
||||
{
|
||||
new Claim("display_name", user.DisplayName ?? user.Email ?? string.Empty),
|
||||
};
|
||||
await signInManager.SignInWithClaimsAsync(user, Input.RememberMe, extraClaims);
|
||||
return SafeRedirect(ReturnUrl);
|
||||
}
|
||||
|
||||
if (result.IsLockedOut)
|
||||
{
|
||||
ErrorMessage = "Too many failed attempts. Please try again later.";
|
||||
return Page();
|
||||
}
|
||||
}
|
||||
|
||||
// Generic: does not confirm whether the identifier exists (prevents enumeration).
|
||||
ErrorMessage = "Invalid username/email or password.";
|
||||
return Page();
|
||||
}
|
||||
|
||||
// Ensures the redirect target is local to this application.
|
||||
// Url.IsLocalUrl rejects absolute URLs and protocol-relative URLs,
|
||||
// preventing open redirect attacks where an attacker crafts a link like
|
||||
// /auth/login?returnUrl=https://evil.com
|
||||
private IActionResult SafeRedirect(string? url)
|
||||
=> Url.IsLocalUrl(url) ? LocalRedirect(url) : RedirectToPage("/Index");
|
||||
public IActionResult OnGet(string? returnUrl)
|
||||
=> Redirect("/auth/challenge" + (string.IsNullOrEmpty(returnUrl) ? "" : $"?returnUrl={Uri.EscapeDataString(returnUrl)}"));
|
||||
}
|
||||
|
||||
@@ -1,71 +1,3 @@
|
||||
@page
|
||||
@model RegisterModel
|
||||
@{
|
||||
ViewData["Title"] = "Create Account";
|
||||
}
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
<h1 class="auth-title">Create Account</h1>
|
||||
<p class="auth-subtitle">Begin your journey as a Channeler.</p>
|
||||
|
||||
<form method="post" novalidate>
|
||||
<div asp-validation-summary="ModelOnly" class="alert alert-error"></div>
|
||||
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.Email">Email</label>
|
||||
<input asp-for="Input.Email"
|
||||
type="email"
|
||||
autocomplete="email"
|
||||
autofocus
|
||||
class="form-control"
|
||||
placeholder="you@example.com">
|
||||
<span asp-validation-for="Input.Email" class="field-error"></span>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.DisplayName">Display Name</label>
|
||||
<input asp-for="Input.DisplayName"
|
||||
type="text"
|
||||
autocomplete="nickname"
|
||||
class="form-control"
|
||||
placeholder="Your in-game handle">
|
||||
<span asp-validation-for="Input.DisplayName" class="field-error"></span>
|
||||
<small class="form-hint">3–32 characters. Letters, digits, spaces, hyphens, underscores.</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.Password">Password</label>
|
||||
<input asp-for="Input.Password"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
class="form-control">
|
||||
<span asp-validation-for="Input.Password" class="field-error"></span>
|
||||
<small class="form-hint">At least 8 characters, including an uppercase letter, digit, and symbol.</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.ConfirmPassword">Confirm Password</label>
|
||||
<input asp-for="Input.ConfirmPassword"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
class="form-control">
|
||||
<span asp-validation-for="Input.ConfirmPassword" class="field-error"></span>
|
||||
</div>
|
||||
|
||||
<div class="form-group form-check">
|
||||
<input asp-for="Input.AcceptTerms" type="checkbox" class="form-check-input" id="accept-terms">
|
||||
<label for="accept-terms" class="form-check-label">
|
||||
I agree to the <a href="/terms">Terms of Service</a> and <a href="/privacy">Privacy Policy</a>.
|
||||
</label>
|
||||
<span asp-validation-for="Input.AcceptTerms" class="field-error"></span>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-block">Create Account</button>
|
||||
</form>
|
||||
|
||||
<div class="auth-links">
|
||||
Already have an account? <a href="/auth/login">Log in</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@model SOR.Website.Pages.Auth.RegisterModel
|
||||
@* This page is not rendered — the model redirects to /auth/challenge immediately. *@
|
||||
|
||||
@@ -1,114 +1,15 @@
|
||||
namespace SOR.Website.Pages.Auth;
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using SOR.Database.Entities.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Handles new player registration.
|
||||
///
|
||||
/// Security controls:
|
||||
/// - [EnableRateLimiting]: 5 registrations per IP per hour.
|
||||
/// - Anti-forgery token validated on every POST.
|
||||
/// - Generic error response: does NOT distinguish "email taken" from validation errors
|
||||
/// so an attacker cannot probe whether an email is registered.
|
||||
/// - DisplayName length and character restrictions prevent injection into downstream
|
||||
/// systems that consume this value.
|
||||
/// - Password strength is enforced by Identity (RequireDigit, RequireUppercase, etc.).
|
||||
/// - CreatedAt set server-side — never from user input.
|
||||
/// Local account management is no longer handled by this site — Keycloak owns all
|
||||
/// registration, password reset, and email verification flows.
|
||||
/// Redirects to the Keycloak-hosted login/registration page.
|
||||
/// </summary>
|
||||
[EnableRateLimiting("auth-register")]
|
||||
public sealed class RegisterModel(
|
||||
UserManager<Account> userManager,
|
||||
SignInManager<Account> signInManager) : PageModel
|
||||
public sealed class RegisterModel : PageModel
|
||||
{
|
||||
[BindProperty]
|
||||
public InputModel Input { get; set; } = new();
|
||||
|
||||
public bool Success { get; private set; }
|
||||
|
||||
public sealed class InputModel
|
||||
{
|
||||
[Required(ErrorMessage = "Email is required.")]
|
||||
[EmailAddress(ErrorMessage = "Enter a valid email address.")]
|
||||
[MaxLength(254)]
|
||||
public string Email { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "Display name is required.")]
|
||||
[MinLength(3, ErrorMessage = "Display name must be at least 3 characters.")]
|
||||
[MaxLength(32, ErrorMessage = "Display name cannot exceed 32 characters.")]
|
||||
// Allow letters, digits, spaces, hyphens, underscores only.
|
||||
// This prevents special characters that could cause issues in downstream display.
|
||||
[RegularExpression(@"^[\w\- ]+$",
|
||||
ErrorMessage = "Display name may only contain letters, digits, spaces, hyphens, and underscores.")]
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "Password is required.")]
|
||||
[MinLength(8, ErrorMessage = "Password must be at least 8 characters.")]
|
||||
[MaxLength(128)]
|
||||
[DataType(DataType.Password)]
|
||||
public string Password { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "Please confirm your password.")]
|
||||
[DataType(DataType.Password)]
|
||||
[Compare(nameof(Password), ErrorMessage = "Passwords do not match.")]
|
||||
public string ConfirmPassword { get; set; } = string.Empty;
|
||||
|
||||
[Range(typeof(bool), "true", "true",
|
||||
ErrorMessage = "You must accept the terms and privacy policy.")]
|
||||
public bool AcceptTerms { get; set; }
|
||||
}
|
||||
|
||||
public void OnGet() { }
|
||||
|
||||
public async Task<IActionResult> OnPostAsync()
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return Page();
|
||||
|
||||
var account = new Account
|
||||
{
|
||||
UserName = Input.Email, // Identity uses UserName as the login key
|
||||
Email = Input.Email,
|
||||
DisplayName = Input.DisplayName.Trim(),
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
RankScore = 1000,
|
||||
};
|
||||
|
||||
var result = await userManager.CreateAsync(account, Input.Password);
|
||||
|
||||
if (result.Succeeded)
|
||||
{
|
||||
// Sign in immediately with the display_name claim.
|
||||
var claims = new[] { new Claim("display_name", account.DisplayName ?? string.Empty) };
|
||||
await signInManager.SignInWithClaimsAsync(account, isPersistent: false, claims);
|
||||
return RedirectToPage("/Account/Index");
|
||||
}
|
||||
|
||||
// Do NOT enumerate specific errors back to the user (e.g. "email already taken").
|
||||
// Instead surface a single generic message. Detailed validation errors (password
|
||||
// strength, display name format) are acceptable — they don't expose account info.
|
||||
//
|
||||
// We do add Identity errors but filter out DuplicateEmail/DuplicateUserName to
|
||||
// prevent account enumeration.
|
||||
foreach (var error in result.Errors)
|
||||
{
|
||||
if (error.Code is "DuplicateEmail" or "DuplicateUserName")
|
||||
{
|
||||
// Generic message: attacker cannot learn whether the email is taken.
|
||||
ModelState.AddModelError(string.Empty,
|
||||
"Unable to create account. Please check your details and try again.");
|
||||
}
|
||||
else
|
||||
{
|
||||
ModelState.AddModelError(string.Empty, error.Description);
|
||||
}
|
||||
}
|
||||
|
||||
return Page();
|
||||
}
|
||||
public IActionResult OnGet() => Redirect("/auth/challenge");
|
||||
public IActionResult OnPost() => Redirect("/auth/challenge");
|
||||
}
|
||||
|
||||
@@ -1,56 +1,3 @@
|
||||
@page
|
||||
@model ResetPasswordModel
|
||||
@{
|
||||
ViewData["Title"] = "Reset Password";
|
||||
}
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
<h1 class="auth-title">Reset Password</h1>
|
||||
|
||||
@if (Model.InvalidLink)
|
||||
{
|
||||
<div class="alert alert-error" role="alert">
|
||||
This reset link is missing required parameters. Please request a new one.
|
||||
</div>
|
||||
<a href="/auth/forgot-password" class="btn btn-ghost btn-block">Request Reset Link</a>
|
||||
}
|
||||
else if (Model.Success)
|
||||
{
|
||||
<div class="alert alert-success" role="status">
|
||||
Your password has been reset. You can now log in with your new password.
|
||||
</div>
|
||||
<a href="/auth/login" class="btn btn-primary btn-block">Log In</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" novalidate>
|
||||
@* Token and email from the reset link are hidden — not displayed to user. *@
|
||||
<input type="hidden" asp-for="Input.Token">
|
||||
<input type="hidden" asp-for="Input.Email">
|
||||
|
||||
<div asp-validation-summary="ModelOnly" class="alert alert-error"></div>
|
||||
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.NewPassword">New Password</label>
|
||||
<input asp-for="Input.NewPassword"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
class="form-control">
|
||||
<span asp-validation-for="Input.NewPassword" class="field-error"></span>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label asp-for="Input.ConfirmPassword">Confirm New Password</label>
|
||||
<input asp-for="Input.ConfirmPassword"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
class="form-control">
|
||||
<span asp-validation-for="Input.ConfirmPassword" class="field-error"></span>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-block">Set New Password</button>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@model SOR.Website.Pages.Auth.ResetPasswordModel
|
||||
@* This page is not rendered — the model redirects to /auth/challenge immediately. *@
|
||||
|
||||
@@ -1,97 +1,15 @@
|
||||
namespace SOR.Website.Pages.Auth;
|
||||
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using SOR.Database.Entities.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the reset token and applies a new password.
|
||||
///
|
||||
/// Security controls:
|
||||
/// - [EnableRateLimiting]: 3 per IP per 15 minutes (shared with forgot-password policy).
|
||||
/// - Anti-forgery token validated on POST.
|
||||
/// - Token validated by Identity's built-in TOTP provider — single-use, time-limited.
|
||||
/// - Generic error on invalid/expired token — no detail about why it failed.
|
||||
/// - Email is supplied via query string from the reset link (not from user input).
|
||||
/// It is bound server-side only for the lookup, not displayed back to the user
|
||||
/// in a way that could introduce reflected content.
|
||||
/// - Password must meet the same strength rules as registration (Identity enforces this).
|
||||
/// Local account management is no longer handled by this site — Keycloak owns all
|
||||
/// registration, password reset, and email verification flows.
|
||||
/// Redirects to the Keycloak-hosted login/registration page.
|
||||
/// </summary>
|
||||
[EnableRateLimiting("auth-reset")]
|
||||
public sealed class ResetPasswordModel(UserManager<Account> userManager) : PageModel
|
||||
public sealed class ResetPasswordModel : PageModel
|
||||
{
|
||||
[BindProperty]
|
||||
public InputModel Input { get; set; } = new();
|
||||
|
||||
public bool Success { get; private set; }
|
||||
public bool InvalidLink { get; private set; }
|
||||
|
||||
public sealed class InputModel
|
||||
{
|
||||
// These two come from the query string in the emailed link.
|
||||
// They are not displayed to the user — only used server-side.
|
||||
[Required]
|
||||
public string Token { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
[EmailAddress]
|
||||
[MaxLength(254)]
|
||||
public string Email { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "New password is required.")]
|
||||
[MinLength(8, ErrorMessage = "Password must be at least 8 characters.")]
|
||||
[MaxLength(128)]
|
||||
[DataType(DataType.Password)]
|
||||
public string NewPassword { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "Please confirm your new password.")]
|
||||
[DataType(DataType.Password)]
|
||||
[Compare(nameof(NewPassword), ErrorMessage = "Passwords do not match.")]
|
||||
public string ConfirmPassword { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public IActionResult OnGet([FromQuery] string? token, [FromQuery] string? email)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(email))
|
||||
{
|
||||
InvalidLink = true;
|
||||
return Page();
|
||||
}
|
||||
|
||||
Input.Token = token;
|
||||
Input.Email = email;
|
||||
return Page();
|
||||
}
|
||||
|
||||
public async Task<IActionResult> OnPostAsync()
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return Page();
|
||||
|
||||
var user = await userManager.FindByEmailAsync(Input.Email);
|
||||
|
||||
// If the user doesn't exist, still show success (anti-enumeration).
|
||||
if (user is null || user.IsAi)
|
||||
{
|
||||
Success = true;
|
||||
return Page();
|
||||
}
|
||||
|
||||
var result = await userManager.ResetPasswordAsync(user, Input.Token, Input.NewPassword);
|
||||
|
||||
if (result.Succeeded)
|
||||
{
|
||||
Success = true;
|
||||
return Page();
|
||||
}
|
||||
|
||||
// Generic message — does not reveal whether the token expired, was already used,
|
||||
// or the email was wrong. All failure modes look the same to the requester.
|
||||
ModelState.AddModelError(string.Empty,
|
||||
"This reset link is invalid or has expired. Please request a new one.");
|
||||
return Page();
|
||||
}
|
||||
public IActionResult OnGet() => Redirect("/auth/challenge");
|
||||
public IActionResult OnPost() => Redirect("/auth/challenge");
|
||||
}
|
||||
|
||||
@@ -1,34 +1,3 @@
|
||||
@page
|
||||
@model VerifyEmailModel
|
||||
@{
|
||||
ViewData["Title"] = "Verify Email";
|
||||
}
|
||||
|
||||
<div class="auth-page">
|
||||
<div class="auth-card">
|
||||
<h1 class="auth-title">Email Verification</h1>
|
||||
|
||||
@if (Model.Success)
|
||||
{
|
||||
<div class="alert alert-success" role="status">
|
||||
Your email has been verified. Your account is fully active.
|
||||
</div>
|
||||
<a href="/account" class="btn btn-primary btn-block">Go to Account</a>
|
||||
}
|
||||
else if (Model.AlreadyVerified)
|
||||
{
|
||||
<div class="alert alert-info" role="status">
|
||||
Your email is already verified.
|
||||
</div>
|
||||
<a href="/account" class="btn btn-ghost btn-block">Go to Account</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="alert alert-error" role="alert">
|
||||
This verification link is invalid or has expired.
|
||||
Please log in and request a new verification email.
|
||||
</div>
|
||||
<a href="/auth/login" class="btn btn-ghost btn-block">Log In</a>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@model SOR.Website.Pages.Auth.VerifyEmailModel
|
||||
@* This page is not rendered — the model redirects to /auth/challenge immediately. *@
|
||||
|
||||
@@ -1,55 +1,15 @@
|
||||
namespace SOR.Website.Pages.Auth;
|
||||
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using SOR.Database.Entities.Identity;
|
||||
|
||||
/// <summary>
|
||||
/// Confirms a player's email address via a one-time token link.
|
||||
///
|
||||
/// Security controls:
|
||||
/// - Token validated by Identity's built-in provider (single-use, time-limited).
|
||||
/// - Generic error shown on failure — no detail about whether email or token was wrong.
|
||||
/// - This page does not require authentication — players reach it by clicking a link
|
||||
/// in their registration email before they're signed in.
|
||||
/// Local account management is no longer handled by this site — Keycloak owns all
|
||||
/// registration, password reset, and email verification flows.
|
||||
/// Redirects to the Keycloak-hosted login/registration page.
|
||||
/// </summary>
|
||||
public sealed class VerifyEmailModel(UserManager<Account> userManager) : PageModel
|
||||
public sealed class VerifyEmailModel : PageModel
|
||||
{
|
||||
public bool Success { get; private set; }
|
||||
public bool AlreadyVerified { get; private set; }
|
||||
public bool Failed { get; private set; }
|
||||
|
||||
public async Task<IActionResult> OnGetAsync(
|
||||
[FromQuery] string? userId,
|
||||
[FromQuery] string? token)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
Failed = true;
|
||||
return Page();
|
||||
}
|
||||
|
||||
var user = await userManager.FindByIdAsync(userId);
|
||||
if (user is null)
|
||||
{
|
||||
// Anti-enumeration: don't reveal that the userId is invalid.
|
||||
Failed = true;
|
||||
return Page();
|
||||
}
|
||||
|
||||
if (user.EmailConfirmed)
|
||||
{
|
||||
AlreadyVerified = true;
|
||||
return Page();
|
||||
}
|
||||
|
||||
var result = await userManager.ConfirmEmailAsync(user, token);
|
||||
if (result.Succeeded)
|
||||
Success = true;
|
||||
else
|
||||
Failed = true;
|
||||
|
||||
return Page();
|
||||
}
|
||||
public IActionResult OnGet() => Redirect("/auth/challenge");
|
||||
public IActionResult OnPost() => Redirect("/auth/challenge");
|
||||
}
|
||||
|
||||
@@ -228,10 +228,21 @@ app.UseAuthorization();
|
||||
app.MapGet("/auth/challenge", async (HttpContext ctx,
|
||||
[Microsoft.AspNetCore.Mvc.FromQuery] string? returnUrl) =>
|
||||
{
|
||||
// Validate returnUrl is local before trusting it — prevents open-redirect abuse
|
||||
// where an attacker crafts /auth/challenge?returnUrl=https://evil.com and the
|
||||
// user gets bounced there after a legitimate Keycloak login.
|
||||
var safeReturn = IsLocalUrl(returnUrl) ? returnUrl! : "/";
|
||||
await ctx.ChallengeAsync("Keycloak",
|
||||
new AuthenticationProperties { RedirectUri = returnUrl ?? "/" });
|
||||
new AuthenticationProperties { RedirectUri = safeReturn });
|
||||
}).AllowAnonymous();
|
||||
|
||||
// Guard: old local-password auth routes no longer work (SignInManager is not registered).
|
||||
// Redirect them to the Keycloak challenge so visitors get a working login flow instead of a 500.
|
||||
app.MapGet("/auth/login", () => Results.Redirect("/auth/challenge")).AllowAnonymous();
|
||||
app.MapGet("/auth/register", () => Results.Redirect("/auth/challenge")).AllowAnonymous();
|
||||
app.MapGet("/auth/forgot-password",() => Results.Redirect("/auth/challenge")).AllowAnonymous();
|
||||
app.MapGet("/auth/reset-password", () => Results.Redirect("/auth/challenge")).AllowAnonymous();
|
||||
|
||||
// Logout: signs out of the local cookie AND the Keycloak SSO session so the
|
||||
// player must re-authenticate on both the website and the webclient.
|
||||
app.MapPost("/auth/logout", async (HttpContext ctx) =>
|
||||
@@ -253,6 +264,17 @@ await app.RunAsync();
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
// Mirrors ASP.NET Core's Url.IsLocalUrl logic.
|
||||
// Rejects absolute URLs (https://evil.com), protocol-relative URLs (//evil.com),
|
||||
// and backslash variants (/\evil.com) that some parsers treat as path separators.
|
||||
static bool IsLocalUrl(string? url)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url)) return false;
|
||||
if (url[0] != '/') return false;
|
||||
if (url.Length == 1) return true;
|
||||
return url[1] != '/' && url[1] != (char)0x5C; // 0x5C = backslash
|
||||
}
|
||||
|
||||
static async Task CheckOidcDiscoveryAsync(WebApplication app)
|
||||
{
|
||||
var opts = app.Services
|
||||
|
||||
Reference in New Issue
Block a user