c# - 在 Asp.Net Core 中使用 Swagger 未在请求中发送授权承载 token

标签 c# asp.net-core swagger swagger-ui swashbuckle

我正在使用 Swagger 在 Asp.Net Core 应用程序中测试我的 API。我通过输入这样的 token 发送请求 Authorization: Bearer {token} .但授权 header 未在请求中发送。

Asp.Net Core 3.1 版和 Swashbuckle.AspNetCore 5.4.1

Startup.cs 代码:

public class Startup
{
    private const string _apiVersion = "v1";
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ClockSkew = TimeSpan.FromMinutes(0),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });


        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "MyProject API",
                Description = "MyProject"
            });
            options.DocInclusionPredicate((docName, description) => true);

            // Define the BearerAuth scheme that's in use
            options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseAuthentication();
        loggerFactory.AddLog4Net();

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

        app.UseRouting();

        app.UseAuthorization();

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

        // Enable middleware to serve generated Swagger as a JSON endpoint
        app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });

        // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
        app.UseSwaggerUI(options =>
        {
            // specifying the Swagger JSON endpoint.
            options.SwaggerEndpoint($"/swagger/{_apiVersion}/swagger.json", $"MyProject API {_apiVersion}");
            //options.IndexStream = () => Assembly.GetExecutingAssembly()
            //    .GetManifestResourceStream("MyProject.Web.Host.wwwroot.swagger.ui.index.html");
            options.DisplayRequestDuration(); // Controls the display of the request duration (in milliseconds) for "Try it out" requests.  
        }); // URL: /swagger
    }
}

最佳答案

罪魁祸首

配置看起来不错。您定义的身份验证名称似乎是可能的罪魁祸首。

services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "MyProject API",
            Description = "MyProject"
        });
        options.DocInclusionPredicate((docName, description) => true);


        // options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
                             // "bearerAuth" -> "oauth2"
        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey
        });

        // Add this filter as well.
        options.OperationFilter<SecurityRequirementsOperationFilter>();
    });

您必须使用定义名称作为 "oauth2"除非您手动传递 securitySchemaName进入构造函数。事实上SecurityRequirementsOperationFilter默认使用标准名称。看看 securitySchemaName的默认值。
public SecurityRequirementsOperationFilter(bool includeUnauthorizedAndForbiddenResponses = true, string securitySchemaName = "oauth2")
{
    Func<IEnumerable<AuthorizeAttribute>, IEnumerable<string>> policySelector = (IEnumerable<AuthorizeAttribute> authAttributes) => authAttributes.Where((Func<AuthorizeAttribute, bool>)((AuthorizeAttribute a) => !string.IsNullOrEmpty(a.Policy))).Select((Func<AuthorizeAttribute, string>)((AuthorizeAttribute a) => a.Policy));
    filter = new SecurityRequirementsOperationFilter<AuthorizeAttribute>(policySelector, includeUnauthorizedAndForbiddenResponses, securitySchemaName);
}

它在我的环境中运行良好。请尝试使用此配置,请不要忘记添加过滤器选项。

关于c# - 在 Asp.Net Core 中使用 Swagger 未在请求中发送授权承载 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62087049/

相关文章:

c# - 如何在C#中执行此操作?

docker - 在 Docker 容器中运行的 .Net Core 3 应用程序中缺少 Application Insights 遥测

asp.net - 无法在 helloweb 演示应用程序上运行 k run

swagger - 什么是 Swagger、Swashbuckle 和 Swashbuckle UI

c# - 如何在其他电脑上打包安装Windows 10应用

c# - 嵌入 Windows Media Player 全屏

java - API 描述未显示在 Swagger UI 中

swagger - 我们可以在 OpenAPI/Swagger 2.0 中设置全局 "consumes"和 "produces"吗?

c# - 使用联接时跟踪 LINQ

c# - 使用 asp.net core 进行集成测试(没有 View 的 Controller 测试)