Add ASP.NET Identity (cookie auth) and role seeding

This commit is contained in:
2026-06-11 18:26:34 +00:00
parent 824a27520d
commit 8a7d01ac9e
9 changed files with 815 additions and 3 deletions
+7
View File
@@ -0,0 +1,7 @@
using Microsoft.AspNetCore.Identity;
namespace backend.Auth;
public class ApplicationUser : IdentityUser<Guid>
{
}
+51
View File
@@ -0,0 +1,51 @@
using backend.Data;
using Microsoft.AspNetCore.Identity;
namespace backend.Auth;
public static class IdentitySetup
{
public static IServiceCollection AddAppIdentity(this IServiceCollection services)
{
services.AddIdentity<ApplicationUser, IdentityRole<Guid>>(opt =>
{
opt.Password.RequiredLength = 8;
opt.Password.RequireNonAlphanumeric = false;
opt.User.RequireUniqueEmail = true;
opt.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(opt =>
{
opt.Cookie.HttpOnly = true;
opt.Cookie.SameSite = SameSiteMode.Lax;
opt.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
opt.ExpireTimeSpan = TimeSpan.FromDays(30);
opt.SlidingExpiration = true;
opt.Events.OnRedirectToLogin = ctx =>
{
ctx.Response.StatusCode = 401;
return Task.CompletedTask;
};
opt.Events.OnRedirectToAccessDenied = ctx =>
{
ctx.Response.StatusCode = 403;
return Task.CompletedTask;
};
});
return services;
}
public static async Task SeedRolesAsync(IServiceProvider sp)
{
var roleMgr = sp.GetRequiredService<RoleManager<IdentityRole<Guid>>>();
foreach (var name in Roles.All)
{
if (!await roleMgr.RoleExistsAsync(name))
await roleMgr.CreateAsync(new IdentityRole<Guid>(name));
}
}
}
+9
View File
@@ -0,0 +1,9 @@
namespace backend.Auth;
public static class Roles
{
public const string Admin = "Admin";
public const string User = "User";
public static readonly string[] All = { Admin, User };
}