首页 文章

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

提问于
浏览
0

我正在使用带有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”)并让框架检查声明,但是我的自定义角色声明类型(“myapproleclaim”)而不是标准声明类型 .

1 回答

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

相关问题