Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwaggerUI with .NetCore 3.0 bearer token authorization

I'm trying to add authorization header into SwaggerUI api test. below is my Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
       
        services.AddControllers();
        services.Configure<ApiBehaviorOptions>(options =>
        {
            options.SuppressModelStateInvalidFilter = true;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "API",
                Description = "QPIN API with ASP.NET Core 3.0",
                Contact = new OpenApiContact()
                {
                    Name = "Tafsir Dadeh Zarrin",
                    Url = new Uri("http://www.tdz.co.ir")
                }
            });
            var securitySchema = new OpenApiSecurityScheme
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            };
            c.AddSecurityDefinition("Bearer", securitySchema);
            
            var securityRequirement = new OpenApiSecurityRequirement();
            securityRequirement.Add(securitySchema, new[] { "Bearer" });
            c.AddSecurityRequirement(securityRequirement);
            
        });
    }

    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
    {
        app.UseCors("Cors");


        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMiddleware<ApiResponseMiddleware>();
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();


        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

    }

The Authorize button has been added to the Swagger UI and I've entered the required access token as shown below

authorize swaggerUI

but the issue is when I want to try an API the token is not getting added into API request, and when I click the lock icon over the API it shows that there isn't any available authorization, see below

enter image description here

like image 293
VahiD Avatar asked Oct 02 '19 07:10

VahiD


People also ask

How do I add Authorization in swagger UI net core?

Create an ASP.NET Core Web API project in Visual Studio 2022 Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project.

How do you send Authorization header with request in swagger UI?

After add settings, then run this project, you can find an Authorization button swagger page, and you can use it to set the authorization header. Show activity on this post. then in SwaggerUIBundle constructor: const ui = SwaggerUIBundle({ ..., requestInterceptor: function (req) { req.

How do I use swagger UI authentication token?

To USE the access token in the Swagger Docs UI, copy the access token from the response, and paste it into the access token field at the top of the page. Click the oauth2access_token operation located at the top of the list.


1 Answers

There are two points in your code:

  1. For OpenApiSecurityRequirement in OpenApiSecurityRequirement, need to set OpenApiReference
  2. Need to specify Scheme with bearer

Here is a working demo:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "API",
        Description = "QPIN API with ASP.NET Core 3.0",
        Contact = new OpenApiContact()
        {
            Name = "Tafsir Dadeh Zarrin",
            Url = new Uri("http://www.tdz.co.ir")
        }
    });
    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();
    securityRequirement.Add(securitySchema, new[] { "Bearer" });
    c.AddSecurityRequirement(securityRequirement);
});
like image 132
Edward Avatar answered Oct 11 '22 15:10

Edward