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

mnu*_*sir 6 c# asp.net-core-mvc asp.net-core

我正在尝试在 .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();
    }
}
Run Code Online (Sandbox Code Playgroud)

为了实现基于 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);
}
Run Code Online (Sandbox Code Playgroud)

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?}");
    });
}
Run Code Online (Sandbox Code Playgroud)

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

等待 HttpContext.SignInAsync(IdentityConstants.ApplicationScheme,主体)

发生的异常情况如下:

InvalidOperationException:没有为方案“Identity.Application”注册登录身份验证处理程序。注册的登录方案有: Cookie。您是否忘记调用 AddAuthentication().AddCookies("Identity.Application",...)?Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext上下文,字符串方案,ClaimsPrincipal主体,AuthenticationProperties属性)AccountController.cs中的_01_AuthenticationDemo.Controllers.AccountController.Login(UserLoginModel userModel)+等待HttpContext.SignInAsync(IdentityConstants.ApplicationScheme,主体);

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

Fei*_*Han 5

没有为方案“Identity.Application”注册登录身份验证处理程序。注册的登录方案有: Cookie。

请用 指定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");
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看:https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie ?view=aspnetcore-3.1#create-an-authentication-cookie

测试结果

在此输入图像描述