任何人都可以检查下面的代码并让我知道为什么我总是错误(User.Identity.IsAuthenticated)??我在浏览器上正确获取 cookie 并且 能够从 Claim 获取值,但“User.Identity.IsAuthenticated”始终为 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
为 null 或为空时,
false
返回 ClaimsIdentity.AuthenticationType
。为了避免这种情况,请停止使用无参数 ClaimsIdentity
构造函数并使用接受 authenticationType
参数的重载:
var userIdentity = new ClaimsIdentity("Custom");
我知道这个问题很久以前就被问过,但它可能对其他人有用。
在 Startup.cs 类的配置方法中的
app.UseAuthentication();
之前使用 app.UseAuthorization();
为我解决了这个问题。
就我而言,问题出在启动文件中。 app.UseAuthentication() 行在 app.UseMvc() 行之后。我颠倒了顺序,它开始工作。
你可以试试这个。我认为这会有所帮助
var userIdentity = new ClaimsIdentity( claims, AuthenticationTypes.Basic);
我的是.net core 6 应用程序。
我也观察到
HttpContext.User.Identity!.IsAuthenticated
始终是假的。
对我来说,选择正确的 AddAuthentication 扩展方法重载解决了问题。
选择 AddAuthentication 重载,我必须在其中指定默认架构,并适当设置 IsAuthenticated 标志。
var authBuilder = builder.Services.AddAuthentication("CookieAuth");
基本上我正在配置一个 cookie Auth 处理程序。
var authBuilder = builder.Services.AddAuthentication("CookieAuth");
authBuilder.AddCookie("CookieAuth", options =>
{
options.Cookie.Name = "CookieAuth";
});
如果您想查看完整的示例,这里就是。
我们必须指定我们必须使用哪种方案。 schmeme 名称提供了身份验证处理程序、身份和声明原则的逻辑分组。我们必须告诉中间件,我们正在尝试使用哪种方案,以便中间件能够找到您尝试使用哪个身份验证服务来进行身份验证。
所以基本上通过在以下重载中提供方案名称,
builder.Services.AddAuthentication("CookieAuth");
中间件 UseAuthentication 将能够知道要使用哪个处理程序。那么这个处理程序将能够反序列化传入的 cookie 并将 IsAuthencated 标志设置为 true
我遇到了一个类似但略有不同的问题,对于将来阅读本文的人来说,这是解决方案:
如果您使用自定义中间件来检查 HttpContext 并且它指出用户未经过身份验证,则意味着该中间件以错误的顺序运行。 您必须在program.cs中的UseAuthentication和UseAuthorization之后注册此中间件:
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<AdGroupVerificationMiddleware>();