I have an angular project and I provide token based login in this project. When the user exits using the exit button, I delete the current token from the database, but I cannot delete it when the browser is closed directly. How can I do this?
Handler Code:
public async Task<IResult> Handle(LogoutCommand request, CancellationToken cancellationToken)
{
var isThereAnyUser = await _userRepository.GetAsync(u => u.UserId == request.UserId);
isThereAnyUser.Token = "";
isThereAnyUser.RefreshToken = "";
_userRepository.Update(isThereAnyUser);
await _userRepository.SaveChangesAsync();
return new SuccessResult(Messages.logOutMessage);
}
Wep api Code:
public async Task<IActionResult> Logout([FromBody] LogoutCommand logoutCommand)
{
var result = await Mediator.Send(logoutCommand);
if (result.Success)
{
return Ok(result.Message);
}
else
return BadRequest(result.Message);
}
CodePudding user response:
It will be hard to get this working in all cases and accross a variety of browsers, so you'd need a backup solution anyway that takes care of token expiration.
As an alternative, you could give the tokens an expiration time that is stored in the database and update the expiration every time the token is used to access the API.
The process could be outlined as follows:
- user logs in: if there is no valid token, a token is created with Login Time 5 minutes. Otherwise, the login is refused.
- user accesses the API (with the token): Token is updaten with access time 5 minutes (if there are no API accesses, the Angular app could periodically call the API to extend the token)
- user logs out: Token is deleted; user can immediately log in on another device
- user does not log out but closes the browser: Token expires after 5 minutes; until then the user cannot use the API from another device. Therefore the expiration time should be short (5 minutes in this example)
As an alternative to storing the expiration time in the database, you could also store it in the token, but you'd need to exchange tokens upon API request (or with the periodic calls).