asp.net - MVC 5 和声明默认身份验证的使用

标签 asp.net asp.net-mvc asp.net-mvc-5 owin claims

我对 MVC 5 中的声明有疑问。

所以基本上想象我在数据库中有一个注册用户,现在该用户要登录,如下所示:

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

因此,在这种情况下,我向该身份添加新的声明,然后登录该身份。

现在我的问题是:

  • 设置此声明有什么用? (因为如果我需要的话,我也可以从数据库中获取它,所以在这种情况下 claim 有什么意义)

  • 稍后我如何在代码中使用它?

最佳答案

针对身份设置声明可以使您的应用程序安全性更加高效,并减少每次访问数据库的次数。

上述方法可以称为声明转换,通常涉及读取身份验证成功后转换为声明的数据。

为了稍后阅读,您可以这样做:

//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/

关于asp.net - MVC 5 和声明默认身份验证的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21352583/

相关文章:

c# - 身份(在数据库创建时)错误指定的 key 太长

C# SignalR GetHttpContext/HttpContext 响应不存在

javascript - JQuery 模态对话框表单回发问题

c# - SqlDependency.OnChange 触发但 SqlDataReader 未返回数据

asp.net-mvc - PagedList 的帮助程序支持 ASP.NET MVC 中不显眼的 Ajax

c# - 有人可以向我解释 ASP.NET MVC 吗?

c# - 是否可以序列化或保存 viewbag 状态?

c# - ASP.NET MVC - 单元测试在业务程序集中创建操作方法 URL

asp.net - 'GridView 1' fired event PageIndexChanging which wasn' t 已处理

visual-studio-2013 - Visual Studio 2013 启动错误的 MVC 应用程序