【问题标题】:How to force logout somebody from ASP.NET using Cookies如何使用 Cookie 强制从 ASP.NET 中注销某人
【发布时间】:2023-03-31 20:01:01
【问题描述】:

我想知道当我禁止某人时强制注销某人的方法是什么? 我正在使用这种方式的登录过程

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

到目前为止,我找不到该问题的答案。

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    如果是我,我会使用中间件。禁止时无法访问 auth cookie。 Bcs auth cookie 存储在客户端会话数据库中。

    public async Task Invoke(HttpContext httpContext)
            {
                var bannedUser = new string[] { "foo@foo.com" };
    
                if (bannedUser.Contains(httpContext.User.Claims.FirstOrDefault(ClaimTypes.Email)))
                {
                    await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                }
    
                await _next.Invoke(httpContext);
            }
    

    您可以在此处找到有关中间件的详细信息。 https://www.tutorialsteacher.com/core/aspnet-core-middleware

    【讨论】:

      【解决方案2】:

      首先,这取决于您决定如何禁止用户以及如何检查它。在应用程序业务逻辑中,您必须决定何时是检查用户状态的合适时机。之后,你可以做这样的事情

      • .Net 框架:

      Context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);

      【讨论】:

        猜你喜欢
        • 2016-04-28
        • 2020-12-03
        • 2013-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-25
        • 2021-02-18
        • 1970-01-01
        相关资源
        最近更新 更多