我有一个使用 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/