What Was I Thinking?

Follies & Foils of .NET Development
posts - 94 , comments - 348 , trackbacks - 0

Swashbuckle Swagger UI– Prompt for Access Token (.net Core)

I use swagger to document my API endpoints.  I like the descriptive nature, and find the swagger UI to be a great place for quick testing and discovery.  

The swagger UI works great out of the box for unsecured API endpoints, but doesn’t seem to have any built-in support for requiring users to supply an access token if its required by the endpoint.

Based on my research, it appears we can add an operation filter to inject the parameter into the swagger ui.  Using the code at https://github.com/domaindrivendev/Swashbuckle/issues/290 as a guide, I’ve ported the filter to .net core (2.0) as:

/// <summary>
    ///     This swagger operation filter
    ///     inspects the filter descriptors to look for authorization filters
    ///     and if found, will add a non-body operation parameter that
    ///     requires the user to provide an access token when invoking the api endpoints
    /// </summary>
     public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
    {
        #region Implementation of IOperationFilter

        /// <summary>
        /// </summary>
         /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            var descriptor = context.ApiDescription.ActionDescriptor;

            var isAuthorized = descriptor.FilterDescriptors
                 .Any(i => i.Filter is AuthorizeFilter);


             var allowAnonymous = descriptor.FilterDescriptors
                 .Any(i => i.Filter is AllowAnonymousFilter);

            if (isAuthorized && !allowAnonymous)
            {

                if (operation.Parameters == null)
                {
                     operation.Parameters = new List<IParameter>();
                }
                operation.Parameters.Add(new NonBodyParameter
                {
                    Name = "Authorization",
                    In = "header",
                     Description = "access token",
                    Required = true,
                    Type = "string"
                 });
            }
        }

        #endregion
    }

and add it to the Swagger middleware

services.AddSwaggerGen(c =>
          {
            …

              c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
          });

That’s it!  now when an endpoint requires an access token, the swagger UI will render a parameter for it:

image

Print | posted on Wednesday, November 22, 2017 11:21 AM | Filed Under [ Visual Studio ]

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: