Search code examples
c#asp.net-coreasp.net-core-mvc

User.Identity.IsAuthenticated always false in .net core custom authentication


Can anyone please check below code and let me know why I'm getting always false (User.Identity.IsAuthenticated)??. I'm getting cookie on my browser properly and able to get value from Claim but "User.Identity.IsAuthenticated" always 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();
    }

enter image description here


Solution

  • ClaimsIdentity.IsAuthenticated returns false when ClaimsIdentity.AuthenticationType is null or empty. To avoid that, stop using the parameterless ClaimsIdentity constructor and use the overload accepting an authenticationType parameter:

    var userIdentity = new ClaimsIdentity("Custom");