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

标签 c# asp.net-mvc asp.net-web-api

我有以下自定义授权属性

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

我有以下 web 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,应该是访问被拒绝。

我错过了什么?

最佳答案

检查这个:How to do role based authorization for asp.net mvc 4 web api还有ASP.NET MVC 4 Web API Authentication with Membership Provider .

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

关于c# - WebApi 自定义授权属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35207715/

相关文章:

c# - MVC4 - 如何从 Razor View 调用 Controller 方法

asp.net-mvc - ASP.NET MVC - 如何实现分页?

c# - IdentityServer 4,试图用 fiddler 捕获流量?

c# - Web API 中的电子邮件确认

c# - ObservableCollection 不支持 AddRange 方法,因此除了 INotifyCollectionChanging 之外,我会收到添加的每个项目的通知?

C# AutoResetEvent 不释放

c# - WPF C# MVC/MVP 模式和用户控制代码隐藏

c# - 具有异步和等待的 MVC 操作

asp.net-web-api - 为什么当我发布到服务器时,NSwag/Swagger 方案仅设置为 HTTP,但在我的本地计算机上却设置为 HTTPS?

c# - 如何检查空文本框