JWT Authentication and Role-Based Authorization with .NET 9 and Scalar in Visual Studio 2022

Introduction

Securing APIs is a critical aspect of modern web development. Implementing JWT (JSON Web Token) authentication combined with role-based authorization ensures that only authenticated users with appropriate permissions can access specific resources. This guide provides a step-by-step approach to setting up JWT authentication and role-based authorization in a .NET 9 Web API using Visual Studio 2022, with Scalar for API documentation.

Project Setup

  1. Create a new ASP.NET Core Web API project:

    • Open Visual Studio 2022.

    • Click on "Create a new project."

    • Select "ASP.NET Core Web API" and click "Next."

    • Name your project (e.g., JwtAuthDemo) and choose a location. Click "Next."

    • In the "Additional Information" dialog:

      • Target Framework: .NET 9.0

      • Authentication Type: "None"

      • Check "Use controllers (uncheck to use minimal APIs)"

      • Click "Create."

  2. Install necessary NuGet packages:

    • Right-click on the project in Solution Explorer and select "Manage NuGet Packages."

    • Install the following packages:

      • Microsoft.AspNetCore.Authentication.JwtBearer

      • Microsoft.AspNetCore.Identity.EntityFrameworkCore

      • Microsoft.EntityFrameworkCore.SqlServer

      • Scalar.AspNetCore

      • Microsoft.AspNetCore.OpenApi

Setup Scalar Docs

Scalar is a modern alternative to Swagger for API documentation.

  1. Configure Scalar in Program.cs.

    builder.Services.AddOpenApi(options =>
    {
        options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
    });
    
    var app = builder.Build();
    
    app.MapOpenApi();
    app.MapScalarApiReference(options =>
    {
        options.WithTheme(ScalarTheme.Moon)
               .WithDarkMode(true)
               .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient)
               .WithDarkModeToggle(false)
               .WithPreferredScheme("Bearer")
               .WithHttpBearerAuthentication(bearer =>
               {
                   bearer.Token = "your-bearer-token";
               });
        options.Authentication = new ScalarAuthenticationOptions
        {
            PreferredSecurityScheme = "Bearer"
        };
    });
    
  2. Implement BearerSecuritySchemeTransformer:

    public class BearerSecuritySchemeTransformer : IDocumentTransformer
    {
        public void Apply(OpenApiDocument document, DocumentTransformerContext context)
        {
            var securityScheme = new OpenApiSecurityScheme
            {
                Type = SecuritySchemeType.Http,
                Scheme = "bearer",
                BearerFormat = "JWT",
                In = ParameterLocation.Header,
                Name = "Authorization",
                Description = "JWT Authorization header using the Bearer scheme."
            };
    
            document.Components.SecuritySchemes.Add("Bearer", securityScheme);
    
            document.SecurityRequirements.Add(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    new string[] {}
                }
            });
        }
    }

Setup Identity

Section content here...

Migration and Seed Roles and Users

Section content here...

Setup JWT Configuration

Section content here...

Generate Token

Section content here...

Refresh Token

Section content here...

Login Example

Section content here...

Mock Endpoints

Section content here...

Conclusion

Section content here...

React
Next.js
Node.js
TailwindCSS
JavaScript

Popular Blogs

  • React Server Components Guide
  • Next.js vs Remix
  • JavaScript Performance Tips
Author

NEPCODER

Full-Stack Developer & Tech Blogger

Subscribe to Our Newsletter

Get the latest posts delivered to your inbox.