Add Permission-Attribute to Swashbucke-Swagger-Documentation

Viewed 1180

Having Swashbuckle integrated in my .Net Web-Api project (.Net Framework 4) I'm searching for a way to document the roles that are allowed to execute a respective method.

Each of my web-api methods have a custom attribute that checks the ActiveDirectory-Group of the requesting user and if the user is allowed to execute the action. But now I would like to document that using Swashbuckle-Swagger like

///
///<AllowedRole>Administrator</AllowedRole>
///
public IHttpActionResult Index(){
...
}

Or

[SwaggerAllowedRole("Administrator")]
public IHttpActionResult Index(){
    ...
}

I would love to hear that there is any standard that I can use. Can anyone give me a clever trick?

1 Answers

Now, I solved the problem using the "venderExtension" attribute. I created an "SwaggerGroups"-Attribute:

 [AttributeUsage(AttributeTargets.Method)]
 public class SwaggerGroupsAttribute : Attribute
 {
     public SwaggerGroupsAttribute(params string[] groups)
     {
         this.Groups = groups;
     }
     public IEnumerable<string> Groups{ get; }
 }

And an operation filter that reads the attributes and adds the list to the vendorExtension:

 public class GroupPermission: IOperationFilter
 {

        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var attributes = apiDescription.GetControllerAndActionAttributes<SwaggerGroupsAttribute>().SingleOrDefault();
            if (attributes == null) return;

            if(operation.vendorExtensions == null) operation.vendorExtensions = new Dictionary<string, object>();
            var permissionList = new List<string>();
            foreach(var permission in attributes.Permissions)
            {
                permissionList.Add(permission);
            }
            operation.vendorExtensions.Add("someKey", permissionList);
        }
    }

With this setup I can define the allowed roles as follows:

[SwaggerGroups("Administrator")]
public IHttpActionResult Index(){
    ...
}
Related