skip to Main Content

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.

2

Answers


  1. 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);

    Login or Signup to reply.
  2. 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

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