简体   繁体   English

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

[英]WebApi custom authorization attribute not working

I have the following Custom Authorize attribute 我有以下自定义授权属性

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);
        }
    }
}

I have the following web api method 我有以下web api方法

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

And I have this in the web.config 我在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>

I put my username there, and when I share the API methods url to a colleague, he can see the JSON immediately, it should be access denied. 我把我的用户名放在那里,当我向同事分享API方法url时,他可以立即看到JSON,它应该被拒绝访问。

What am I missing? 我错过了什么?

Check this: How to do role based authorization for asp.net mvc 4 web api and also ASP.NET MVC 4 Web API Authentication with Membership Provider . 检查: 如何对asp.net mvc 4 web api进行基于角色的授权,以及如何 使用成员资格提供程序进行ASP.NET MVC 4 Web API身份验证

Try to enable Windows Authentication on IIS, override OnAuthorize method of AuthorizationAttribute and check if user is set correctly. 尝试在IIS上启用Windows身份验证,重写AuthorizationAttribute的OnAuthorize方法并检查用户是否设置正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM