Search code examples
asp.net-coreasp.net-identityasp.net-core-3.1

Including Logout functionality in _Layout ASP.NET 3.0 Razor Pages project


I have built a simple razor page application where login which uses AddAuthentication() and checks to ensure the username and password match the values in the db. Each page is then authorized based on that so only logged in users can move forward to other pages. My login view model includes the following type of authentication:

               var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, UserName)
                };
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                if (RememberMe)
                {
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(claimsIdentity),
                        new AuthenticationProperties
                        {
                            IsPersistent = RememberMe,
                            ExpiresUtc = DateTimeOffset.UtcNow.AddHours(2)
                        });
                }
                else
                {
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(claimsIdentity));
                }
                return RedirectToPage("/index");

Now I need to create logout functionality. I feel as though logout in the navigation bar is pretty common. My navigation bar is built using shared _layout. So first I need to pass some sort of model to this _layout class so I can catch an onpost event to remove the session cookie or persistent cookie if it exists and redirect the user to the login page.

How can this be done without controllers to maintain a MVVM approach?

Second, in regards to logging out. I want to use

    public async Task<IActionResult> Logout()
    {

        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToPage("/index");

    }

In the model I pass to _layout. However, using HttpContext will only work with PageModel so just creating model class doesnt seem to work but instead i Need to createa a partial PageModel class to pass to _layout. THoughts?

Thanks


Solution

  • I usually use a separate Razor Page with code-behind that performs the logout. You should give some feed-back to the user after logout instead of just redirecting user to index page. Hence, you can have a link to your logout-page from your layout since logout can be done on GET.