我对MVC 5中的声明有疑问.
所以基本上想象我在DB中有一个注册用户,现在用户将要登录,如下所示:
private async Task SignInAsync(ApplicationUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // Add more custom claims here if you want. Eg HomeTown can be a claim for the User var homeclaim = new Claim(ClaimTypes.Country, user.HomeTown); identity.AddClaim(homeclaim); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); }
所以在这种情况下,我添加一个新的声明身份,然后我签署此身份.
现在我的问题是:
设置此声明有什么用?(因为如果我需要的话,我也可以从数据库中得到这个,在这个索赔案例中有什么意义)
我如何在代码中使用它?
hutchonoid.. 9
根据身份设置声明可以提高应用程序的安全性,并且每次都可以节省数据库.
上述方法可以称为声明转换,其通常涉及读取在身份验证成功后转换为声明的数据.
为了以后阅读,您可以这样做:
//Get the current claims principal var identity = (ClaimsPrincipal)Thread.CurrentPrincipal; //Get the country from the claims var country = identity.Claims.Where(c => c.Type == ClaimTypes.Country).Select(c => c.Value);
更新
只是为了在下面的评论中讨论的答案提供一些进一步的信息.
使用基于声明的方法,您还可以使用声明授权管理器,该声明管理器可以为资源和操作提供集中/细粒度的访问控制.
如果您之前没有使用过声明,那么最好考虑针对资源的操作而不是基于角色的权限.这样,您可以向下钻取并单独控制对每个资源/操作的访问,而不是为每个资源/操作分配多个角色.
我个人喜欢使用混合物,但也将角色存储为声明.这样我就可以在mvc中使用带有角色的标准授权标签,这些角色读取声明并使用thinktecture的属性/ ClaimsAuthorization来使声明授权管理器获取更复杂的规则.
有关在MVC 4中实现基于声明的身份验证的良好链接,请访问:
http://dotnetcodr.com/2013/02/25/claims-based-authentication-in-mvc4-with-net4-5-c-part-1-claims-transformation/