Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 26 additions & 21 deletions src/Extensions/SwaggerExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,45 @@
using Microsoft.OpenApi.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Playtesters.API.Extensions;

public static class SwaggerExtensions
{
public static IServiceCollection AddSwaggerWithApiKey(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
services.AddSwaggerGen(options =>
{
c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
options.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
{
Description = "API Key needed to access the endpoints. X-Api-Key: Your_API_Key",
In = ParameterLocation.Header,
Name = "X-Api-Key",
Type = SecuritySchemeType.ApiKey,
Scheme = "ApiKeyScheme"
In = ParameterLocation.Header,
Description = "API key required to access protected endpoints."
});

c.AddSecurityRequirement(new OpenApiSecurityRequirement
options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "ApiKey"
},
Scheme = "ApiKeyScheme",
Name = "X-Api-Key",
In = ParameterLocation.Header
},
[]
}
[new OpenApiSecuritySchemeReference("ApiKey", document)] = []
});

options.OperationFilter<ApiKeySecurityOperationFilter>();
});
return services;
}

public class ApiKeySecurityOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
bool isAnonymous = context.ApiDescription.ActionDescriptor.EndpointMetadata
.OfType<AllowAnonymousAttribute>()
.Any();

if (isAnonymous)
{
operation.Security = [];
}
}
}
}
4 changes: 2 additions & 2 deletions src/Playtesters.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.22" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.3" />
<PackageReference Include="DotEnv.Core" Version="3.1.1" />
<PackageReference Include="SimpleResults" Version="4.0.0" />
<PackageReference Include="SimpleResults.AspNetCore" Version="4.0.0" />
Expand Down
Loading