How to Implement authorization for Swagger in ASP.NET Core
By FoxLearn 2/26/2025 4:03:24 AM 118
Swagger provides a user-friendly interface for visualizing and testing API methods, and in this article, we'll focus on how to implement authentication for Swagger in an ASP.NET Core project.
If you're unfamiliar with Swagger, I encourage you to review my earlier article that introduces Swagger. In this tutorial, we’ll explore how to implement basic authentication for Swagger using JSON Web Tokens (JWT).
Setting Up Swagger with OpenAPI Support
The OpenAPI Specification (previously known as Swagger Specification) defines a standardized, machine-readable format for describing APIs. It provides a clear and concise representation of an API’s resources and operations, making it easy for developers to design and consume APIs.
When you create an ASP.NET Core Web API project with OpenAPI support enabled, the Swashbuckle.AspNetCore package is automatically included. Swashbuckle is an open-source project that simplifies generating Swagger documentation for ASP.NET Core APIs.
If your project doesn't have OpenAPI support enabled, you can install the Swashbuckle package manually using the NuGet Package Manager:
PM> Install-Package Swashbuckle.AspNetCore
Now, open the Program.cs
file and you should see the following code, which configures Swagger:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseAuthorization(); app.MapControllers(); app.Run();
Using the Swagger UI
When you run the application, the Swagger UI should load in your browser. You’ll see a list of available API endpoints, including the default WeatherForecast
controller, which includes an HttpGet
method.
Now, we’ll implement authentication for Swagger.
Creating a Login Controller for Authentication
To authenticate users, we’ll create a User
class to capture the username and password. Then, we'll create a LoginController
that returns a JWT upon successful authentication.
Create the User
class:
public class User { public string UserName { get; set; } public string Password { get; set; } }
Create the LoginController
to validate credentials:
[Route("api/[controller]")] [ApiController] public class LoginController : ControllerBase { [HttpPost, Route("login")] public IActionResult Login(User user) { try { if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password)) return BadRequest("Username and/or Password not specified"); if (user.UserName.Equals("admin") && user.Password.Equals("admin123")) { var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key-here")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var jwtSecurityToken = new JwtSecurityToken( issuer: "YourIssuer", audience: "YourAudience", claims: new List<Claim>(), expires: DateTime.Now.AddMinutes(15), signingCredentials: signinCredentials ); return Ok(new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken)); } } catch { return BadRequest("An error occurred while generating the token"); } return Unauthorized(); } }
This controller accepts a POST request with the login details. If the credentials match the predefined values, it generates and returns a JWT.
Implementing Authorization in Swagger
Now we will modify the Program.cs
to enable JWT authentication for Swagger. Add the following code to configure Swagger's security definition:
builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" }); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please enter a valid token", Name = "Authorization", Type = SecuritySchemeType.Http, BearerFormat = "JWT", Scheme = "Bearer" }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] {} } }); });
This code sets up Swagger to expect a bearer token in the Authorization
header when making requests.
Protecting Endpoints with the [Authorize]
Attribute
To restrict access to certain endpoints, apply the [Authorize]
attribute to those methods. For example, in the WeatherController
, apply the [Authorize]
attribute to the HttpGet
method:
[HttpGet(Name = "GetWeatherForecast"), Authorize] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToArray(); }
With the [Authorize]
attribute in place, a valid JWT token is required to access this endpoint.
Generating and Using a JWT Token in Swagger
Now that we've configured authentication, you can use the Swagger UI to generate a JWT token. Execute the Login
method from the LoginController
by providing the correct credentials:
- Username:
admin
- Password:
admin123
Upon success, Swagger will return a JWT token that you can use for authentication. To use this token in Swagger:
- Click the Authorize button in the Swagger UI.
- Paste the JWT token into the Authorization field.
- Now, you can test the secured API endpoints that require authentication.
Swagger, combined with JWT authentication, provides a seamless way to document and test secure APIs. Swashbuckle is an excellent tool for generating Swagger documentation in ASP.NET Core, and it’s easy to configure. By implementing the steps outlined in this article, you can quickly secure your API endpoints with JWT authentication and allow developers to test them through the Swagger UI.