WebApi自定义授权属性不起作用

Lui*_*cia 2 c# asp.net-mvc asp.net-web-api

我需要使用Active Directory中的一个或多个特定用户来保护我的Web api,在web.config中,我具有以下代码:

<configSections> 
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />

    <section name="users" type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

  </configSections> 
  <users> 
    <add key="user" value="domain\loginname" /> 
  </users> 
  <system.web> 
    <authentication mode="Windows" /> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" /> 
  </system.web>
Run Code Online (Sandbox Code Playgroud)

然后,我有一个自定义授权属性,该属性从上面显示的web.config部分读取用户。

public class MyAuthorizeAttribute : AuthorizeAttribute
    {

        public MyAuthorizeAttribute(params string[] userKeys)
        {
            List<string> users = new List<string>(userKeys.Length); 
            var allUsers = (NameValueCollection)ConfigurationManager.GetSection("users");
            foreach (var userKey in userKeys)
            {
                users.Add(allUsers[userKey]);
            }

            this.Users = string.Join(",", users);
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool isAuthorized = base.AuthorizeCore(httpContext);
            bool isRequestHeaderOk = false;
            return isAuthorized && isRequestHeaderOk;
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题在于,即使在调试器中未放置Authorize Core,也不会在调试器中显示该JSON,即使我将硬编码的false放置在该浏览器中,也始终会显示该浏览器中的JSON。

然后,使用自定义的authorize属性装饰控制器

[MyAuthorize("user")]
        [ResponseType(typeof(tblCargo))]
        public IHttpActionResult GettblCargosByActivo()
        {
            var query = from c in db.tblCargos
                        orderby c.strCargo
                        select c;

            //var result = Newtonsoft.Json.JsonConvert.SerializeObject(query);
            //return result;

            return Ok(query);
        }
Run Code Online (Sandbox Code Playgroud)

在IIS中,唯一启用的方法是Windows身份验证

当我从另一台计算机浏览到该站点时,我会看到身份验证窗口,但是上面显示的authoze方法从未被点击过。

这是一篇不错的文章,它引导我朝正确的方向(我相信) Asp.net WebApi中的自定义授权-真是一团糟?

小智 6

  1. 您应该使用AuthorizeAttributeSystem.Web.Http,而不是System.Web.Mvc
  2. IsAuthorized改为实施。

protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        bool isAuthorized = base.IsAuthorized(actionContext);
        bool isRequestHeaderOk = false;
        return isAuthorized && isRequestHeaderOk;
    }
Run Code Online (Sandbox Code Playgroud)