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();
}
identity. isauthenticated is False when a user is already logged in.
Using the Codebool isAuthenticated = Request. IsAuthenticated; the result is always true .
Obviously, User. Identity. IsAuthenticated checks to see if the User is authenticated while Request. IsAuthenticated checks to see if the Request is Authenticated.
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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With