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.


// 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[]{}}
    });
});

If we need to add some additional header instead of Authorization, we can add it

// 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[] { } }
    });
 
    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[] { } }
    });
});


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

>wwwroot
--->swagger-ui
------->custom.js
------->custom.css



app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json""API V1");
    c.RoutePrefix ="docs";
    c.InjectStylesheet("/swagger-ui/custom.css");
    c.InjectJavascript("/swagger-ui/custom.js");
 
});