I would like to know what is the way to force logout somebody when I ban them? I am using this way of login process
private async Task SignInWithRoleAsync(string email, string userRoleName)
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Email, email));
identity.AddClaim(new Claim(ClaimTypes.Role, userRoleName));
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
}
I couldn't find an answer for that question so far.
CodePudding user response:
First of all, it depends how you decide to ban a user and how to check it. In application business logic you must decide when is the proper moment to check user status. After that, you can do something like this
- .Net Framework:
Context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
CodePudding user response:
I would use middleware if it were me. it's not possible access to auth cookie when banning. Bcs auth cookies is store in client session database.
public async Task Invoke(HttpContext httpContext)
{
var bannedUser = new string[] { "[email protected]" };
if (bannedUser.Contains(httpContext.User.Claims.FirstOrDefault(ClaimTypes.Email)))
{
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
await _next.Invoke(httpContext);
}
You can find detailed information about middleware here. https://www.tutorialsteacher.com/core/aspnet-core-middleware