简体   繁体   English

自定义授权属性 ASP.NET WebApi - Null 角色

[英]Custom Authorization Atribute ASP.NET WebApi - Null Roles

I'm trying to implement custom authorization and can't get the Roles to come through the attribute.我正在尝试实现自定义授权,但无法通过该属性获取角色。 If I run my code it's hitting the BasicAuth class but I can't get any roles values through.如果我运行我的代码,它会达到 BasicAuth class 但我无法通过任何角色值。 I've even tried creating a new "AllowedRoles" property to the class and that doesn't work either.我什至尝试为 class 创建一个新的“AllowedRoles”属性,但这也不起作用。 What am I doing wrong?我究竟做错了什么? How can I pass values through the custom attribute?如何通过自定义属性传递值?

   public class BasicAuthAttribute : AuthorizeAttribute 
    {
        private const string Realm = "my.api.com";

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var r = Roles; // NULL?


            //more code that's not relevant

        }

   public class ValuesController : ApiController
    {
        // GET api/<controller>
        [BasicAuth(Roles = "admin")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

   public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

    }

   public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

            // Basic Auth Attribute
            config.Filters.Add(new BasicAuthAttribute());
        }
    }



I had a similar problem and I found that, the first time that an action is called, the set of the properties of the authorization filter(s) for that action are called with the default value for the type of the property (eg null for strings).我有一个类似的问题,我发现,第一次调用一个动作时,该动作的授权过滤器的属性集被调用,并使用属性类型的默认值(例如 null 为字符串)。

In my case, I was "wrapping" the Roles with a custom RolesArray property that was something like:就我而言,我使用自定义 RolesArray 属性“包装”角色,类似于:

public string[] RolesArray { get => Roles is null ? new string[0] : Roles.Split(','); set => Roles = string.Join(",", value ?? new string[0]); }

And I was always getting string[0] because there was an unexpected call to set with null as value.而且我总是得到 string[0] 因为有一个意外的调用来设置 null 作为值。

The solution in my case was to prevent setting Roles if value was null, so:在我的情况下,解决方案是防止在值为 null 时设置角色,因此:

set { if (value is not null) Roles = ... }

In your case, the solution is more complicated.在您的情况下,解决方案更复杂。 Roles is not overridable.角色是不可覆盖的。 Furthermore, it set a private backing field that is then used in IsAuthorized Depending on how much you want to override the default implementation, you can try to shadow it with public new string Roles... and then override IsAuthorized, or you can completely re-implement the attribute by deriving from AuthorizationFilterAttribute.此外,它设置了一个私有支持字段,然后在 IsAuthorized 中使用根据您想要覆盖默认实现的程度,您可以尝试使用公共新字符串角色来隐藏它...然后覆盖 IsAuthorized,或者您可以完全重新- 通过从 AuthorizationFilterAttribute 派生来实现属性。

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

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