Pan*_*wat 9 asp.net-core-mvc asp.net-core
任何人都可以检查下面的代码,让我知道为什么我总是假的(User.Identity.IsAuthenticated)?? 我正在我的浏览器上正确地获取cookie并且能够从Claim获得价值,但"User.Identity.IsAuthenticated"总是错误的.
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();
}
Run Code Online (Sandbox Code Playgroud)
Kév*_*let 21
ClaimsIdentity.IsAuthenticated
false
当ClaimsIdentity.AuthenticationType
为null或为空时返回.为避免这种情况,请停止使用无参数ClaimsIdentity
构造函数并使用接受authenticationType
参数的重载:
var userIdentity = new ClaimsIdentity("Custom");
Run Code Online (Sandbox Code Playgroud)
小智 9
我知道这个问题很久以前就有人问过了,但它可能对其他人有用。
在 Startup.cs 类中的 Configure 方法中使用app.UseAuthentication();
之前app.UseAuthorization();
为我修复了它。
归档时间: |
|
查看次数: |
7089 次 |
最近记录: |