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

前端 未结 2 892
太阳男子
太阳男子 2020-11-30 22:53

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 authe

相关标签:
2条回答
  • 2020-11-30 23:26

    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

    0 讨论(0)
  • 2020-11-30 23:33

    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);
    });
    
    0 讨论(0)
提交回复
热议问题