Wednesday, 30 January 2019

How to use JWT Authorization token in swagger .netCore?

It's easy to add Swashbuckle for the DotNet core application but without any Authorization for the API.
But some time we need to pass additional Authorization header in to API call. On that time this trick worked for me.

public static class Extensions
{
    public static IServiceCollection AddAsptricksSwaggerDocumentation(this IServiceCollection services)
    {
        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1"new Info
            {
                Version = "v1",
                Title = "Core API",
                Description = "ASP.NET Core API",
                TermsOfService = "None",
                Contact = new Contact
                {
                    Name = "Raj Kumar",
                    Email = ""
                },
                License = new License
                {
                    Name = "Demo"
                }
            });
            c.AddSecurityDefinition("Bearer"new ApiKeyScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = "header",
                Type = "apiKey"
            });
            c.AddSecurityRequirement(new Dictionary<stringIEnumerable<string>>
            {
            {"Bearer",new string[]{}}
            });
        });
        return services;
    }
 
    public static IServiceCollection AddAsptricksSwaggerDocumentationForMultipleHeader(this IServiceCollection services)
    {
        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1"new Info
            {
                Version = "v1",
                Title = "Core API",
                Description = "ASP.NET Core API",
                TermsOfService = "None",
                Contact = new Contact
                {
                    Name = "Raj Kumar",
                    Email = ""
                },
                License = new License
                {
                    Name = "Demo"
                }
            });
 
            //Distinguish model by Full name, if any duplicate exists.
            c.CustomSchemaIds(x => x.FullName);
 
            //Expose XML comments in doc.
            var xmlPath = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
            c.IncludeXmlComments(xmlPath);
            c.AddSecurityDefinition("Bearer"new ApiKeyScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = "header",
                Type = "apiKey"
            });
            c.AddSecurityRequirement(new Dictionary<stringIEnumerable<string>>
            {
                { "Bearer"new string[] { } }
            });
 
            c.AddSecurityDefinition("AdditionaHeaderData"new ApiKeyScheme()
            {
                Description = "Based on API demand",
                Name = "AdditionaHeaderData",
                In = "header",
                Type = "apiKey"
            });
            c.AddSecurityRequirement(new Dictionary<stringIEnumerable<string>>
            {
                { "AdditionaHeaderData"new string[] { } }
            });
        });
        return services;
    }
    public static IApplicationBuilder UseAsptricksSwaggerDocumentationUI(
      this IApplicationBuilder app)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            //Allow to add addition attribute info on doc. like [MaxLength(50)]
            c.ConfigObject = new ConfigObject
            {
                ShowCommonExtensions = true
            };
 
            c.SwaggerEndpoint("/swagger/v1/swagger.json""Asptricks.net API");
            c.RoutePrefix = "api/docs/index";
            c.InjectStylesheet("/swagger-ui/custom.css");
            c.InjectJavascript("/swagger-ui/custom.js");
            c.SupportedSubmitMethods(new[] { SubmitMethod.Patch });
 
            //Collapse model near example.
            c.DefaultModelExpandDepth(0);
 
            //Remove separate model definition.
            c.DefaultModelsExpandDepth(-1);
 
        });
 
        return app;
    }
 
 
}

Output:

If you want to modify the UI of swagger you can do it by adding your custom js and css file. So just add files as described in UseAsptricksSwaggerDocumentationUI
>wwwroot
--->swagger-ui
------->custom.js
------->custom.css


If you want to use example data or default value for swagger doc refer to this blog