问题描述
谁能检查下面的代码,让我知道为什么我总是假的(User.Identity.IsAuthenticated)??.我在浏览器上正确获取了 cookie,并且能够从 Claim 中获取价值,但User.Identity.IsAuthenticated"始终为 false.
Can anyone please check below code and let me know why I'm getting always false (User.Identity.IsAuthenticated)??. I'm getting cookie on my browser properly and able to get value from Claim but "User.Identity.IsAuthenticated" always false.
public async Task<IActionResult> Login(string phoneNumber, int otp, string returnUrl)
{
if (this.accountService.ValidateOTP(phoneNumber, otp))
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.MobilePhone, phoneNumber),
new Claim(ClaimTypes.Name, phoneNumber)
};
var userIdentity = new ClaimsIdentity();
userIdentity.AddClaims(claim);
ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
});
if (string.IsNullOrWhiteSpace(returnUrl))
{
return RedirectToAction("Create", "Ad");
}
else
{
return Redirect(returnUrl);
}
}
return BadRequest();
}
推荐答案
ClaimsIdentity.IsAuthenticated
当 ClaimsIdentity.AuthenticationType
为 null 时返回 false
或空的.为避免这种情况,请停止使用无参数 ClaimsIdentity
构造函数并使用接受 authenticationType
参数的重载:
ClaimsIdentity.IsAuthenticated
returns false
when ClaimsIdentity.AuthenticationType
is null or empty. To avoid that, stop using the parameterless ClaimsIdentity
constructor and use the overload accepting an authenticationType
parameter:
var userIdentity = new ClaimsIdentity("Custom");
这篇关于User.Identity.IsAuthenticated 在 .net 核心自定义身份验证中始终为 false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!