Add protected admin scope with login

This commit is contained in:
Francesco Lorenzo D'Amico
2026-08-18 14:56:41 +02:00
parent dfe5044c69
commit 04877691b9
7 changed files with 178 additions and 9 deletions
+15
View File
@@ -0,0 +1,15 @@
using System.ComponentModel.DataAnnotations;
namespace RazorPagesMovie.Models;
public class AdminUser
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Username { get; set; } = string.Empty;
[Required]
public string PasswordHash { get; set; } = string.Empty;
}
+11
View File
@@ -0,0 +1,11 @@
@page
@model RazorPagesMovie.Pages.Admin.IndexModel
@{
ViewData["Title"] = "Admin";
}
<h1>Welcome, @User.Identity?.Name</h1>
<form method="post" asp-page-handler="Logout">
<button type="submit" class="btn btn-secondary">Logout</button>
</form>
@@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RazorPagesMovie.Pages.Admin;
public class IndexModel : PageModel
{
public void OnGet()
{
}
public async Task<IActionResult> OnPostLogoutAsync()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToPage("/Login");
}
}
+28
View File
@@ -0,0 +1,28 @@
@page
@model RazorPagesMovie.Pages.LoginModel
@{
ViewData["Title"] = "Login";
}
<div class="row justify-content-center">
<div class="col-md-4">
<h1>Admin Login</h1>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">@Model.ErrorMessage</div>
}
<form method="post">
<div class="mb-3">
<label asp-for="Username" class="form-label"></label>
<input asp-for="Username" class="form-control" autofocus />
</div>
<div class="mb-3">
<label asp-for="Password" class="form-label"></label>
<input asp-for="Password" type="password" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
+53
View File
@@ -0,0 +1,53 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;
using RazorPagesMovie.Models;
namespace RazorPagesMovie.Pages;
public class LoginModel : PageModel
{
private readonly RazorPagesMovieContext _context;
public LoginModel(RazorPagesMovieContext context)
{
_context = context;
}
[BindProperty]
public string Username { get; set; } = string.Empty;
[BindProperty]
public string Password { get; set; } = string.Empty;
public string? ErrorMessage { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync(string? returnUrl)
{
var user = await _context.AdminUser.SingleOrDefaultAsync(u => u.Username == Username);
var hasher = new PasswordHasher<AdminUser>();
if (user is null || hasher.VerifyHashedPassword(user, user.PasswordHash, Password) == PasswordVerificationResult.Failed)
{
ErrorMessage = "Benutzername oder Passwort ist falsch.";
return Page();
}
var identity = new ClaimsIdentity(
new[] { new Claim(ClaimTypes.Name, user.Username) },
CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
return LocalRedirect(returnUrl ?? "/Admin");
}
}
+15 -1
View File
@@ -1,3 +1,4 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;
using RazorPagesMovie.Models;
@@ -6,7 +7,19 @@ var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.Local.json", optional: true, reloadOnChange: true);
builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));
builder.Services.AddRazorPages();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Login";
options.AccessDeniedPath = "/Login";
});
builder.Services.AddAuthorization();
builder.Services.AddRazorPages(options =>
{
options.Conventions.AuthorizeFolder("/Admin");
});
var app = builder.Build();
@@ -27,6 +40,7 @@ if (!app.Environment.IsDevelopment())
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
+37 -8
View File
@@ -1,4 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using RazorPagesMovie.Data;
namespace RazorPagesMovie.Models;
@@ -15,18 +17,45 @@ public static class SeedData
throw new ArgumentNullException("Null RazorPagesMovieContext");
}
if (context.Movie.Any())
if (!context.Movie.Any())
{
return;
}
context.Movie.AddRange(
context.Movie.AddRange(
new Movie { Title = "When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-2-12"), Genre = "Romantic Comedy", Price = 7.99M, Rating = "R" },
new Movie { Title = "Ghostbusters", ReleaseDate = DateTime.Parse("1984-3-13"), Genre = "Comedy", Price = 8.99M, Rating = "G" },
new Movie { Title = "Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre = "Comedy", Price = 9.99M, Rating = "G" },
new Movie { Title = "Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre = "Western", Price = 3.99M, Rating = "NR" }
);
context.SaveChanges();
);
context.SaveChanges();
}
if (!context.AdminUser.Any())
{
var accounts = serviceProvider.GetRequiredService<IConfiguration>()
.GetSection("AdminAccounts")
.Get<List<AdminAccountSeed>>() ?? new List<AdminAccountSeed>();
var hasher = new PasswordHasher<AdminUser>();
foreach (var account in accounts)
{
if (string.IsNullOrWhiteSpace(account.Username) || string.IsNullOrWhiteSpace(account.Password))
{
continue;
}
var user = new AdminUser { Username = account.Username };
user.PasswordHash = hasher.HashPassword(user, account.Password);
context.AdminUser.Add(user);
}
context.SaveChanges();
}
}
}
private class AdminAccountSeed
{
public string Username { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}
}