.NET Core Cookie身份验证SignInAsync无法正常工作

时间:2017-07-14 10:05:36

标签: c# asp.net-core

我使用AspNetCore.Authentication.Cookies进行基于cookie身份验证的核心项目,但我似乎无法让用户进行身份验证。我已经阅读了类似的线程,但提供的解决方案似乎都没有用。

[HttpPost]
public async Task<IActionResult> CookieAuth(ITwitterCredentials userCreds)
{
    var claims = new[] {
        new Claim("AccessToken" , userCreds.AccessToken),
        new Claim("AccessTokenSecret", userCreds.AccessTokenSecret)
    };

    var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "CookieAuthentication"));

    await HttpContext.Authentication.SignInAsync("CookieAuthentication", principal);

    return Ok();
}

和startup.cs配置方法

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AuthenticationScheme = "CookieAuthentication",
    LoginPath = new PathString("/"),
    AccessDeniedPath = new PathString("/"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

用户似乎没有进行身份验证,因为HttpContext.User.Identity.IsAuthenticated始终返回false。

知道为什么这可能不起作用?

5 个答案:

答案 0 :(得分:4)

从.net 2.x开始,如果您使用的是Cookie身份验证,请确保您包含authenticationScheme,identity和auth属性。

var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);

identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, email));
identity.AddClaim(new Claim(ClaimTypes.Name, email));
identity.AddClaim(new Claim(ClaimTypes.Role, "User"));

var principal = new ClaimsPrincipal(identity);

var authProperties = new AuthenticationProperties
{
    AllowRefresh = true,
    ExpiresUtc = DateTimeOffset.Now.AddDays(1),
    IsPersistent = true,
};

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(principal),authProperties);

return RedirectToPage("dashboard");

答案 1 :(得分:2)

在我的情况下是 options.Cookie.SecurePolicy ,我们的托管应用程序尚未使用HTTPS。

.AddCookie(config =>
        {
            config.Cookie.HttpOnly = true;
            //options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            config.Cookie.SameSite = SameSiteMode.Lax;
            config.Cookie.Name = CookieAuthenticationDefaults.AuthenticationScheme;
            config.LoginPath = "/Login";
        });

答案 2 :(得分:1)

尝试清除浏览器缓存和Cookie,然后重试。

答案 3 :(得分:0)

通常,当您尝试使用Http运行时会发生这种情况,启用SSL应该可以解决您的问题,这在项目的Debug部分中。 enter image description here

答案 4 :(得分:0)

我认为您的 startup configure 服务缺少以下代码行:

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