Home > OS >  Cannot reach the cookies with Response.Cookies method in .net Core
Cannot reach the cookies with Response.Cookies method in .net Core

Time:12-31

ı have a project with .net core and reactjs. I can create the cookie successfully but in my logout method, ı can not get the cookies with response.cookies method to remove the cookie. All ı wanted is just remove the cookie. Here is my backend codes:

        [HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            var userDb = await _creditTrackerContext.Users.FirstOrDefaultAsync(x => x.UserName == user.UserName && x.Password == user.Password);

            if (userDb is not null && user.UserName == userDb.UserName && user.Password == userDb.Password)
            {
                var jwt = _jwtService.Generate(userDb.Id);

                Response.Cookies.Append("jwt", jwt, new CookieOptions
                {
                    HttpOnly = true,
                    IsEssential = true,
                    SameSite = SameSiteMode.None,
                    Secure = true,
                });

                return Ok(new
                {
                    message = "success"
                });
            }
            return BadRequest(new { message = "Invalid Credentials" });
        }

        [HttpGet]
        public async Task<IActionResult> getAuthenticatedUser()
        {
            try
            {
                var jwt = Request.Cookies["jwt"];

                var token = _jwtService.Verify(jwt);

                int ID = Convert.ToInt32(token.Issuer);

                var user = await _creditTrackerContext.Users.FindAsync(ID);
                return Ok(user);
            }
            catch (Exception _ex)
            {
                return Unauthorized(_ex);
            }
        }

        [Route("Logout")]
        [HttpPost()]
        public IActionResult Logout()
        {
            try
            {
                Response.Cookies.Delete("jwt");

                return Ok(new
                {
                    message = "success logout"
                });
            }
            catch (Exception _ex)
            {

                throw new Exception("",_ex);
            }
            
        } 

And here is my logout call from frontend:

    console.log('test')
    const URL = 'https://localhost:44337/api/user/logout'
     fetch(URL,{
      method:'POST',
      headers:{'Content-Type':'application/json'},
      credentials:'include'
    }).then( setRedirect(true))
  } 

And ı also see something about enable cookie decoding attribute in non-public members but ı didnt get the interest. Thx in advance

CodePudding user response:

You can't delete a cookie in the browser by:

Response.Cookies.Delete("jwt");

Instead what you need is to create a new cookie with the same name, but with an expire date in the past.

Something like this:

if (Request.Cookies["jwt"] != null)
{
    var c = new HttpCookie("jwt")
    {
        Expires = DateTime.Now.AddDays(-1)
    };
    Response.Cookies.Add(c);
}

However, storing tokens unencrypted is a bad idea. I would rater add it to the ASP.NET Core session cookies, because then i know the data is properly encrypted before its added as a cookie.

  • Related