Swashbuckle.AspNetCore: Authorization Header not being sent from Swagger UI 5.0.0-rc5

Tried both the following solutions:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1022

                    options.AddSecurityDefinition("basicAuth", new OpenApiSecurityScheme
                    {
                        Type = SecuritySchemeType.Http,
                        Scheme = "Basic", // tried lowercase "basic" too.
                        Description = "Input your username and password to access this API",
                        In = ParameterLocation.Header,
                    });

                    options.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference {
                                    Type = ReferenceType.SecurityScheme,
                                    Id = "basicAuth" }
                            }, new List<string>() }
                    });

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1171

                    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        Description = "JWT Authorization header using the Bearer scheme.",
                        Name = "Authorization",
                        In = ParameterLocation.Header,
                        Scheme = "bearer",
                        Type = SecuritySchemeType.Http,
                        BearerFormat = "JWT"
                    });

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

I need basic auth, and I am willing to settle for making the user put the encoded final header in. Ideally, they would be prompted for a username and password and that could automatically be encoded.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 3
  • Comments: 18 (4 by maintainers)

Most upvoted comments

Don’t use parameters to accomplish this as it is no longer supported by Swagger UI. To get the Authorization header included in the curl request you must define it entirely using security schemes. For reference see this comment

Want to share my configuration that works on 5.0.0-rc5:

In Startup.cs, add a global Security Definition and operation filter:

services.AddSwaggerGen(opt =>
{
	opt.SwaggerDoc("v1", new OpenApiInfo { Title = "My Api", Version = "v1" });
	opt.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
	{
		Type = SecuritySchemeType.Http,
		BearerFormat = "JWT",
		In = ParameterLocation.Header,
		Scheme = "bearer"
	});
	opt.OperationFilter<AuthenticationRequirementsOperationFilter>();
});

In the AuthenticationRequirementsOperationFilter add a Security Requirement to the operation by referencing the Security Definition that was added globally:

public class AuthenticationRequirementsOperationFilter : IOperationFilter
{
	public void Apply(OpenApiOperation operation, OperationFilterContext context)
	{
		if (operation.Security == null)
			operation.Security = new List<OpenApiSecurityRequirement>();


		var scheme = new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearer" } };
		operation.Security.Add(new OpenApiSecurityRequirement
		{
			[scheme] = new List<string>()
		});
	}
}

Note:

  • The Id value “bearer” matches what was passed as the first parameter to AddSecurityDefinition in Startup.cs
  • This example adds the security requirement to ALL endpoints. Typically, filtering logic will be included to only add the security requirement to endpoints that need it.

The generated UI won’t have Authorization fields in each endpoint. There should be open locks on the endpoints that had a security requirement added to them in the OperationFilter and an Authorize button should show up on the top right. Add the token to the header using the Authorize button and the endpoints will show with closed locks. Note: “Bearer” will be added automatically, so only provide the token when authorizing.

Screen Shot 2020-01-07 at 11 23 07 PM

Requests should now include the Authorization header with the provided token. You can verify in the curl:

Screen Shot 2020-01-07 at 11 24 51 PM

Hope it helps!

Really need a working example for bearer token.

The options below working with Bearer scheme for me:

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

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

For those who are still having trouble with this, here is the code that worked for me after few hours of trial and error.

services.AddSwaggerGen(c =>
            {                
                c.AddSecurityDefinition("Basic", new OpenApiSecurityScheme
                {
                    Name = "Basic",
                    Description = "Please enter your username and password",
                    Type = SecuritySchemeType.Http,
                    Scheme = "basic", //This is were it was not working for me. I was using uppercase B
                    In = ParameterLocation.Header
                });

`               c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Basic" }
                        }, new List<string>() 
                    }
                });
        }

The following example works for me (including automatic encoding of credentials). It’s worth noting that this type of question is related to understanding the Swagger specification, and how to express certain API behaviors with it, as opposed to Swashbuckle itself. When this is the case, I would encourage people to look at the Swagger documents (e.g. authentication examples) instead as they contain many examples which can be easily ported over to Swashbuckle configuration.

Anyway, here’s a working example for basic Auth (derived from the Swagger docs):

c.AddSecurityDefinition("basicAuth", new OpenApiSecurityScheme
{
    Type = SecuritySchemeType.Http
    Scheme = "basic"
});

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

I’m also experiencing the same issue where the UI is not adding the authorization header.

I’m using token authentication that is applied conditionally based on attrbiutes of my controller, but with very similar code in an IOperationFilter:


               operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Description = "[Your Token]",
                    Required = true,
                    Schema = new OpenApiSchema { Type = "string" },
                });

                operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
                operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });

                operation.Security = new List<OpenApiSecurityRequirement>
                {
                    new OpenApiSecurityRequirement()
                        {
                             {
                                new OpenApiSecurityScheme
                                {
                                    Description = "Adds token to header",
                                    Name = "Authorization",
                                    Type = SecuritySchemeType.Http,
                                    In = ParameterLocation.Header,
                                    Scheme = "bearer",
                                    Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                                },
                                new List<string>()
                            }
                    }
                };

The UI is generated correctly but the header is not added to the request.

using 5.0.0-rc5

I met the same issue before and resolved it.

Now the available Authorization header works fine.

Please check my latest sample using SwashBuckle v5.5.1 and netcore 3.1 https://github.com/capcom923/MySwashBuckleSwaggerWithJwtToken

send-authorization-header

@pnavk Thank’s you led me to the solution which was that I had options.OperationFilter<SecurityRequirementsOperationFilter>() in my startup.cs! This was overriding anything I did thanks to this https://github.com/mattfrear/Swashbuckle.AspNetCore.Filters/blob/master/src/Swashbuckle.AspNetCore.Filters/SecurityRequirementsOperationFilter/SecurityRequirementsOperationFilter.cs#L20

Similar one here: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/test/WebSites/OAuth2Integration/ResourceServer/Swagger/SecurityRequirementsOperationFilter.cs#L27

All I had to do was add the following to my AddSwaggerGen and the problem was solved.

options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
    Type = SecuritySchemeType.Http,
    Scheme = "basic"
});

The key here being "oauth2" since that references the hardcoded OpenApiScheme.OpenApiReference.

Really need a working example for bearer token.

This is working for me under 5.0.0-rc5:

In Startup.cs in ConfigureServices:

services.AddSwaggerGen(options =>
            {
                options.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.Http,
                    BearerFormat = "JWT",
                    In = ParameterLocation.Header,
                    Scheme = "bearer"
                });


                // add auth header for [Authorize] endpoints
                options.OperationFilter<AddAuthHeaderOperationFilter>();
public class AddAuthHeaderOperationFilter : IOperationFilter
    {

        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
               if (operation.Security == null)
                    operation.Security = new List<OpenApiSecurityRequirement>();


                var scheme = new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearer" } };
                operation.Security.Add(new OpenApiSecurityRequirement
                {
                    [scheme] = new List<string>()
                });
        }
    }

NOTE: I filter on

  • controllers that have an [Authorize] attribute
  • do not have [AllowAnonymous] method attributes.

in AddAuthHeaderOperationFilter - code removed for clarity.

@domaindrivendev That did not work.

Click authorize

image

Fill out info and click the authorize button

image

Expand an operation

image

Click “Try it out”

image

Click “Execute”

image

401! And there is no “Authorize” header in the request payload.

image

It’s worth noting that this type of question is related to understanding the Swagger specification, and how to express certain API behaviors with it, as opposed to Swashbuckle itself

But Swashbuckle needs to understand the Swagger body to make use of it in the UI does it not? How else does the UI know to create Auth headers, and encode parameters?