如何在JWT中使用权限级别?

时间:2018-08-06 13:41:07

标签: c# jwt asp.net-core-webapi

我有一个.net core 2.0 WebAPI,我使用JWT作为HttpOnly cookie对其进行保护。 我现在正在尝试对每个端点实施基于位的权限级别,并且试图了解它是否可以在JWT cookie中完成。 例如,我有一个基本的访问级别枚举:

[Flags]
public enum AccessLevel
{
    Read = 1,
    Write = 2,
    Modify = 4,
    Delete = 8,
    FullControl = 15
}

我可以这样向我的令牌添加声明吗?

var claims = new List<Claim>
{
    new Claim("StudentsAccessLevel", "3"),
    new Claim("CoursesAccessLevel", "7")
};

然后以某种方式在我的StudentsController中使用它:

public class StudentsController : Controller
{
    [HttpPost]
    //obviously this is not the syntax, but is there a syntax that can be used like that?
    [Authorize("StudentsAccessLevel" & 1 > 0)]
    public  IActionResult Create() { }

    [HttpGet]
    [Authorize("StudentsAccessLevel" & 2 > 0)]
    public IActionResult Read() { }

    [HttpPut]
    [Authorize("StudentsAccessLevel" & 4 > 0)]
    public IActionResult Update() { }

    [HttpDelete()]
    [Authorize("StudentsAccessLevel" & 8 > 0)]
    public IActionResult DeleteAsync() { }
}

1 个答案:

答案 0 :(得分:0)

为了影响根据它们所属的角色实际应用于给定用户身份验证的范围,可以在Auth0仪表板中定义一个规则。这是一个非常简单的示例:

function (user, context, callback) {

  user.app_metadata = user.app_metadata || {};

   if (user.app_metadata.role === "Administrator") {
     context.accessToken.scope = 'openid read:posts create:posts edit:posts';
   } else if (user.app_metadata.role === "User") {
  ...  // define likewise as needed..
   }

   callback(null, user, context);
}

是静态地应用到用户配置文件还是动态查找等角色,尚不清楚,并且取决于您的要求。但是,如果进行了此设置,您应该会收到一个JWT访问令牌,该令牌的有效负载包含如下内容(对于用户身份验证具有管理员角色的情况。

enter image description here

然后,您可以保护.NET Core API的安全性,以相应地验证访问令牌。如果您不使用API​​,那么从理论上讲,您可以“代替”使用ID令牌...(因为应用程序本身就是使用者)。但是,我基于您希望对某些API授权请求的理解而得出以上结论……?