Basic Authentication in Swagger .NET 5
Hi all,
Basic authentication is a very simple authentication scheme that is built into the HTTP protocol. The client sends HTTP requests with the Authorization header that contains the Basic word followed by a space and a base64-encoded Username:Password string. In this article, you can learn about how to setup the basic authentication for API's using swagger in ASP.NET 5.0.
Step 1:
Create a ASP.NET Core Web API project in Visual studio 2019.
Step 2:
Install Swashbuckle.AspNetCore package to the project.
Step 3:
Create IUserService.cs interface class and UserService.cs class in the project.
IUserService.cs
UserService.cs
Step 4:
Add BasicAuthenticationHandler Class to handle Basic Authentication.
Step 5:
Add Authorize attribute as header in the Controller to have Basic Authentication setup.
Step 6:
Add the configuration of Swagger in Startup.cs file for setup Basic Authentication in Swagger.
For that,
Add services.AddSwaggerGen to ConfigureServices method.
And add app.UseAuthentication() to Configure method.
Step 7:
Run the application and open Swagger URL. You can see Authorize button have enabled on the page.
Now, You can not do Api calls until your authorization successful. It gives 401 error.
Step 8:
Click the Authorize button and give correct username and password to access API.
Now, You can do Api calls and get responses.
Thank You!