How to Implement Authorization ASP.NET Core 6

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:

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. 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).
  9. Ensure that the “Enable Docker” and “Configure for HTTPS” check boxes are unchecked as we won’t be using those features here.
  10. 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.

If you created your project without enabling OpenAPI support, you would have to install the Swashbuckle package via the NuGet Package Manager Console as shown below.

PM> Install-Package Swashbuckle.AspNetCore

When you open the Program.cs file, you should see the following code.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
if (app.Environment.IsDevelopment())

The Swagger UI

And when you execute the application, you should see the Swagger UI displayed in the web browser as shown in figure below.

As you can see, the Swagger UI shows the WeatherForecast controller that is created by default when you create a new ASP.NET Core 6 API project. There is just one HttpGet action method in this controller.

You can execute the endpoint without having to specify any authentication information, and the output should be similar like below

We’ll learn how to implement authentication in Swagger shortly. Let’s first create a new API controller to validate user credentials and return a JSON Web Token (JWT) if the credentials are valid.

Create a login controller in ASP.NET Core 6

Create a new class named LoginDTO in a file with the same name and a .cs extension. Now write the following code in there.

public class LoginDTO
public string UserName { get; set; }
public string Password { get; set; }

Create a new API controller named LoginController and insert the following code.

public class LoginController : ControllerBase
    [HttpPost, Route("login")]
    public IActionResult Login(LoginDTO loginDTO)
            if (string.IsNullOrEmpty(loginDTO.UserName) ||
                return BadRequest("Username and/or Password not specified");
            if (loginDTO.UserName.Equals("joydip") &&
                var secretKey = new SymmetricSecurityKey
                var signinCredentials = new SigningCredentials
               (secretKey, SecurityAlgorithms.HmacSha256);
                var jwtSecurityToken = new JwtSecurityToken(
                    issuer: "ABCXYZ",
                    audience: "http://localhost:51398",
                    claims: new List<Claim>(),
                    expires: DateTime.Now.AddMinutes(10),
                    signingCredentials: signinCredentials
                Ok(new JwtSecurityTokenHandler().
           return BadRequest
           ("An error occurred in generating the token");
        return Unauthorized();

The LoginController contains only one HttpPost action method. Note how the user credentials are validated and the JWT token generated.

Secure the Swagger UI in ASP.NET Core 6

To implement authentication in Swagger, write the following code in the Program class.

builder.Services.AddSwaggerGen(option =>
    option.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" });
    option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        In = ParameterLocation.Header,
        Description = "Please enter a valid token",
        Name = "Authorization",
        Type = SecuritySchemeType.Http,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    option.AddSecurityRequirement(new OpenApiSecurityRequirement
            new OpenApiSecurityScheme
                Reference = new OpenApiReference
            new string[]{}

Apply the Authorize attribute in ASP.NET Core 6

Next, apply the Authorize attribute on the HttpGet action method of the WeatherController as shown in the code snippet given below.

[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)]

With the Authorization attribute applied, an authentication token will now be required to execute this endpoint in Swagger.

Generate a JWT token in ASP.NET Core 6

Now, execute the HttpPost action method of the LoginController and specify the credentials as shown below.

Lastly, you can execute the same endpoint again in the Swagger UI after specifying the authentication token. The endpoint will work this time and you’ll be able to see the output in the Swagger UI.

Swashbuckle is a great tool for generating Swagger documents for your API. It is quite easy to configure and customize. You can use Swagger with minimal APIs in ASP.NET Core 6 as well.


Related Posts

Leave a Reply

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