Files

52 lines
1.6 KiB
C#

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));
}
}
}