HttpContext.SignOutAsync() Method not deleting my authentication cookie

Viewed 29

I have a razor pages project that creates a authentication scheme on a login page i hardcoded the name and password for testing purposes.

public async Task<IActionResult> OnPost()
    {
        if(ModelState.IsValid)
        {
            if(Credential.Username == "admin" && Credential.Password =="password")
            {
               
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, Credential.Username),
                    new Claim(ClaimTypes.Email, "admin@gmail.com"),
                    new Claim("Tipo", "admin")
                };
                var identity = new ClaimsIdentity(claims, "CookieAuth");
                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
                HttpContext.Session.SetString("Username", Credential.Username);
                await HttpContext.SignInAsync("CookieAuth", claimsPrincipal);
                return RedirectToPage("/Index");
                

            }
        }
        return Page();
    }

I have configured a simple authentication/authorization with policies to restrict acess

builder.Services.AddAuthentication("CookieAuth").AddCookie("CookieAuth", options =>
{
options.Cookie.Name = "CookieAuth";
options.LoginPath = "/Login/LoginIndex";
options.AccessDeniedPath = "/Login/AcessDenied";

My login is working fine and the cookie is created sucessfully however when i try to logout the cookie refuses to be removed/cleared from the browser and im not too sure why, heres my logout method, it gets called by a button on a partial view on the nav bar

public async Task<ActionResult> OnPost()
    {
        await HttpContext.SignOutAsync("CookieAuth");//cookie nao apaga, inspecionar
        return RedirectToPage("/Index");
    }

i have tried other solutions from previous threads but noone seem to fix my issue, the post method gets called and the cookie persist in the browser making me have to delete it manually for other testing.

1 Answers

I have found the problem. The problem was in the @model reference of the logout page, I had cloned a page view before to save time doing HTML and never REALIZED THE LOGOUT PAGE MODEL WAS DIFFERENT FROM THE LOGOUTMODEL THAT CONTAINED THE METHOD. Anyways, after switching the model it works and the cookie is gone, so all good.

Related