25

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

Lukas
  • 1,699
  • 1
  • 16
  • 49
Pankaj Rawat
  • 4,037
  • 6
  • 41
  • 73

5 Answers5

43

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");
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
15

I know this question was asked a long time ago, but it might be useful to another person.

Using app.UseAuthentication(); right before app.UseAuthorization(); inside the Configure method in the Startup.cs class fixed it for me.

Jemil Oyebisi
  • 633
  • 8
  • 10
12

In my case the problem was in the startup file. app.UseAuthentication() line was coming after app.UseMvc() line.I reversed the orders and it started to work.

erhan355
  • 806
  • 11
  • 23
2

You can try this one. I think this can help

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

Mohammad Taherian
  • 1,622
  • 1
  • 15
  • 34
0

Mine is .net core 6 app.

I also observed that

HttpContext.User.Identity!.IsAuthenticated

is always false.

For me selecting the correct overload of the AddAuthentication extension method resolved the issue.

Choosing the AddAuthentication overload in which I have to specify the default schema, sets IsAuthenticated flag appropriately.

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

Basically I am configuring a cookie Auth handler.

var authBuilder = builder.Services.AddAuthentication("CookieAuth");
authBuilder.AddCookie("CookieAuth", options =>
{
    options.Cookie.Name = "CookieAuth";
});

If you want to take a look at the full example, here it is.

We have to specify which scheem we have to use. The schmeme name provides a logical grouping of the auth handler, identity and cliams principles all together. We have to tell the middleware, which scheme we are trying to use so that the middleware will be able to locate which auth service you are trying to use to do the authentication.

So basically by providing the scheme name in the following overload,

builder.Services.AddAuthentication("CookieAuth");

the middleware UseAuthentication will be able to know which handler to use. So then this handler will be able to deserialize the in coming cookie and set the IsAuthencated flag to true

VivekDev
  • 20,868
  • 27
  • 132
  • 202