自定义asp.net身份角色声明 [英] Customize asp.net identity role claim

查看:88
本文介绍了自定义asp.net身份角色声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

一切正常,但是我想指示asp.net使用自定义声明类型作为角色,而不是标准System.Security.Claims.ClaimTypes.Role(

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).

有可能吗?

我想将标准的Authorize属性与角色构造函数一起使用,例如:Authorize(Roles ="staff")并让框架检查声明,但是我的自定义角色声明类型("myapproleclaim")代替了标准的.

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.

推荐答案

您可以做类似的事情,

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

这篇关于自定义asp.net身份角色声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆