Customize asp.net identity role claim

﹥>﹥吖頭↗ 提交于 2019-12-12 06:05:52

问题


I'm using asp.net identity with ClaimsPrincipal and ClaimsIdentity. The identity is created by a custom usermanager and sent to the clients as a bearer token.

All works fine, but I would like to instruct asp.net to use a custom claim type for role, instead of the standard System.Security.Claims.ClaimTypes.Role (http://schemas.microsoft.com/ws/2008/06/identity/claims/role).

Is it possibile?

Edit: I would like to use the standard Authorize attribute with role constructor, ex: Authorize(Roles="staff") and let the framework to check the claims, but my custom role claim type ("myapproleclaim") instead of the standard one.


回答1:


You can do things like,

public class CustomPrinciple : ClaimsPrincipal
{
    public CustomPrinciple(ClaimsIdentity identity) : base(identity)
    {
    }

    public override bool IsInRole(string role)
    {
        return HasClaim("myRoleClaimType", role);
    }
}

[TestClass]
public class CustomRoleTest
{
    [TestMethod]
    public void testing_custom_role_type()
    {
        var identity = new ClaimsIdentity();
        identity.AddClaim(new Claim("myRoleClaimType", "role1"));
        var principle = new CustomPrinciple(identity);

        Assert.IsTrue(principle.IsInRole("role1"));
        Assert.IsFalse(principle.IsInRole("role2"));
    }
}


来源:https://stackoverflow.com/questions/34226127/customize-asp-net-identity-role-claim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!