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 asp.net 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 builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); 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 { Type=ReferenceType.SecurityScheme, Id="Bearer" } }, 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