In this blog post, we will walk through how to set up a security scheme in Swagger for your ASP.NET Web API, enabling secure authentication using API keys or authentication tokens. This tutorial is based on an example where the authentication is done via a token passed through the HTTP header.
Why is this important?
By default, Swagger UI provides a great interface to test API endpoints. However, when your API requires authentication via headers, cookies, or query strings, you’ll need a way to pass that information securely through Swagger. This post demonstrates how to set up the Swagger UI to accept and use authentication tokens or API keys, particularly when passing these tokens through HTTP headers.
Step 1: Setting up the API Controller for Swagger Authentication
Let’s start by making sure your API controller is set up to handle authorization via headers.
In your WeatherForecastController
, for example, you may want to check if the Authorization
header is provided in the request. If it’s missing, you should return a 401 Unauthorized
response:
[HttpGet]
public ActionResult<IEnumerable<WeatherForecast>> Get()
{
if (!Request.Headers.ContainsKey("Authorization"))
{
return Unauthorized();
}
// Log or process the authorization header
Console.WriteLine(Request.Headers["Authorization"]);
return Ok(new List<WeatherForecast> { /* your forecast data */ });
}
At this point, if you run the application and try to access the Swagger UI, you will receive a 401 Unauthorized
error since the authentication token is missing.
Step 2: Adding Authentication Configuration in Swagger
Now, we need to configure Swagger to accept and use authentication. We will update the Swagger configuration to add a security scheme for the API.
Modify Program.cs
(or Startup.cs
for older versions):
- Add Security Definition
In this step, we define the security scheme for Swagger to recognize how to authenticate the API requests.Add the following code in theConfigureServices
method:
services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Au", new OpenApiSecurityScheme
{
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
Description = "Enter your Bearer token here"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{ new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Au"
}
}, new List<string>() }
});
});
Explanation:
- Name: This is the name of the header parameter (e.g.,
Authorization
). - In: Specifies where the API key will be passed (in our case, through the header).
- Type: The type of security, in this case,
Http
, which is used for token-based authentication. - Scheme: The authorization scheme, here it’s set to
Bearer
. - Description: Provides additional details in Swagger UI, guiding users on how to use the token.
- Add Security Requirement
Next, we ensure that this authentication requirement is added to each endpoint by linking the security definition:
services.AddSwaggerGen(options =>
{
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{ new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Au"
}
}, new List<string>() }
});
});
This tells Swagger that the authentication method (Au
) should be required when accessing the API endpoints.
Step 3: Running the Application
Now that you’ve updated your Swagger configuration, go ahead and run the application. When you open Swagger UI, you will notice a new “Authorize” button at the top. Click on it, and you will be prompted to enter a Bearer token.
- The Swagger UI will now show the expected behavior of asking for an authentication token.
- Once you provide the token, it will be automatically included in the headers of any API request made via Swagger, allowing the API to authenticate the request successfully.
Step 4: Testing
- Provide Token: In Swagger UI, click the “Authorize” button, and enter a Bearer token, for example:
Bearer 1234567890abcdef
- Test the Endpoint: After entering the token, try calling any secured endpoint. You should now receive a valid response instead of a
401 Unauthorized
.
Final Thoughts
By adding a security definition and requirement in Swagger, you make it clear to users how to authenticate when interacting with your API. This is especially helpful when building APIs that require tokens or API keys for access, ensuring that both the contract and the implementation are secure.
This setup also facilitates automated client generation tools that use the Swagger/OpenAPI specification, allowing them to know how to handle authentication tokens properly.
With this approach, you’ve successfully configured Swagger to support secure authentication in your ASP.NET Core API.
This entire exercise is available in a YouTube video here: https://youtu.be/AIeUbh07Pfs?si=0I2Jc05GBKFqcXyM