How to add an authorize button in Swagger UI using asp.net core

  • Post category:asp.net core
  • Reading time:2 mins read

By default authorize button is missing in Swagger UI. So if you use any Authorization system in your application you are unable to use [Authorize] attribute. For escaping this problem you need to add few lines of codes in the Startup.cs class

Step 1: Open your API project and go to Startup.cs

Step 2: Go to ConfigureServices(IServiceCollection services) method there you can see this.

services.AddSwaggerGen(c =>{
   c.SwaggerDoc("v1", new OpenApiInfo { Title = "YOURPROJECTNAME", Version = "v1" });
});

Step 3: Replace this with the given code bellow

services.AddSwaggerGen(c =>{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "JWTToken", Version = "v1" });
    
// Include 'SecurityScheme' to use JWT Authentication
    var jwtSecurityScheme = new OpenApiSecurityScheme
        {
            Scheme = "bearer",
            BearerFormat = "JWT",
            Name = "JWT Authentication",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.Http,
            Description = "Put **_ONLY_** your JWT Bearer token on textbox below!",
            Reference = new OpenApiReference
         {
            Id = JwtBearerDefaults.AuthenticationScheme,
            Type = ReferenceType.SecurityScheme
         }
        };
     c.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);
     c.AddSecurityRequirement(new OpenApiSecurityRequirement {
        { jwtSecurityScheme, Array.Empty<string>() }
     });
});

Now you can see the Authorize button on the top right corner of Swagger UI.

Now you can use [Authorize] attribute by clicking on the Authorize button and give the JWT Token which is already described in this given blog

How to Secure API using JWT Tokens. Building CRUD API using JWT Tokens with ASP.NET Core and Entity Framework Core and Swagger

 

 

Leave a Reply