WebAPI 自定义授权属性

本文关键字:属性 授权 自定义 WebAPI | 更新日期: 2023-09-27 18:33:17

我一直在为这个而磨头。我一直在尝试为 WebAPI 实现自定义授权属性。我已经阅读了多篇关于如何执行此操作的文章,但由于某种原因,授权从未执行。

public class ActivityAuthorizeWebApiAttribute : System.Web.Http.AuthorizeAttribute
{
    private string[] Activities { get; set; }
    public string Activity
    {
        set
        {
            this.Activities = value.Split(',').Select(x => x.Trim()).ToArray();
        }
        get { return string.Join(",", this.Activities); }
    }
    public ActivityAuthorizeWebApiAttribute()
    {
    }
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var principalUser = HttpContext.Current.User;
        if (principalUser == null || !principalUser.Identity.IsAuthenticated)
        {
            return false;
        }
        if (!principalUser.Activities().Any())
        {
            var activityProvider = (IActivityProvider)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IActivityProvider));
            var activities = activityProvider.GetActivitiesByRoleId(principalUser.Identity.GetUserId());
            principalUser.SetActivities(activities);
        }
        return principalUser.HasAnyActivity(this.Activities.ToList());
        //check your permissions
    }
}

正如我所看到的,我是从正确的授权属性继承的,而不是 mvc 的。但从不调用 IsAuthorized 方法。控制器操作

[ActivityAuthorizeWebApi(Activity = "Home")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

可能是因为与持有者令牌身份验证的组合吗?

编辑:我什至尝试过以下代码:

public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
{
}

作为自定义代码执行,而不是授权。

WebAPI 自定义授权属性

创建自定义属性时,您需要挂钩到以下方法:

 public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
 protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
 private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)

它是您需要覆盖和执行安全逻辑的 OnAuthorization 方法。您可以从签名方法中的 actionContext 中获取用户。

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
         public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (AuthorizeRequest(actionContext))
            {
                return;
            }
            HandleUnauthorizedRequest(actionContext);
        }
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
           //Code to handle unauthorized request
        }
        private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //Write your code here to perform authorization
            return true;
        }
    }