DEV Community

Ravi Ranjan Pandey
Ravi Ranjan Pandey

Posted on

Configure Authorization in OpenAPI(Swagger UI) for JWT in ASP.Net Core Web Api

OpenAPI Specifications are popular choices for REST Api documentation and Swagger UI is interactive API documentation in ASP.Net Webapi.

Authorization needs to be configured for Swagger UI to bear Json Web Tokens(JWT) in the authorized APIs.

Here's how you can add security schema in the dependency container.


public void ConfigureServiceExtensions(IServiceCollection services, IConfiguration configuration)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyProject", Version = "v1.0.0" });

                var securitySchema = new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer",
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                };

                c.AddSecurityDefinition("Bearer", securitySchema);

                var securityRequirement = new OpenApiSecurityRequirement
                {
                    { securitySchema, new[] { "Bearer" } }
                };

                c.AddSecurityRequirement(securityRequirement);

            });
        }

Enter fullscreen mode Exit fullscreen mode

Top comments (0)