Ich habe versucht, die Cookie-Middleware von ASP.NET Core zu verwenden, um eine benutzerdefinierte Autorisierung wie in der offiziellen asp.net-Dokumentation (https://docs.asp.net/en/latest/security/authentication/cookie.html) erwähnt zu erstellen.Cookie Middleware Cookie nicht richtig setzen
Leider funktioniert es nicht in meinem ASP.NET MVC-Projekt, kein Cookie wird nach dem Aufruf von "HttpContext.Authentication.SignInAsync" festgelegt.
Hier ist meine aktuellen Code:
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "CookieInstance",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieSecure = env.IsDevelopment()
? CookieSecurePolicy.None
: CookieSecurePolicy.Always
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Anmeldung Controller-
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid && model.Email == "[email protected]")
{
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "Kev", ClaimValueTypes.String)
};
var userIdentity = new ClaimsIdentity(claims, "CookieInstance");
var userPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.Authentication.SignInAsync("CookieInstance", userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
});
return RedirectToLocal(returnUrl);
} else { ... }
...
}
Er leitet mich erfolgreich Seite zu korrigieren, aber apparentely kein Cookie eingestellt sein. wie zum Beispiel SignInManager.IsSignedIn (Benutzer) gibt immer noch falsch zurück.
Hat jemand eine Lösung?
dank
Haben Sie die Webbrowser-Entwicklungstools verwendet, um zu bestätigen, dass kein Cookie erstellt wurde? Ich denke, dass Sie auch eine ClaimTypes.NameIdentifier Anspruch –
beachten Sie auch, dass SignInManager Teil des Identity-Systems ist, die es nicht wie Sie aussieht, da Sie Ihre eigene Cookie-Middleware einrichten –