Include Bearer token in swagger

  • builder.Services.AddOpenApi(); // this line is commented
  • builder.Services.AddSwaggerGen method is enhanced.
  • It is not recommended to downgrade from open api. But if someone still wants to use the old way then they can still progress as below.
  • Use Scalar package if possible to get the best features as compared to swagger.
				
					using JWT_WebApi;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Scalar.AspNetCore;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
//builder.Services.AddOpenApi();


//1. jwt configure
var jwtSettings = new Jwtsettings();
builder.Configuration.GetSection("JwtSettings").Bind(jwtSettings);
builder.Services.AddSingleton(jwtSettings);

//2. jwt AddAuthentication....place it in extension method...
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{

    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = jwtSettings.Issuer,
        ValidAudience = jwtSettings.Audience,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
    };
});

//3....jwt
builder.Services.AddAuthorization();


// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
//builder.Services.AddOpenApi();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
    {
        Description = "",
        Name = "Authorization",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Scheme = "Bearer"
    });

    options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement()
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                  Type =ReferenceType.SecurityScheme,
                   Id="Bearer"
                },
            Scheme ="oauth2",
            Name ="Bearer",
            In = ParameterLocation.Header
            },new List<string>()
        }
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    //app.MapOpenApi();
    //only call you need to do
    app.UseSwaggerUI();

    //app.MapScalarApiReference(options =>
    //{
    //    options.WithTitle("Demo Api")
    //    .WithTheme(ScalarTheme.Mars);
    //});
}


app.UseHttpsRedirection();

//4.jwt 
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

				
			

Leave a Comment