VS1 Cloud Blog
Implement authorization for Swagger in ASP.NET Core 6
25th Feb 2022 | Software
When building your .NET 6 applications, you might often need to generate API documentation. To do this, you might use Swagger, a toolkit that makes it simple to provide a graphical representation of your API. You can test the API methods within the Swagger UI once the API documentation is available.
If you could use an introduction to Swagger, I provided one in an earlier article. In this article I’ll discuss how we can implement basic authentication in Swagger. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.
Create an ASP.NET Core Web API project in Visual Studio 2022
First off, let’s create an ASP.NET Core project in Visual Studio 2022. Following these steps to create a new ASP.NET Core 6 Web API project in Visual Studio 2022:
Launch the Visual Studio 2022 IDE.
Click on “Create new project.”
In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
Click Next.
In the “Configure your new project” window, specify the name and location for the new project.
Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
Click Next.
In the “Additional Information” window shown next, select .NET 6.0 as the target framework from the drop-down list at the top. Set “Authentication Type” to “None” (default) and check the last two check boxes (Use controllers and Enable OpenAPI support).
Ensure that the “Enable Docker” and “Configure for HTTPS” check boxes are unchecked as we won’t be using those features here.
Click Create.
You should now have a new ASP.NET Core 6 Web API project ready to go. We’ll use this project in the subsequent sections of this article.
Configure Swagger to enable OpenAPI support
The OpenAPI Specification, formerly known as the Swagger Specification, defines a standard, machine-readable, programming language-agnostic interface description language for APIs. By effectively mapping all of the resources and processes associated with an API, a Swagger definition establishes a RESTful interface for conveniently designing and consuming the API.
Because we enabled OpenAPI support when we created our ASP.NET Core 6 Web API project, the Swashbuckle.AspNetCore package will be added to the project automatically. Swashbuckle is an open source project that enables the generation of Swagger documentation.