Home > Enterprise >  User.Identity.IsAuthenticated does not work
User.Identity.IsAuthenticated does not work

Time:05-04

The Problem: View does not changes when user is authenticated

I want to make a special view for logged in users. I now that is possible to reach with User.Identity.IsAuthenticated. I tried to do it, but it does not work.

I implemented a registration and authentication, I made a models, migrations and created database. My authentication is working good, because cookies creates in my browser. So check the next screenshots and code:

[ValidateAntiForgeryToken]
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            User user = new User
            {
                Email = model.Email,
                UserName = model.Username
            };

            if (ModelState.IsValid)
            {
                var result = await userManager.CreateAsync(user, model.Password);
                if(!result.Succeeded)
                {
                    foreach(var error in result.Errors)
                    {
                        ModelState.TryAddModelError(error.Code, error.Description);
                    }

                    return View(model);
                }
            }
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AllowAnonymous]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, true,false);

                if (result.Succeeded)
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
            }


            return View("~Views/Home/Index", model);
        }

Cookie was created after authentication:

Cookie

_Layout.cshtml:

 @if(User.Identity.IsAuthenticated)
    {
         <div >
        <ul>
            <li><a href="#">@User.Identity.Name</a></li>
            <li><a asp-controller="Account" asp-action="Logout">Logout</a></li>
        </ul>
    </div>
    }
    else
    {
         <div >
        <ul>
            <li><a asp-controller="Account" asp-action="Login">Login</a></li>
            <li><a asp-controller="Account" asp-action="Register">Register</a></li>
        </ul>
    </div>
    }

CodePudding user response:

I found an answer. User.Identity.IsAuthenticated was always false. So from 1 one hour googling why it did not work I realized that I forgot to add this in Program.cs

app.UseAuthentication();

  • Related