【问题标题】:Force another user to refresh their Claims with ASP.NET Identity 2.1.0强制另一个用户使用 ASP.NET Identity 2.1.0 刷新他们的声明
【发布时间】:2015-09-21 06:30:07
【问题描述】:

我正在使用 Asp.NET Identity 2.1.0 并存储 Accounts 的列表,User 可以访问,作为声明。 ClaimsIdentityUser 登录时生成:

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

    // Add Claims concerning Account
    userIdentity.AddClaim(new Claim("AccountList", SerializedListOfAccounts));

    return userIdentity;
}

假设管理员撤销了User A 对特定帐户的访问权限。如何强制User A 重新生成其ClaimsIdentity?请记住,它不在User A 的上下文中。而且我不想等到 cookie 过期(并且会自动生成一个新的ClaimsIdentity

有可能吗?难道没有办法告诉服务器将User A的cookie视为无效并强制重新生成吗?

我想要这种行为的原因是创建一个自定义 AuthorizeAttribute,我可以将它放在我的控制器上,检查 Claims 以查看 User 是否具有访问权限,以避免额外往返数据库。

【问题讨论】:

  • 您必须将它们注销,对吗?也许这会有所帮助:stackoverflow.com/questions/10369225/…
  • @BrendanGreen 我真的不想注销他们,只是强迫他们重新生成他们的声明。我可以使用 UpdateSecurityStamp 强制他们再次登录,但无论如何,这将是令牌过期的时间。
  • 您可以将其注销,然后使用更新的声明重新登录。

标签: asp.net asp.net-mvc-5 asp.net-identity asp.net-identity-2


【解决方案1】:

您不能将他们的声明存储在 cookie 上,而是在管道的早期将它们应用于对身份的每个请求。你必须破解Startup.Auth.cs 才能做到这一点。我正在这样做here

以下是您可以使用的要点:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            Provider = GetMyCookieAuthenticationProvider(),
            // other configurations
        });

        // other usual code
    }



    private static CookieAuthenticationProvider GetMyCookieAuthenticationProvider()
    {
        var cookieAuthenticationProvider = new CookieAuthenticationProvider();
        cookieAuthenticationProvider.OnValidateIdentity = async context =>
        {
            // execute default cookie validation function
            var cookieValidatorFunc = SecurityStampValidator.OnValidateIdentity<UserManager, ApplicationUser>(
                TimeSpan.FromMinutes(10),
                (manager, user) =>
                {
                    var identity = manager.GenerateUserIdentityAsync(user);
                    return identity;
                });
            await cookieValidatorFunc.Invoke(context);

            // sanity checks
            if (context.Identity == null || !context.Identity.IsAuthenticated)
            {
                return;
            }


            // get your claim from your DB or other source
            context.Identity.AddClaims(newClaim);
        };
        return cookieAuthenticationProvider;
    }
}

您需要对每个请求应用声明的缺点,这可能不是很高效。但是在正确的地方进行适量的缓存会有所帮助。此外,这段代码也不是最容易工作的地方,因为它处于管道的早期阶段,您需要自己管理 DbContext 和其他依赖项。

好处是声明会立即应用于每个用户的请求,您可以立即更改权限,而无需重新登录。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多