Home » Web API » Test Web API with JWT Bearer Authentication In Swagger – .Net Core

Test Web API with JWT Bearer Authentication In Swagger – .Net Core

In this article, we’ll walk through the steps to configure Swagger in a Web API with JWT Bearer Authentication to provide comprehensive documentation and testing capabilities while ensuring security.

Prerequisites

Before we look into the configuration process, make sure:
1) You have installed the Swashbuckle NuGet package, which integrates Swagger with your API or .NET Core application.
2) You should have JWT Bearer Authentication set up in your Web API to validate incoming tokens.


Configure Swagger with JWT Bearer Authentication

Now, let’s configure Swagger to work with JWT Bearer Authentication in your .NET Core Web API.

Open your Startup.cs file and add the necessary configurations for Swagger in the ConfigureServices and Configure methods.

Startup.cs
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Reflection;


public void ConfigureServices(IServiceCollection services)
{
	// ...

	services.AddSwaggerGen(swagger =>
	{
		//This is to generate the Default UI of Swagger Documentation  
		swagger.SwaggerDoc("v1", new OpenApiInfo
		{
			Version = "v1",
			Title = "My App",
			Description = "About Application"
		});

		// Set the comments path for the Swagger JSON and UI.
		var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
		var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
		swagger.IncludeXmlComments(xmlPath);                
	});

	//To Enable authorization using Swagger (JWT)
	swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
	{
		Name = "Authorization",
		Type = SecuritySchemeType.ApiKey,
		Scheme = "Bearer",
		BearerFormat = "JWT",
		In = ParameterLocation.Header,
		Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
	});
	swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
	{
		{
			  new OpenApiSecurityScheme
				{
					Reference = new OpenApiReference
					{
						Type = ReferenceType.SecurityScheme,
						Id = "Bearer"
					}
				},
				new string[] {}
		}
	});
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	// ...

	// Enable middleware to serve generated Swagger as a JSON endpoint.
	app.UseSwagger();

	// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
	// specifying the Swagger JSON endpoint.
	app.UseSwaggerUI(c =>
	{
		c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API Name v1");
	});
} 


Secure Your API

Make sure your API controllers and actions are protected using JWT Bearer Authentication. You can use the [Authorize] attribute on specific controllers or actions that require authentication.

example:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class YourController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public IActionResult Get()
    {
        // Your action logic
    }
} 


Test Your API with Swagger JWT Bearer Authentication

With Swagger configured, you can now test your API with JWT Bearer Authentication:
  1. Start your .NET Core Web API project.
  2. Navigate to the Swagger UI by accessing /swagger in your web application (e.g., http://localhost:5000/swagger).
  3. Click on the “Authorize” button in the top right corner of the Swagger UI.
    swagger jwt bearer token authorize button

  4. In the “Authorization” dialog, enter your JWT token in the following format: Bearer YOUR_JWT_TOKEN.
    swagger jwt bearer token authorization dialog

  5. Click “Authorize” to authenticate.
  6. Explore the available API endpoints, provide any required input data, and click “Execute” to test your API.

Swagger will include the JWT token in the “Authorization” header automatically, allowing you to test the secured endpoints.

Leave a Reply

Your email address will not be published. Required fields are marked *