首页 > 解决方案 > 如何将不记名授权标头附加到招摇请求。Swashbuckle v 5.0.0-rc2

问题描述

我无法获取输入到 swagger UI 以附加到发送的请求的不记名授权标头。我在 UI 上有授权选项,但它基本上什么都不做

我已经浏览并查看了一堆教程,但似乎大摇大摆可能已经改变了他们附加标题的方式,所以我很挣扎。我相当有信心我需要使用“AddSecurityRequirement()”函数,但我知道如何创建正确的对象来传递给它。

services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Message Service", Version = "v1" });

        var security = new Dictionary<string, IEnumerable<string>>
        {
            { "Bearer", new string[] { } },
        };

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

        // Im not sure how to get the token to apply to the header being called. It will get the token, but it doesnt apply it to the request

       c.AddSecurityRequirement(/*What goes here???? I tried passing security object above but no dice.*/);

       var xmlDocFile = Path.Combine(AppContext.BaseDirectory, "MessageService.xml");
       if (File.Exists(xmlDocFile))
       {
           var comments = new XPathDocument(xmlDocFile);
           c.OperationFilter<XmlCommentsOperationFilter>(comments);
           c.SchemaFilter<XmlCommentsSchemaFilter>(comments);
       }
   });

我希望标头附加到请求,但它没有附加,所以我从我的 api 得到一个 401。

标签: c#.net-coreswaggerswagger-ui

解决方案


要添加安全要求,您通常需要传入一个新OpenApiSecurityRequirement实例。鉴于您当前的设置,以下可能满足您的要求。

c.AddSecurityRequirement(new OpenApiSecurityRequirement 
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference 
            {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
            }
        },
        new string[] {}
    }
});

推荐阅读