强制另一个用户使用ASP.NET Identity 2.1.0刷新他们的声明

5

我正在使用 Asp.NET Identity 2.1.0,并将User可以访问的Accounts列表存储为Claims。当User登录时,会生成ClaimsIdentity

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

假设管理员撤销了“用户A”对特定账户的访问权限。我如何强制“用户A”重新生成其“ClaimsIdentity”?请记住这不是在“用户A”的上下文中进行的。而且我不想等到cookie过期(自动生成新的“ClaimsIdentity”)。
有可能吗?难道没有一种方法告诉服务器将“用户A”的cookie视为无效并强制重新生成它吗?
我想要这种行为的原因是创建一个自定义的“AuthorizeAttribute”,可以放在我的控制器上,检查“用户”是否具有访问权限,以避免额外的数据库往返。

1
你需要将他们注销,对吧?也许这个链接可以帮到你:https://dev59.com/7GPVa4cB1Zd3GeqP3z-1 - Brendan Green
1
@BrendanGreen 我并不想把他们注销,只是强制让他们重新生成声明。我可以使用UpdateSecurityStamp来强制让他们再次登录,但这只有在令牌过期时才会发生。 - Joel
您可以使用更新的声明将其注销并重新登录。 - tickwave
1个回答

5
您不能将其声明存储在cookie中,但可以在管道早期的每个请求中应用它们。您需要修改Startup.Auth.cs来实现这一点。我正在这里进行操作。
以下是相关内容:
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 和其他依赖项。
好处是索赔立即应用于每个用户的请求,无需重新登录即可立即更改权限。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接