5

我正在使用Asp.NET Identity 2.1.0,并且我存储User有权访问的Accounts列表。强制另一个用户使用ASP.NET身份刷新其声明2.1.0

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的特定帐户存取:ClaimsIdentityUser迹象产生。我如何强制User A重新生成ClaimsIdentity?请记住,它不在User A的背景下。我不希望等到cookie过期(并且自动生成新的ClaimsIdentity

是否有可能?是否有办法告诉服务器将User A的Cookie视为无效并强制它再生吗?

的原因,我想这种行为是创建一个自定义AuthorizeAttribute,我可以把我的控制器,检查Claims看是否有User访问或没有,以避免额外的往返到数据库

+1

你必须登出它们,对吗?也许这将有所帮助:http://stackoverflow.com/questions/10369225/forcefully-log-out-a-specific-user-among-all-online-users –

+1

@BrendanGreen我真的不想登出去,只是迫使他们重新提出索赔。我可以使用UpdateSecurityStamp强制他们再次登录,但这将是何时令牌过期。 – Joel

+0

您可以将它们注销并使用更新的声明重新登录。 – warheat1990

回答

5

您不能将它们的声明存储在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和其他依赖关系。

好处是,索赔是立即应用到每个用户的请求,你立即改变权限,而无需重新登录。