首页 > 解决方案 > Web API 拦截器

问题描述

我在我的 web api 上创建了一个自定义授权属性。我的目标是检查用户是否有权直接访问 web api url,否则将他重定向到未经授权的页面。这个过程需要我在任何地方添加 [CustomAuthorize("modulename")]。有没有其他方法可以做到这一点? 可能是拦截器?。任何指导将不胜感激。

         Customised authorize attribute pseudo code snippet: 

        public override void OnAuthorization(HttpActionContext context){
                var username = HttpContext.Current.Request.LogonUserIdentity.Name;
                 var  accesiblemodulelistforuser = GetPermissions(username );

                if (user != null)
            {
                if (modulename does not exist in list )
                {
                var response = 
                context.Request.CreateResponse(HttpStatusCode.Forbidden);
                    context.Response = response;

                }
           else{
          return;

                }

                  }
              else{
                        //redirect to unauthorized page
                  }
              }

标签: c#.netasp.net-web-apiinterceptor

解决方案


在你的 ASP.NET 版本中没有类定义,所以我假设你继承了ActionFilterAttributeclass 。刚刚注意到,你不是。见编辑版本。如果是这样,您可以为所有 Web api 操作和控制器全局注册过滤器,WebApiConfig.cs如下所示:

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new CustomAuthorize());
}

编辑

完全误解了你的情况。所以有更多的信息。您可以使用自己的全局授权过滤器:

public class CustomAuthorize : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            // user not authorized, redirect to login page
            filterContext.Result = new HttpUnauthorizedResult();

            return;
        }

        string roleName = GetModuleName(filterContext);
        var user = filterContext.HttpContext.User;


        // Chaeck user permissions
        if (!user.IsInRole(roleName))
        {
            // Handle not authorized requests and redirect to error page
            filterContext.Result = new RedirectResult("~/Error/NotAuthorized");
            return;
        }

        base.OnAuthorization(filterContext);
    }

    string GetModuleName(AuthorizationContext filterContext)
    {
        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
        var actionName = filterContext.ActionDescriptor.ActionName;

        return controllerName; // or actionName
    }
}

您可以WebApiConfig.cs像这样为所有操作和控制器全局注册过滤器:

public static void Register(HttpConfiguration config)
{
    filters.Add(new CustomAuthorize());
}

或仅用于特定的控制器/动作。

请注意,这种方法不适用于 web api,仅适用于 mvc,因为 web api 有它自己的AuthorizeAttribute位置System.Web.Http(MVC 版本位于System.Web.Mvc)。实现方式略有不同,但您可以查找示例。所以你需要拥有不同的属性——一个用于 MVC,一个用于 WEB API。请参阅原始答案以了解如何全局注册 WEB API 过滤器,或仅将其用于特定控制器。


推荐阅读