【问题标题】:User.Identity.IsAuthenticated always false in .net core custom authenticationUser.Identity.IsAuthenticated 在 .net 核心自定义身份验证中始终为 false
【发布时间】:2017-12-28 22:14:01
【问题描述】:

谁能检查下面的代码,让我知道为什么我总是假的(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();
    }

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    ClaimsIdentity.IsAuthenticatedClaimsIdentity.AuthenticationType 为空或为空时返回false。为避免这种情况,请停止使用无参数 ClaimsIdentity 构造函数并使用接受 authenticationType 参数的重载:

    var userIdentity = new ClaimsIdentity("Custom");
    

    【讨论】:

    • 非常感谢:) 无参构造函数有什么用??
    • 这样工作真是不可思议哈哈,但确实有效!
    【解决方案2】:

    就我而言,问题出在启动文件中。 app.UseAuthentication() 行在 app.UseMvc() 行之后。我颠倒了订单,它开始工作了。

    【讨论】:

      【解决方案3】:

      我知道这个问题是很久以前提出的,但它可能对其他人有用。

      在 Startup.cs 类的 Configure 方法中在 app.UseAuthorization(); 之前使用 app.UseAuthentication(); 为我修复了它。

      【讨论】:

        【解决方案4】:

        你可以试试这个。我认为这会有所帮助

        var userIdentity = new ClaimsIdentity( claims, AuthenticationTypes.Basic);

        【讨论】:

          猜你喜欢
          • 2019-11-03
          • 2019-02-23
          • 1970-01-01
          • 2017-11-01
          • 2018-09-26
          • 1970-01-01
          • 1970-01-01
          • 2018-09-22
          • 1970-01-01
          相关资源
          最近更新 更多