gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:02:05 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com