7

I am using Swagger to test my APIs in the Asp.Net Core application. I am sending the request using by entering the token like this Authorization: Bearer {token}. but the Authorization header is not being sent in requests.

Asp.Net Core version 3.1 and Swashbuckle.AspNetCore 5.4.1

Startup.cs Code:

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
    }
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197

2 Answers2

6

The culprit

Configuration looks fine. It seems that the auth name you defined is the possible culprit.

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

You must use the definition name as "oauth2" unless you manually pass the securitySchemaName into the constructor. As a matter of fact the SecurityRequirementsOperationFilter uses the standard name by default. Just look at the securitySchemaName's default value.

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

It works fine in my environment. Please try with this configuration and please don't forget to add the filter option.

hina10531
  • 3,938
  • 4
  • 40
  • 59
0

You need to manually add Authorisation header in Swagger UI. The API config needs to include the BearerAuth schema for the endpoints as described in the specification https://swagger.io/docs/specification/authentication/.

OpenAPI uses the term security scheme for authentication and authorization schemes. OpenAPI 3.0 lets you describe APIs protected using the following security schemes: HTTP authentication schemes (they use the Authorization header), API keys in headers, query string or cookies Cookie authentication, OAuth 2, OpenID Connect Discovery

This is done with AddSecurityDefinition, but you are missing AddSecurityRequirement which says it's a requirement for the endpoints and it renders in the UI as it's described in this answer. Also here is an option to automatically add the header.

fsacer
  • 1,382
  • 1
  • 15
  • 23
  • I have added this code but still not autorization header not being sent options.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List() } }); – Vivek Nuna May 29 '20 at 13:52
  • maybe try the automatic version? this question should help out https://stackoverflow.com/questions/38784537/use-jwt-authorization-bearer-in-swagger-in-asp-net-core/47709074. – fsacer May 29 '20 at 14:02