Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach bearer authorization header to swagger request. Swashbuckle v 5.0.0-rc2

I am having trouble getting the bearer authorization header that I input into swagger UI to attach to the request that is sent. I have the authorize option on the UI, but it essentially does nothing

I've gone through and looked at a bunch of tutorials, but it seems like swagger may have changed the way that they attach the header, so I am struggling. I am fairly confident I need to use the 'AddSecurityRequirement()' function but I know how to create the correct object to pass to it.

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);
       }
   });

I would expect the header to attach to the request, but it is not attaching, so I am getting a 401 from my api.

like image 655
Andrew Overton Avatar asked Aug 13 '19 20:08

Andrew Overton


1 Answers

For adding the security requirement, you typically need to pass in a new OpenApiSecurityRequirement instance. Given your current setup, the following may satisfy your requirements.

c.AddSecurityRequirement(new OpenApiSecurityRequirement 
{
    {
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference 
            {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
            }
        },
        new string[] {}
    }
});
like image 91
Jonathon Chase Avatar answered Sep 21 '22 21:09

Jonathon Chase