User.Identity.IsAuthenticated在.net核心自定义身份验证中始终为false

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.IsAuthenticatedfalseClaimsIdentity.AuthenticationType为null或为空时返回.为避免这种情况,请停止使用无参数ClaimsIdentity构造函数并使用接受authenticationType参数的重载:

var userIdentity = new ClaimsIdentity("Custom");
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢:)无参数构造函数的用途是什么? (4认同)

erh*_*355 10

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


小智 9

我知道这个问题很久以前就有人问过了,但它可能对其他人有用。

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