Home > database >  ASP .NET Core Log Out from JWT
ASP .NET Core Log Out from JWT

Time:06-28

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?

CodePudding user response:

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");
    }

CodePudding user response:

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.

  • Related