Adds Blazor Web App standard login
This commit is contained in:
@@ -1,87 +1,137 @@
|
||||
using WatchLog.Components;
|
||||
using WatchLog.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using WatchLog.Components;
|
||||
using WatchLog.Components.Account;
|
||||
using WatchLog.Data;
|
||||
|
||||
namespace WatchLog
|
||||
{
|
||||
public class Program
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
builder.Services.AddCascadingAuthenticationState();
|
||||
builder.Services.AddScoped<IdentityUserAccessor>();
|
||||
builder.Services.AddScoped<IdentityRedirectManager>();
|
||||
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
|
||||
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
options.DefaultScheme = IdentityConstants.ApplicationScheme;
|
||||
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
|
||||
})
|
||||
.AddIdentityCookies();
|
||||
|
||||
var connectionString = builder.Configuration.GetConnectionString("WatchLogDB") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
|
||||
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
||||
options.UseSqlite(connectionString));
|
||||
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
|
||||
|
||||
builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
|
||||
.AddRoles<IdentityRole>() // <-- Das ist der wichtige Zusatz
|
||||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||||
.AddSignInManager()
|
||||
.AddDefaultTokenProviders();
|
||||
|
||||
builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseMigrationsEndPoint();
|
||||
}
|
||||
else
|
||||
{
|
||||
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
|
||||
app.UseAntiforgery();
|
||||
|
||||
app.MapStaticAssets();
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
// Add additional endpoints required by the Identity /Account Razor components.
|
||||
app.MapAdditionalIdentityEndpoints();
|
||||
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
||||
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>(); // UserManager hinzufügen
|
||||
|
||||
string[] roleNames = { "Admin", "User" };
|
||||
IdentityResult roleResult;
|
||||
|
||||
foreach (var roleName in roleNames)
|
||||
{
|
||||
var roleExist = await roleManager.RoleExistsAsync(roleName);
|
||||
if (!roleExist)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
var connectionString = builder.Configuration.GetConnectionString("WatchLogDB");
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
builder.Services.AddDbContextFactory<WatchLogDataContext>(options => options.UseSqlite(connectionString));
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
|
||||
builder.Services.AddIdentityCore<AppUser>(options =>
|
||||
{
|
||||
// Hier könntest du Passwortregeln festlegen, z.B.
|
||||
options.Password.RequireDigit = false;
|
||||
options.Password.RequireNonAlphanumeric = false;
|
||||
options.Password.RequiredLength = 4; // Nur für Entwicklung!
|
||||
})
|
||||
.AddSignInManager() // Fügt den SignInManager hinzu, der den Login-Prozess steuert.
|
||||
.AddDefaultTokenProviders(); // Nötig für Features wie Passwort-Reset.
|
||||
|
||||
// 2. Jetzt sagen wir Identity, welche Klassen es für seine Aufgaben verwenden soll.
|
||||
// Dies ist der wichtigste Teil!
|
||||
builder.Services.AddScoped<IUserStore<AppUser>, MyUserStore>();
|
||||
builder.Services.AddScoped<IPasswordHasher<AppUser>, PasswordHasher<AppUser>>();
|
||||
|
||||
// 3. Da wir IdentityCore verwenden, müssen wir die Cookie-Authentifizierung selbst hinzufügen.
|
||||
// Die Konfiguration ist fast identisch zu deiner alten, aber sie ist jetzt
|
||||
// an das Identity-System gekoppelt.
|
||||
builder.Services.AddAuthentication(IdentityConstants.ApplicationScheme)
|
||||
.AddCookie(IdentityConstants.ApplicationScheme, options =>
|
||||
{
|
||||
options.Cookie.Name = "WatchLogAuthCookie";
|
||||
options.LoginPath = "/login";
|
||||
options.LogoutPath = "/logout";
|
||||
options.AccessDeniedPath = "/access-denied";
|
||||
options.ExpireTimeSpan = TimeSpan.FromDays(1);
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
|
||||
// 4. Die Autorisierungs-Policy ist perfekt und bleibt genau so!
|
||||
// Sie sorgt dafür, dass alle Seiten standardmäßig einen Login erfordern.
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
|
||||
});
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Error");
|
||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseStaticFiles();
|
||||
app.UseAntiforgery();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
app.Run();
|
||||
roleResult = await roleManager.CreateAsync(new IdentityRole(roleName));
|
||||
}
|
||||
}
|
||||
|
||||
// --- HIER BEGINNT DER NEUE TEIL ---
|
||||
// Erstellt den Admin-Benutzer und weist ihm die Admin-Rolle zu.
|
||||
// WICHTIG: Ändere hier die E-Mail-Adresse und das Passwort!
|
||||
var adminEmail = "admin@deine-app.de";
|
||||
var adminPassword = "EinSehrSicheresPasswort123!"; // Nur für lokale Entwicklung, besser aus Konfiguration laden
|
||||
var normalUserEmail = "user@deine-app.de";
|
||||
|
||||
// Sucht nach dem Benutzer anhand der E-Mail.
|
||||
var adminUser = await userManager.FindByEmailAsync(adminEmail);
|
||||
var normalUser = await userManager.FindByEmailAsync(normalUserEmail);
|
||||
|
||||
// Wenn der Admin-Benutzer NICHT existiert, erstellen wir ihn.
|
||||
if (adminUser == null)
|
||||
{
|
||||
adminUser = new ApplicationUser
|
||||
{
|
||||
UserName = adminEmail,
|
||||
Email = adminEmail,
|
||||
EmailConfirmed = true // Wichtig, damit er sich direkt einloggen kann
|
||||
};
|
||||
// Erstellt den Benutzer mit dem definierten Passwort.
|
||||
var createResult = await userManager.CreateAsync(adminUser, adminPassword);
|
||||
|
||||
// Wenn die Erstellung erfolgreich war, weisen wir die Admin-Rolle zu.
|
||||
if (createResult.Succeeded)
|
||||
{
|
||||
await userManager.AddToRoleAsync(adminUser, "Admin");
|
||||
}
|
||||
}
|
||||
else if (normalUser == null)
|
||||
{
|
||||
normalUser = new ApplicationUser
|
||||
{
|
||||
UserName = normalUserEmail,
|
||||
Email = normalUserEmail,
|
||||
EmailConfirmed = true
|
||||
};
|
||||
var createResult = await userManager.CreateAsync(normalUser, adminPassword);
|
||||
|
||||
if (createResult.Succeeded)
|
||||
{
|
||||
await userManager.AddToRoleAsync(adminUser, "User");
|
||||
}
|
||||
}
|
||||
else if (!await userManager.IsInRoleAsync(normalUser, "User"))
|
||||
{
|
||||
await userManager.AddToRoleAsync(normalUser, "User");
|
||||
}
|
||||
// Optional: Wenn der Benutzer bereits existiert, aber kein Admin ist.
|
||||
else if (!await userManager.IsInRoleAsync(adminUser, "Admin"))
|
||||
{
|
||||
await userManager.AddToRoleAsync(adminUser, "Admin");
|
||||
}
|
||||
}
|
||||
|
||||
app.Run();
|
||||
Reference in New Issue
Block a user