gpt4 book ai didi

c# - Cookie 身份验证在 ASP.NET Core 应用程序中不起作用

转载 作者:行者123 更新时间:2023-12-04 01:32:45 28 4
gpt4 key购买 nike

我正在尝试在 .NET Core 3.1 中开发一个项目。我正在尝试在我的项目中实现基于 cookie 的身份验证。我的登录功能是:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(UserLoginModel userModel)
{
if (!ModelState.IsValid)
{
return View(userModel);
}

if (userModel.Email == "admin@test.com" && userModel.Password == "123")
{
var identity = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "User Id"));
identity.AddClaim(new Claim(ClaimTypes.Name, "User Name"));

var principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);

return RedirectToAction(nameof(HomeController.Index), "Home");
}
else
{
ModelState.AddModelError("", "Invalid UserName or Password");
return View();
}
}

为了实现基于 cookie 的身份验证,我将以下代码放在 Startup 类的 ConfigureService 方法中:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();

services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "_auth";
options.Cookie.HttpOnly = true;
options.LoginPath = new PathString("/account/login");
options.LogoutPath = new PathString("/account/logout");
options.AccessDeniedPath = new PathString("/account/login");
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.SlidingExpiration = false;
});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
}

而Startup类的configure方法是:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

但问题是每次尝试登录时,登录操作方法的以下代码中都会出现以下异常。

await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal)



发生的异常如下:

InvalidOperationException: No sign-in authentication handler is registered for the scheme 'Identity.Application'. The registered sign-in schemes are: Cookies. Did you forget to call AddAuthentication().AddCookies("Identity.Application",...)? Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties) _01_AuthenticationDemo.Controllers.AccountController.Login(UserLoginModel userModel) in AccountController.cs + await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, principal);



任何人都可以给我解决问题的建议。

最佳答案

No sign-in authentication handler is registered for the scheme 'Identity.Application'. The registered sign-in schemes are: Cookies.


请用 CookieAuthenticationDefaults.AuthenticationScheme指定,如下图。
if (userModel.Email == "admin@test.com" && userModel.Password == "123")
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "User Id"));
identity.AddClaim(new Claim(ClaimTypes.Name, "User Name"));

var principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

return RedirectToAction(nameof(HomeController.Index), "Home");
}
更多信息请查看: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1#create-an-authentication-cookie
测试结果 enter image description here

关于c# - Cookie 身份验证在 ASP.NET Core 应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60580907/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com