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

时间:2020-03-07 18:30:53

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

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

# allows image files to bypass cors @jkr
<Files *.jpg>
  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Credentials "true"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
  Header always set Access-Control-Max-Age "1000"
  Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</Files>

#always allow preflight to pass @jkr
<LimitExcept OPTIONS>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} OPTIONS
  RewriteRule ^(.*)$ $1 [R=200,L]
</LimitExcept>

要实现基于cookie的身份验证,我将以下代码放在Startup类的ConfigureService方法中:

[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();
    }
}

启动类的配置方法是:

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

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

等待HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, 校长)

发生的异常如下:

InvalidOperationException:没有登录身份验证处理程序是 注册了“ Identity.Application”方案。已注册 登录方案为:Cookies。你忘了打电话吗 AddAuthentication()。AddCookies(“ Identity.Application”,...)? Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext 上下文,字符串方案,ClaimsPrincipal主体, AuthenticationProperties属性) _01_AuthenticationDemo.Controllers.AccountController.Login(UserLoginModel userModel)在AccountController.cs中 + 等待HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, 校长);

谁能给我建议解决这个问题。

2 个答案:

答案 0 :(得分:3)

没有为方案“ 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

测试结果

enter image description here

答案 1 :(得分:0)

我会在这里留下这条评论,以防它对任何人有帮助。

我花了 2 天时间尝试获得 cookie 身份验证,然后只是在我的 .NET Core 3.1 站点上运行了一个基本的会话身份验证登录页面。

结果是我的广告平台(Ezoic)导致了这个问题。他们基本上使用某种代理系统,将请求发送到他们的服务器,然后他们的服务器向我的服务器发出请求(反向代理?)。无论如何,如果您使用的是 CDN 或广告服务器或类似的东西,那么这可能是一个问题。

就我而言,另一个线索是我的网站在本地主机上运行良好,但在生产服务器上运行不正常。

为了解决这个问题,广告公司说我可以在我的网站上添加一个 X-Forwarded-For 标头,但尽管按照有关将适当的行添加到 Startup.cs 的说明进行操作,但我还是无法使其正常工作.