Home > Back-end >  How to create Logout Endpoint when using JWT
How to create Logout Endpoint when using JWT

Time:01-20

I made the login method like this:

public async Task<IActionResult> Login([FromBody] LoginUserDTO userDTO)
{
    var res = await _authManager.ValidateUser(userDTO);
    if (!res) return Unauthorized();
    await _authManager.SetLoginInfo(userDTO, Request);
    return Accepted(new { Token = await _authManager.CreateToken() });
}

public async Task<string> CreateToken()
{
    var signingCredentials = GetSigningCredentials();
    var claims = await GetClaims();
    var token = GenerateTokenOptions(signingCredentials, claims);
    return new JwtSecurityTokenHandler().WriteToken(token);
}

How can I create an endpoint for Logout?

CodePudding user response:

In ASP, there is no such thing as logging out from a JWT on the server.

A JWT is a token that has an expiry date and is issued by the server (or a trusted third-party). It is then cached by the client and sent to the server by the client in the header of subsequent requests and is then validated by the server to ensure that it is both valid and not expired.

If the expiry is reached, then the server will return a 401 - Unauthorised response.

If you want to log a client out then you just remove the client side cached token so that it cannot be sent in the header of any future requests.

  • Related