我有一个使用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)
| 归档时间: |
|
| 查看次数: |
4171 次 |
| 最近记录: |