【问题标题】:ASP.NET Core 2.0 Authentication Cookie not set未设置 ASP.NET Core 2.0 身份验证 Cookie
【发布时间】:2018-03-30 00:50:35
【问题描述】:

我按照 Microsoft 的这篇文章 (https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x) 在我的 .NET Core 2.0 MVC 应用程序中迁移了我的身份验证过程。

Startup.cs (ConfigureServices)

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

services.AddAuthentication("MyCookieAuthenticationScheme")
        .AddCookie("MyCookieAuthenticationScheme", options => {
            options.AccessDeniedPath = "/Account/Forbidden/";
            options.LoginPath = "/Account/Login/";
        });

Startup.cs(配置)

app.UseAuthentication();

AccountController.cs

List<Claim> claims = new List<Claim> {
                        new Claim(ClaimTypes.Name, "testUser"),
                        new Claim(ClaimTypes.Email, model.Email),
                        //new Claim("ID", user.ID.ToString(), ClaimValueTypes.Integer),
                        new Claim(ClaimTypes.Role, "Admin")
                    };

ClaimsIdentity identity = new ClaimsIdentity(claims, "MyCookieAuthenticationScheme");

ClaimsPrincipal principal = new ClaimsPrincipal(identity);

await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal, new AuthenticationProperties
{
    IsPersistent = false
});

不幸的是,我的 .NET Cookie 从未设置。这意味着 User.Identity.IsAuthenticated 始终为假。我尝试了许多 cookie 选项,例如将 Cookie.SameSite 或 Cookie.SecurePolicy 更改为所有可能的值。

我使用 Visual Studio 2017、localhost over https、Chrome 61。

【问题讨论】:

  • 您是否真的检查过是否没有设置 cookie 或者您只是在假设因为您无法进行身份验证?检查浏览器开发者控制台的 cookie,因为我很确定这段代码会设置 cookie。
  • 呃,你是对的。我刚刚检查了控制台并生成了它。你知道为什么不会设置身份吗?
  • 您能否删除 AddIdentity(...) 并在身份验证期间为其提供一些固定值以查看问题是否出在身份上,因为此代码非常简单并且可以正常工作。跨度>
  • 如果我删除它,它会在调用其中包含 UserManager 的任何视图时立即失败:InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[PTCConnector.Models.ApplicationUser] ' 已注册。
  • @Rob 我的解决方案现在可以工作了:诀窍是您的所有组件都需要引用相同的身份 ID。所以我需要在 AddAuthentication..的选项中将 DefaultChallengeScheme、DefaultAuthenticateScheme 和 DefaultScheme 设置为 MyCookieAuthenticationScheme。

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


【解决方案1】:

假设您在localhost 上为您的应用程序提供服务,似乎Chrome browser 没有为IP 或内部网主机名(如localhost)设置cookie。您可以从 IIS 为您的应用程序提供服务,并使用具有有效主机名的绑定。

【讨论】:

  • 我已经检查过了,Chrome 确实在 localhost 上设置了 cookie。
  • 当我遇到这个时,我正要烧掉我的笔记本电脑。然后我在 FF 中尝试了它并按预期工作.. Chrome....
  • 我只需要重启 chrome
【解决方案2】:

我认为您应该使用 Identity 的 UserManager 类而不是 HttpContext.SignInAsync 来提供登录过程。将 IUserManager 注入到你的控制器构造函数中,并使用它来登录。

AccountController: Controller
{
    private readonly SignInManager<ApplicationUser> _signInManager;

    public AccountController(SignInManager<ApplicationUser> singInManager)
    {
        _signInManager = signInManager;
    }

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
        ...
    }

}

您可以在 Startup.cs 中修改 Identity 的 cookie 设置。看一眼:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity

【讨论】:

  • 我使用的是 MySQL 数据库,所以我需要覆盖 PasswordSignInAsync 方法。我认为cookie身份验证会更容易。但似乎我会这样。
  • 这对我来说也是合适的方法,HttpContext 方法不起作用,这确实有效
【解决方案3】:

在为 .NET Core 2.0 升级我们网站的身份验证系统时,我必须更新我们的控制器方法以使用 AuthenticationHttpContextExtensions.SignInAsync() 方法而不是旧的 HttpContext.SignInAsync()

例子:

public async Task ClaimsLogin() {

    // Claims identity creation here...

    ClaimsPrincipal principal = new ClaimsPrincipal(identity);

    await Task.FromResult(
        AuthenticationHttpContextExtensions.SignInAsync(
            this.httpContextAccessor.HttpContext,
            "NameOfYourCookieHere",
            userPrincipal,
            new AuthenticationProperties()
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(2880),
                IsPersistent = false,
                AllowRefresh = false
            }));
}

希望这对某人有所帮助!

【讨论】:

  • 投反对票,因为AuthenticationHttpContextExtensions.SignInAsync 只是HttpContext.SignInAsync() 上的扩展方法,因此它们是同一回事。
【解决方案4】:

我遇到了同样的问题,在尝试了数小时的谷歌搜索和 stackoverflow 答案后,尽管从 SignInManager 获得了成功,但我无法登录。 所以添加了我解决问题的方法 .AspNetCore.Identity.Application 手动在cookie名称中,并在值字段中添加了一个随机令牌,然后我就能够成功登录。再次注销后,身份令牌从 cookie 中消失了,但再次登录后,这次它进入了 cookie。

我希望这个过程可以帮助像我一样经历过的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-19
    • 2017-03-30
    • 2018-01-28
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 2018-07-19
    • 2018-06-23
    相关资源
    最近更新 更多