首页 > 解决方案 > Cookie 身份验证在 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();
    }
}

为了实现基于 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 类的配置方法是:

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?}");
    });
}

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

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

发生的异常如下所示:

InvalidOperationException:没有为方案“Identity.Application”注册登录身份验证处理程序。注册的登录方案是: Cookies。您是否忘记调用 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);

谁能给我解决问题的建议。

标签: c#asp.net-coreasp.net-core-mvc

解决方案


没有为方案“Identity.Application”注册登录身份验证处理程序。注册的登录方案是: 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

测试结果

在此处输入图像描述


推荐阅读