Empty authorization header on requests for Swashbuckle.AspNetCore

前端 未结 2 476
无人共我
无人共我 2021-01-28 18:24

Currently having an issue with authorization headers in swashbuckle for .net core The first line of code on every endpoint is:

string auth = Request.Headers[\"Au         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-28 18:42

    The problem here is that the name in your security definition ("Bearer") does not match the name added to your security requirement ("Authorization"). For background context, there used to be a bug in SwashBuckle that meant that it enforced authorization without the SecurityRequirement defined so many found that it suddenly stopped working for them. The Requirement definition is a bit clunky and leads to issues like these.

    If you change the SecurityRequirement to match the code below it should work:

     services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = "Employee Navigator",
                Description = "Authorization Key: Z29vZEtleQ==",
            });
            c.AddSecurityDefinition("Bearer", new ApiKeyScheme
            {
                Name = "Authorization",
                In = "header",
                Type = "apiKey",
                Description = "Authorization Key: Z29vZEtleQ=="
            });
            c.AddSecurityRequirement(new Dictionary>
            {
                { "Bearer", new[] { "readAccess", "writeAccess" } }
            });
    
        });
    

提交回复
热议问题