What Was I Thinking?

Follies & Foils of .NET Development
posts - 95 , comments - 352 , 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"


and add it to the Swagger middleware

services.AddSwaggerGen(c =>


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


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



# Send Cake Gift to Pune

Create an elegant expression of your special moments with delicious taste of Cake that comes in different flavors such as Black Forest Cake, Pineapple Cake, Vanilla Cake, Strawberry Cake, Chocolate Cake and so on. Cakes remain the prime ingredient of each and every celebration. Send Cakes to Pune and let the recipient pop into this real feast of joy. Just in few clicks, order online and let the recipient enjoy the burst of multiple assortments.
2/23/2018 12:32 AM | Pooja Gupta
Post A Comment

Powered by: