在.NET Core自定义身份验证中,User.Identity.IsAuthenticated始终为false

25

请问有人可以检查以下代码并告诉我为什么我一直得到false(User.Identity.IsAuthenticated)吗?我在浏览器上正确获取了cookie,并且能够从声明中获取值,但“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();
    }

输入图像描述

5个回答

45

ClaimsIdentity.IsAuthenticatedClaimsIdentity.AuthenticationType为null或空时返回false。为避免该问题,请停止使用不带参数的ClaimsIdentity构造函数,并改用接受authenticationType参数的重载:

var userIdentity = new ClaimsIdentity("Custom");

13
没有参数的构造函数有什么用? - Pankaj Rawat
1
真是不可思议,它能这样工作哈哈,但确实有效! - Kat Lim Ruiz

16

我知道这个问题很久以前就被问了,但是它可能对另一个人有用。

在 Startup.cs 类的 Configure 方法中,在 app.UseAuthorization(); 之前使用 app.UseAuthentication(); 可以解决此问题。


12
在我的情况下,问题出现在启动文件中。app.UseAuthentication()方法在app.UseMvc()方法之后执行,我将其顺序颠倒后,程序开始正常工作。

2
您可以尝试这个。我认为这可能会有所帮助。 var userIdentity = new ClaimsIdentity(claims, AuthenticationTypes.Basic); 意思是创建一个基本身份验证类型的声明标识。

0

我的是 .net core 6 应用程序。

我还观察到

HttpContext.User.Identity!.IsAuthenticated

始终为false。

对我来说,选择正确的AddAuthentication扩展方法的重载解决了这个问题。

选择指定默认模式的AddAuthentication重载,可以适当地设置IsAuthenticated标志。

var authBuilder = builder.Services.AddAuthentication("CookieAuth");

基本上我正在配置一个cookie身份验证处理程序。
var authBuilder = builder.Services.AddAuthentication("CookieAuth");
authBuilder.AddCookie("CookieAuth", options =>
{
    options.Cookie.Name = "CookieAuth";
});

如果您想查看完整的示例,请点击此处

我们必须指定要使用哪个方案。方案名称将所有授权处理程序、身份和声明原则逻辑分组在一起。我们必须告诉中间件,我们正在尝试使用哪个方案,以便中间件能够找到您正在尝试使用的授权服务来进行身份验证。

因此,基本上通过在以下重载中提供方案名称,

builder.Services.AddAuthentication("CookieAuth");

中间件 UseAuthentication 将能够知道使用哪个处理程序。因此,该处理程序将能够反序列化传入的 cookie 并将 IsAuthenticated 标志设置为 true。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接