自定义asp.net身份角色声明

时间:2015-12-11 14:45:17

标签: c# asp.net asp.net-identity

我在ClaimsPrincipal和ClaimsIdentity中使用asp.net身份。身份由自定义用户管理器创建,并作为承载令牌发送给客户端。

一切正常,但我想指示asp.net使用自定义声明类型作为角色,而不是标准的System.Security.Claims.ClaimTypes.Role(http://schemas.microsoft.com/ws/2008/06/identity/claims/role)。

可能吗?

编辑:我想使用带有角色构造函数的标准Authorize属性,例如:Authorize(Roles =" staff")并让框架检查声明,但我的自定义角色声明类型(& #34; myapprolalaim")而不是标准的。

1 个答案:

答案 0 :(得分:1)

你可以做点什么,

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"));
    }
}
相关问题