ChatGPT解决这个技术问题 Extra ChatGPT

Setting up Swagger (ASP.NET Core) using the Authorization headers (Bearer)

I have a Web API (ASP.NET Core) and I am trying to adjust the swagger to make the calls from it. The calls must contains the Authorization header and I am using Bearer authentication. The calls from third party apps like Postman, etc. go fine. But I am having the issue with setting up the headers for swagger (for some reason I don't receive the headers). This is how it looks like now:

  "host": "localhost:50352",
  "basePath": "/" ,
  "schemes": [
    "http",
    "https"
  ],
 "securityDefinitions":  {
    "Bearer": {
      "name": "Authorization",
      "in": "header",
      "type": "apiKey",
      "description": "HTTP/HTTPS Bearer"
    }
  },
  "paths": { 
    "/v1/{subAccountId}/test1": {
      "post": {
        "tags": [
          "auth"
        ],
        "operationId": "op1",
        "consumes": ["application/json", "application/html"],
        "produces": ["application/json", "application/html"],
        "parameters": [
          {
            "name": "subAccountId",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "security":[{
          "Bearer": []
        }],
        "responses": {
          "204": {
            "description": "No Content"
          },
          "400": {
            "description": "BadRequest",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          },
          "401": {
            "description": "Unauthorized",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          },
          "500": {
            "description": "InternalServerError",
            "schema": {
              "$ref": "#/definitions/ErrorResponse"
            }
          }
        },
        "deprecated": false
      }
    },

J
Jesse

ApiKeyScheme was deprecated, in version 5 you can use like this:

services.AddSwaggerGen(c =>
  {
    c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
      {
        Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n 
                      Enter 'Bearer' [space] and then your token in the text input below.
                      \r\n\r\nExample: 'Bearer 12345abcdef'",
         Name = "Authorization",
         In = ParameterLocation.Header,
         Type = SecuritySchemeType.ApiKey,
         Scheme = "Bearer"
       });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
      {
        {
          new OpenApiSecurityScheme
          {
            Reference = new OpenApiReference
              {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
              },
              Scheme = "oauth2",
              Name = "Bearer",
              In = ParameterLocation.Header,

            },
            new List<string>()
          }
        });
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

Can confirm this is working like a charm for .NET Core 3.0 - the code I wrote when using .NET Core 2.2 no longer worked after the upgrade and this is what I needed
Minor points: i) I needed to use
instead of \r\n for the message to display correctly. ii) instead of new Info { ... I needed new OpenApiInfo {Title ... . [using swashbuckle.aspnetcore 5.0.0 and Microsoft.OpenApi 1.1.4 [.net core 3.1]]
What about: 1. AllowAnonymous 2. Roles?
This works for me but the description "\r\n" part is not working...
@Ben It gets turned into HTML so you can use
instead of "\r\n"
A
Ashish Kamble

First of all, you can use Swashbuckle.AspNetCore nuget package for auto generating your swagger definition. (tested on 2.3.0)

After you've installed package, setup it in Startup.cs in method ConfigureServices

services.AddSwaggerGen(c => {
    c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
    c.AddSecurityDefinition("Bearer",
        new ApiKeyScheme { In = "header",
          Description = "Please enter into field the word 'Bearer' following by space and JWT", 
          Name = "Authorization", Type = "apiKey" });
    c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
        { "Bearer", Enumerable.Empty<string>() },
    });

});

Then you can use Authorize button at the top right of the page.

At least you can try to use this package to generate valid swagger definition


Good answer but when I do that with ABP boilerplate, it doesn't work with Dynamic Web Api (aspnetboilerplate.com/Pages/Documents/Dynamic-Web-API)
@VadimK That worked perfectly until I upgraded to .NET Core 2.0
In the case this helps, in the Auth box , in the value input you have to put exactly the Auth header not only the JWT (in the case you are using it). This means : Bearer your_token_jwt
Make sure you prefix you token with "Bearer". I was not using Bearer your_token_jwt
And what they did for: 1. AllowAnonymous 2. Roles?
I
Igor

TIP!

To avoid always write the keyword Bearer on the Swagger(a.k.a Swashbuckle) auth dialog, like: "bearer xT1...", you can use the code/config below on ConfigureServices(...) method at your Startup class:

using Microsoft.OpenApi.Models;
...


services.AddSwaggerGen(setup =>
{
    // 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
        }
    };

    setup.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme);

    setup.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        { jwtSecurityScheme, Array.Empty<string>() }
    });

});

We can make this, only by changing the Type property of the OpenApiSecurityScheme class to:

Type = SecuritySchemeType.Http

instead

Type = SecuritySchemeType.ApiKey.

https://i.stack.imgur.com/88nJd.png

https://i.stack.imgur.com/EjHEY.png

Packages:

Swashbuckle.AspNetCore(5.6.3)
Swashbuckle.AspNetCore.SwaggerUI(5.6.3)

I'am using .NET Core 3.1, and hope this helps!


Many Thanks for posting the tip. I was looking for a way to avoid typing bearer in swagger and this helped.
Thanks! This worked for me & displayed the authorize button in Swagger UI.
Thanks, worked. Nice and easy
J
João Ignacio

Using ASP.Net Core 3.1, here's what worked for me:

services.AddSwaggerGen(s =>
        {
            s.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "Chat API",
                Description = "Chat API Swagger Surface",
                Contact = new OpenApiContact
                {
                    Name = "João Victor Ignacio",
                    Email = "ignaciojvig@gmail.com",
                    Url = new Uri("https://www.linkedin.com/in/ignaciojv/")
                },
                License = new OpenApiLicense
                {
                    Name = "MIT",
                    Url = new Uri("https://github.com/ignaciojvig/ChatAPI/blob/master/LICENSE")
                }

            });

            s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
            {
                Description = "JWT Authorization header using the Bearer scheme (Example: 'Bearer 12345abcdef')",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey,
                Scheme = "Bearer"
            });

            s.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        }
                    },
                    Array.Empty<string>()
                }
            });

        });

c
cdev

There is no need to generate token separate and key in swagger. Swagger support generation part too. Below work for me with asp.net core 3.1 and keycloack auth.

swagger.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme
{
    Type = SecuritySchemeType.OAuth2,
    Flows = new OpenApiOAuthFlows
    {
        Implicit = new OpenApiOAuthFlow
        {
            AuthorizationUrl = new Uri("https://youauthsrv.com/auth/realms/your-realm/protocol/openid-connect/auth"),
        }
    },
    In = ParameterLocation.Header,
    Scheme = JwtBearerDefaults.AuthenticationScheme,
});

swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = JwtBearerDefaults.AuthenticationScheme
            }
        },
        new string[] {}
    }
});

in Configure

app.UseSwaggerUI(c =>
{
    c.OAuthClientId("clientname");
    c.OAuthRealm("your-realm");
});

P
Pavel K.

Currently Swagger has functionality for authentication with JWT-token and can automatically add token into header, I have answered here.