简体   繁体   中英

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. I've even tried creating a new "AllowedRoles" property to the class and that doesn't work either. 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).

In my case, I was "wrapping" the Roles with a custom RolesArray property that was something like:

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.

The solution in my case was to prevent setting Roles if value was null, so:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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