Add ASP.NET Identity (cookie auth) and role seeding
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
|
||||
namespace backend.Auth;
|
||||
|
||||
public class ApplicationUser : IdentityUser<Guid>
|
||||
{
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
Reference in New Issue
Block a user