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

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

我有以下自定义授权属性

namespace xx.Api
{
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        public MyAuthorizeAttribute(params string[] roleKeys)
        {
            List<string> users = new List<string>(roleKeys.Length); 
            var allRoles = (NameValueCollection)ConfigurationManager.GetSection("users");
            foreach (var roleKey in roleKeys)
            {
                users.Add(allRoles[roleKey]);
            }
            this.Roles = string.Join(",", users);
        }
    }
}

我有以下网络 api 方法

[MyAuthorize("user")]
        [ResponseType(typeof(tblArea))]
        public IHttpActionResult GettblAreasByActivo()
        {
            var query = from a in db.tblAreas
                        orderby a.strArea
                        select a;

我在 web.config 中有这个

<configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <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'firstname.lastname" />
  </users>

我把我的用户名放在那里,当我将 API 方法 url 分享给同事时,他可以立即看到 JSON,应该拒绝访问。

我错过了什么?

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

检查以下内容:如何对 asp.net mvc 4 Web api 以及使用成员资格提供程序 ASP.NET MVC 4 Web API 身份验证执行基于角色的授权。

尝试在 IIS 上启用 Windows 身份验证,覆盖授权属性的授权方法,并检查用户设置是否正确。