You'll have to create an IOperationFilter
to only add the OpenApiSecurityScheme
to certain endpoints. How this can be done is described in this blog post (adjusted for .NET Core 3.1, from a comment in the same blog post).
In my case, all endpoints defaults to [Authorize]
if not [AllowAnonymous]
is explicitly added (also described in the linked blog post). I then create the following implementation of IOperationFilter
:
public class SecurityRequirementsOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (!context.MethodInfo.GetCustomAttributes(true).Any(x => x is AllowAnonymousAttribute) &&
!(context.MethodInfo.DeclaringType?.GetCustomAttributes(true).Any(x => x is AllowAnonymousAttribute) ?? false))
{
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "bearer"
}
}, new string[] { }
}
}
};
}
}
}
You'll have to tweak the if statement if you don't default all endpoints to [Authorize]
.
Finally, where I call services.AddSwaggerGen(options => { ... }
(usually in Startup.cs
) I have the following line:
options.OperationFilter<SecurityRequirementsOperationFilter>();
Note that the above line will replace the (presumably) existing call to options.AddSecurityRequirement(...)
in the same place.
Id = "Bearer"
to match my code in Startup.cs:c.AddSecurityDefinition("Bearer", ...
– Duer