【问题标题】:How to create my own Authorize attribute for MVC API如何为 MVC API 创建我自己的 Authorize 属性
【发布时间】:2017-10-30 18:22:21
【问题描述】:

我想创建一个 Web API MVC。 此 API 将授权 TOKEN JWT,我想创建自己的 Authorize 属性,如 CanRead、CanModify、CanWrite。 三个属性只是继承Attribute类(没有AuthorizeAttribute),可以吗?

我的应用程序具有复杂的角色和权限,因此我想自定义所有有关授权和身份验证的内容。 我要管理权限动态

那我该怎么做呢?

我会从属性(CanRead 或 CanModify)访问数据库以检查权限

【问题讨论】:

    标签: asp.net-mvc api authorize


    【解决方案1】:

    改为创建自定义 AuthorizeAttribute。下面是一个例子。

    public class KeyAuthorizeAttribute : AuthorizeAttribute  
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string key = httpContext.Request["X-Key"];
            return ApiValidatorService.IsValid(key);
        }
    }
    
    public static class ApiValidatorService
    {
        public static bool IsValid(string key)
        {
            int keyvalue;
    
            if (int.TryParse(key, out keyvalue))
            {
                return keyvalue % 2137 == 7;
            }
            return false;
        }
    }
    

    拍摄from Jon Galloway's blog。我不知道你具体是如何授权的,但是如果你创建一个类:

    public bool CanRead { get; set; }
    public bool CanWrite { get; set; }
    public bool CanModify { get; set; }
    

    然后在AuthorizeCore方法中,根据设置判断用户是否有权限。

    【讨论】:

      猜你喜欢
      • 2013-06-19
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2011-06-07
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多