c# - .NET Core Cookie 身份验证 SignInAsync 不起作用

标签 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。

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

最佳答案

从 .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");

关于c# - .NET Core Cookie 身份验证 SignInAsync 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45100238/

相关文章:

c# - 列表框 IsSelected with SelectionMode=Extended

c# - 构造函数链接或使用命名/可选参数

asp.net-core - 如何在 Asp .Net Core SignalR Hub 中获取不记名 token ?

docker - 我一直在Docker Build上获取错误解析引用

c# - ASP.NET 4.5 在 ASP.NET Core 2.0 应用程序下将 502.5 作为 Azure Web App 中的虚拟应用程序抛出

wpf - .Net 核心 3 : manually adding framework dependencies

c# - 保持IEnumerable和ObservableCollection同步

c# - asp.net MVC 4,标记地点 - 最佳实践(例如酒吧、商店、餐厅)

c# - 如何根据字符串描述符的一部分对列表 <string> 进行排序

iis-express - 可以将iis Express配置(Windows身份验证)添加到asp.net mvc6项目吗?