Skip to content

Setup Authorization In Swagger Asp.Net Core API

Swagger is a very helpful library that provides nice UI for web API projects. It enables easy user testing of these API endpoints, and in most cases eliminate the need of REST client tools like Postman.

In this article we will see how we can add authorization option in the swagger in core web API project.

For that all you need is to configure you swagger service to add bearer token like this:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// your other services

// Learn more about configuring Swagger/OpenAPI at
builder.Services.AddSwaggerGen(c =>
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        In = ParameterLocation.Header,
        Description = "Please enter token",
        Name = "Authorization",
        Type = SecuritySchemeType.Http,
        BearerFormat = "JWT",
        Scheme = "bearer"
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
            new OpenApiSecurityScheme
                Reference = new OpenApiReference
            new string[]{}

var app = builder.Build();

Now if you run your project, you will see authorization option on top right side of screen. Once you run the login API endpoint and obtain the JWT token, now you can click on this authorization button, it will ask for JWT token, paste the token you obtained earlier, and click on OK. This will add this token in all the requests you have in your API.

Nice and easy.

Be First to Comment

Leave a Reply

Your email address will not be published.