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

Key*_*ume 9 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();
}
Run Code Online (Sandbox Code Playgroud)

和startup.cs配置方法

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

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

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

小智 6

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


Kev*_*Bui 5

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

  • @joab 这也对我有用。这样做的逻辑原因是什么?我们如何以编程方式从服务器强制它清除浏览器的缓存 (2认同)