【问题标题】:Web API Controller Authorization with parameters带参数的 Web API 控制器授权
【发布时间】:2020-06-26 21:18:13
【问题描述】:

我有一个 MVC5 应用程序,我们使用 mvc 控制器和 web api 控制器。

我们的 MVC 控制器上有如下授权属性:

    /// <summary>
    /// Only allows authorization if the logged in user has the corresponding application access name
    /// </summary>
    /// <seealso cref="AuthorizeAttribute" />
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class ApplicationAccessAuthorizationAttribute : AuthorizationBaseAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ApplicationAccessAuthorizationAttribute"/> class.
        /// </summary>
        /// <param name="accessNames">Name of the access.</param>
        public ApplicationAccessAuthorizationAttribute(string accessNames)
        {
            AccessNames = accessNames.Split(',');
        }

        /// <summary>
        /// Gets or sets a comma separated list of access names to apply against the users
        /// permission set.
        /// </summary>
        protected IList<string> AccessNames { get; set; }

        /// <summary>
        /// Called when a process requests authorization.
        /// </summary>
        /// <param name="filterContext">The filter context, which encapsulates information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute" />.</param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Account", action = "Login", area = string.Empty, returnURL = HttpContext.Current.Request.RawUrl }));
            }
            else
            {
                     var currentUserId = GetUserId();

                    var userPermissions = Task.Run(() => UserService.GetUsersApplicationAccess(currentUserId)).Result;
                    var permissions = userPermissions.Select(x => x.AccessName).ToList();

                    if (!permissions.Intersect(AccessNames).Any())
                    {
                        filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Error", action = "NotFound", area = string.Empty }));
                    }
            }
        }
    }

那我们这样称呼它:

    [ApplicationAccessAuthorization(ApplicationAccessConstants.Manager)]

我需要在 WebAPI 控制器上复制它。

我知道我需要在 WebApiConfig 文件中添加一个过滤器。

但是如何传递 Web API 控制器中每个控制器/操作调用所请求的特定访问名称?

    public static class WebApiConfig
    {
        /// <summary>
        /// Registers the specified configuration.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            // Log the filter here for the api controllers error handling ; this should catch all errors that occur within the web api
            config.Filters.Add(new APICustomExceptionFilter();
        }
    }

如何通过 API Web 控制器设置传递参数?

因为当我在 WebAPIConfig 文件中设置过滤器时,它迫使我添加“AccessNames”作为参数,但我还没有访问权限?

【问题讨论】:

  • 什么不起作用?我相信你应该做同样的事情。只需从AuthorizeAttribute 继承即可。什么不工作?
  • @Michael:我最后更新了我的问题,但是:因为当我在 WebAPIConfig 文件中设置过滤器时,它迫使我添加“AccessNames”作为参数,但我没有访问到了吗?那么我是否必须在 Web API 控制器配置中添加一些内容作为过滤器,或者是否有其他方法可以强制触发该属性?

标签: c# authentication asp.net-web-api


【解决方案1】:

我不需要 WebApiConfig.cs 过滤器。我可以忽略它,我将它从 MVC 更改为 API Controller 属性似乎已经修复了它。

    /// <summary>
    /// Only allows authorization if the logged in user has the corresponding application access name
    /// </summary>
    /// <seealso cref="AuthorizeAttribute" />
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class WebApplicationAccessAuthorizationAttribute : AuthorizationFilterAttribute
...

【讨论】:

    猜你喜欢
    • 2013-02-22
    • 2018-01-29
    • 2020-04-15
    • 2023-01-19
    • 2018-09-29
    • 2014-01-04
    • 1970-01-01
    • 2013-08-29
    • 2016-05-03
    相关资源
    最近更新 更多