skip to Main Content

I logged in with JWT, but how can I log out? Without Token invalidation. I want to do it with button

 [AllowAnonymous]
        [Route("login")]
        [HttpPost]
        public IActionResult Login(LoginModel loginModel)
        {
            if (string.IsNullOrEmpty(loginModel.UserName) || string.IsNullOrEmpty(loginModel.Password))
            {
                return (RedirectToAction("Error"));
            }

            IActionResult response = Unauthorized();
            var validUser = GetUser(loginModel);

            if (validUser != null)
            {
                generatedToken = _tokenService.BuildToken(_config["Jwt:Key"].ToString(), _config["Jwt:Issuer"].ToString(),
                validUser);

                if (generatedToken != null)
                {
                    HttpContext.Session.SetString("Token", generatedToken);
                    return RedirectToAction("MainWindow");
                }
                else
                {
                    return (RedirectToAction("Error"));
                }
            }
            else
            {
                return (RedirectToAction("Error"));
            }
        }

Here is the login function
How can I log out?

2

Answers


  1. You can remove your cookies as a JWT token saved in cookies so that you must read them and then remove them. Here is the sample code

    [AllowAnonymous]
            [Route("logout")]
    [HttpPost]
        public IActionResult LogOut()
        {
            //Delete the Cookie from Browser.
            Response.Cookies.Delete("Name");
     
            return RedirectToAction("ActionMethodName");
        }
    
    Login or Signup to reply.
  2. If you store the refresh tokens in the database, simply you can delete the refresh token for this user when call "Logout" endpoint and the client app should clear the stored JWT token from wherever it’s stored, and then when the client call "Refresh token" endpoint it’ll return unauthorized.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search