heldersepu / Swagger-Net

Seamlessly adds a swagger to WebApi projects!
BSD 3-Clause "New" or "Revised" License
144 stars 42 forks source link

apiKey is not included in headers when set in UI #107

Closed spikernum1 closed 3 years ago

spikernum1 commented 3 years ago

Reproduction Steps:

Swagger initialization code:

public static void Register(HttpConfiguration config)
        {
            config
                .EnableSwagger(c => { 
                    c.SingleApiVersion("v1", "My.WebApi");
                    c.PrettyPrint();
                    c.ApiKey("X-API-KEY", "header", "API Key Authentication");
                    c.IncludeXmlComments(XmlCommentsFilePath);
                })
                .EnableSwaggerUi();
        }

The X-API-KEY is initialized properly, since if I change the name to apiKey or anything else, it is reflected in the "Authorize" popup.

The problem is that any of the "Try It Out" requests don't actually read from the values that are saved.

spikernum1 commented 3 years ago

I should also mention that even if I change it to "query" instead of "header", it reflects it properly when clicking the Authorize button, but when using "Try It Out" it does not include it in the query string.

spikernum1 commented 3 years ago

I found that the "type" defaults to AuthorizeAttribute, so unless your authorization implementation uses that type you will have to override it.

I was attempting to use my own custom attribute:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public class ApiKeyAuth : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        IEnumerable<string> apiKeyArr;
        actionContext.Request.Headers.TryGetValues("X-API-KEY", out  #apiKeyArr);
        var apiKey = apiKeyArr?.First();

        if (apiKey != "test")
        {
            return false;
        }

        return true;
    }

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        actionContext.Response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.Unauthorized,
            Content = new StringContent("Invalid API Key")
        };
    }

}

so i had to change my swagger registration to use:

config
                .EnableSwagger(c => { 
                    c.SingleApiVersion("v1", "My.WebApi");
                    c.PrettyPrint();
                    c.ApiKey("X-API-KEY", "header", "API Key Authentication", typeof(ApiKeyAuth)); //i had to add my type here
                    c.IncludeXmlComments(XmlCommentsFilePath);
                })
                .EnableSwaggerUi();