Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 372
Pankaj Rawat Avatar asked Jul 23 '17 05:07

Pankaj Rawat


People also ask

Why is user identity IsAuthenticated false?

identity. isauthenticated is False when a user is already logged in.

How do I make request IsAuthenticated true?

Using the Codebool isAuthenticated = Request. IsAuthenticated; the result is always true .

What is IsAuthenticated identity?

Obviously, User. Identity. IsAuthenticated checks to see if the User is authenticated while Request. IsAuthenticated checks to see if the Request is Authenticated.


2 Answers

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");
like image 135
Kévin Chalet Avatar answered Sep 20 '22 12:09

Kévin Chalet


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.

like image 25
erhan355 Avatar answered Sep 17 '22 12:09

erhan355