Appending API Key header from UI automatically

Hi Josef,
I am trying to get my swagger to send the x-api-key in its header, but i cant get it to work.
Do you maybe know how to connect the swagger authentication to this API authentication method?

That qoute is from the following issue that was created on my JOS.ApiKeyAuthentication repository and since I actually know the answer (since I've done it before), I decided to blog about it.

I've actually done this in a few different projects, and it's pretty straightforward. I decided to implement this in JOS.ApiKeyAuthentication so if you just want to see the code, go to this commit.

As you can see in the GitHub issue, Gijs was on the right track, he just forgot to add the SecurityRequirement.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "JOS.ApiKeyAuthentication", Version = "v1" });

    c.AddSecurityDefinition(ApiKeyConstants.HeaderName, new OpenApiSecurityScheme
    {
        Description = "Api key needed to access the endpoints. X-Api-Key: My_API_Key",
        In = ParameterLocation.Header,
        Name = ApiKeyConstants.HeaderName,
        Type = SecuritySchemeType.ApiKey
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        { 
            new OpenApiSecurityScheme 
            {
                Name = ApiKeyConstants.HeaderName,
                Type = SecuritySchemeType.ApiKey,
                In = ParameterLocation.Header,
                Reference = new OpenApiReference
                { 
                    Type = ReferenceType.SecurityScheme,
                    Id = ApiKeyConstants.HeaderName
                },
             },
             new string[] {}
         }
    });
});

That's it!
Click on Authorize, enter your API Key and you should be good to go!

One thing to note.
The first endpoint, /api/user/anyone, by looking at the UI, it seems like you need to be authenticated/authorized to call it because of the lock? That is simply not true since the action method does not have any Authorize attribute specified. It seems to be a hot potato in the Swagger community and I have currently not found a solution to this problem...maybe in the next blog post? :)