Kurse:Identity & Authorization

Aus ahrensburg.city
Zur Navigation springen Zur Suche springen
// Benutzerregistrierung
ApplicationUser user = new ApplicationUser { UserName = registerDTO.Email, Email = registerDTO.Email };
IdentityResult result = await _userManager.CreateAsync(user, registerDTO.Password);

// Benutzer anmelden
var result = await _signInManager.PasswordSignInAsync(
    loginDTO.Email,
    loginDTO.Password,
    isPersistent: false,
    lockoutOnFailure: false);

// Rolle prüfen
if (await _userManager.IsInRoleAsync(user, "Admin")) {
    // Admin-spezifische Logik
}

// Rolle erstellen (falls nicht vorhanden)
if (!await _roleManager.RoleExistsAsync("Admin")) {
    await _roleManager.CreateAsync(new ApplicationRole("Admin"));
}

// Benutzer zu Rolle hinzufügen
await _userManager.AddToRoleAsync(user, "Admin");

// Benutzer abmelden
await _signInManager.SignOutAsync();

// E-Mail prüfen (bereits registriert?)
var existingUser = await _userManager.FindByEmailAsync(email);
return Json(existingUser == null);

// [Authorize] zum Schutz von Aktionen
[Authorize]
public IActionResult ProtectedAction() { ... }

// [AllowAnonymous] für anonyme Zugriffe
[AllowAnonymous]
public IActionResult PublicAction() { ... }

// [ValidateAntiForgeryToken] gegen CSRF
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult SubmitForm() { ... }

// Benutzerdefinierte Richtlinie in Program.cs
builder.Services.AddAuthorization(options => {
    options.AddPolicy("NotAuthorized", policy => policy.RequireAssertion(
        context => !context.User.Identity.IsAuthenticated));
});

// Identity-Konfiguration in Program.cs
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>(options => {
    options.Password.RequiredLength = 8;
    options.Password.RequireNonAlphanumeric = true;
}).AddEntityFrameworkStores<ApplicationDbContext>()
  .AddDefaultTokenProviders();

// Identity-Cookie konfigurieren
builder.Services.ConfigureApplicationCookie(options => {
    options.LoginPath = "/Account/Login";
});