You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Automatically infer OpenApiSecuritySchemes from authentication configuration #39761
Priority:1Work that is critical for the release, but we could probably ship withoutarea-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesenhancementThis issue represents an ask for new feature or an enhancement to an existing onefeature-openapi
At the moment, when users enable authentication in their ASP.NET apps, they typically have to manually the describe the OpenApiSecuritySchemes in their application and the top level and configure OpenApiSecurityRequirements for each route that requires authentication and authorization.
We should infer as much of these definitions as possible so users don't need to configure auth twice, once for their application and another time for OpenAPI.
Reacted by Juliano Leal Goncalves, Tomasz, Niels Pilgaard Grøndahl, Giorgi Chakhidze, Ali Aslan, Constantinos Leftheris, Alexander Wicht, Alex Klaus, Veikko Eeva, Arthur Moore and 26 more
changed the title [-]Security schemes cannot be generated for individual endpoints/actions[/-][+]Generate security schemes for individual endpoints/actions[/+]on Feb 2, 2022
I started experimenting with some of this support in the new Microsoft.AspNetCore.OpenAPI package. The problem is generally easy to solve for cookie and JWT bearer-based authentication types, but OAuth authentication types are a lot trickier for us to derive automatic annotations for because:
We don't store any information about what type of grant flow an OAuth implementation uses
We don't make it easy for authentication scheme providers to describe what authentication type they are
We've had conversations about how to make the authentication system more self-describing for annotation purposes. There's more design scenarios to reason about here but for .NET 7 we're scoping it down to auto-generating annotations for JWT-bearer based types to align with the work we've done with dotnet user-jwts and the options-from-config changes.
Reacted by Martin Costello, Juliano Leal Goncalves and Arthur Moore
If anyone want a workaround to get securityScheme resolution on a per endpoint basics, here is what i personally done:
(Because not all my endpoints required authorization)
There might be a more optimized (or a different) way to do it, but it seems to work.
EDIT (Yes there was a better way haha, i didn´t check far enough to see there was an operation transformer instead):
publicstaticclassOpenApiEndpointsSecuritySchemeResolution{internalsealedclassEndpointsHttpSecuritySchemeResolutionTransformer(IAuthenticationSchemeProviderauthenticationSchemeProvider):IOpenApiOperationTransformer{privatestaticstring?_defaultSchemeName;publicasyncTaskTransformAsync(OpenApiOperationoperation,OpenApiOperationTransformerContextcontext,CancellationTokencancellationToken){varauthorizeAttribute=context.Description.ActionDescriptor.EndpointMetadata.OfType<AuthorizeAttribute>().FirstOrDefault();if(authorizeAttributeisnull)return;vartargetScheme=authorizeAttribute.AuthenticationSchemes?.Split(',').FirstOrDefault();if(string.IsNullOrEmpty(targetScheme)){_defaultSchemeName??=(awaitauthenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync())?.Name??thrownewInvalidOperationException("No default authentication scheme found.");targetScheme=_defaultSchemeName;}operation.Security??=newList<OpenApiSecurityRequirement>(1);operation.Security.Add(newOpenApiSecurityRequirement{[newOpenApiSecurityScheme{Type=SecuritySchemeType.Http,Reference=newOpenApiReference{Type=ReferenceType.SecurityScheme,Id=targetScheme}}]=[]});}}/// <summary>/// Adds the security requirement for operations that have the <see cref="AuthorizeAttribute" /> applied./// </summary>/// <param name="options">The <see cref="OpenApiOptions" /> to add endpoints security scheme resolution to.</param>/// <returns>The same <see cref="OpenApiOptions" /> returned to allow chaining.</returns>publicstaticOpenApiOptionsAddEndpointsHttpSecuritySchemeResolution(thisOpenApiOptionsoptions)=>options.AddOperationTransformer<EndpointsHttpSecuritySchemeResolutionTransformer>();}
Transformers are actually useful. For a first time migrating to minimal api and the new openapi lib, the experience isn´t too bad.
It's still a bit weird not having a proper built-in group tag description support though. (I had to add my own transformers with a WithTag() with a static dictionary)
I am in use of .Net 10 preview and try to get security property generated correctly. I tried my best, but I don't know how to implement it to get it done correctly in my custom OpenApiOperationTransformer.
// No Swashbuckel or other deps, only the followingusingMicrosoft.OpenApi;usingMicrosoft.AspNetCore.OpenApi;// 1. Create security scheme and add to documentvarscheme=newOpenApiSecurityScheme{Type=SecuritySchemeType.ApiKey,Scheme=ApiKeyAuthenticationOptions.SchemeName,In=ParameterLocation.Header,Name=ApiKeyAuthenticationOptions.ApiKeyHeaderName};context.Document.Components??=newOpenApiComponents();context.Document.Components.SecuritySchemes??=newDictionary<string,IOpenApiSecurityScheme>();if(!context.Document.Components.SecuritySchemes.ContainsKey(ApiKeyAuthenticationOptions.SchemeName)){context.Document.Components.SecuritySchemes.Add(ApiKeyAuthenticationOptions.SchemeName,scheme);}// 2. Create the OpenApiReference objectvaropenApiReference=newOpenApiReferenceWithDescription{Type=ReferenceType.SecurityScheme,Id=ApiKeyAuthenticationOptions.SchemeName};varsecuritySchemeReference=newOpenApiSecuritySchemeReference(ApiKeyAuthenticationOptions.SchemeName){Reference=openApiReference};// 3. Create the security requirementvarsecurityRequirement=newOpenApiSecurityRequirement{// Use the securitySchemeReference as the key{securitySchemeReference,newList<string>()}};operation.Security??=newList<OpenApiSecurityRequirement>();operation.Security.Add(securityRequirement);// Solution by @Kuuruma wont compile anymore (old API)[//operation.Security.Add(new OpenApiSecurityRequirement//{// [new OpenApiSecurityScheme// {// Reference = new OpenApiReference// {// Type = ReferenceType.SecurityScheme,// Id = targetScheme// }// }] = []//});](url)
Why isn't this auth stuff generated automatically at all?
Here's a version of this, but for ASP.NET Core 10 preview 6 and Microsoft.OpenApi 2.0.0 (code):
// Configure bearer authentication using a JWTvarscheme=newOpenApiSecurityScheme(){BearerFormat="JSON Web Token",Description="Bearer authentication using a JWT.",Scheme="bearer",Type=SecuritySchemeType.Http,};varreferenceId="Bearer";varreference=newOpenApiSecuritySchemeReference(referenceId,document);document.Components??=new();document.Components.SecuritySchemes??=newDictionary<string,IOpenApiSecurityScheme>();document.Components.SecuritySchemes[referenceId]=scheme;document.Security??=[];document.Security.Add(new(){[reference]=[]});
Why isn't this auth stuff generated automatically at all?
That's what this issue is tracking, but it isn't going to be part of the .NET 10 release: #39761 (comment)
Actually @martincostello , I think a safer approach would be this one, where it does not add the security scheme if it isn't registered, and it DOES NOT add the bearer requirements to all endpoints (.NET 10):
usingMicrosoft.AspNetCore.Authentication;usingMicrosoft.AspNetCore.Authentication.JwtBearer;usingMicrosoft.AspNetCore.OpenApi;usingMicrosoft.OpenApi;publicstaticclassOpenApiBearerSecuritySchemeTransformer{internalsealedclassBearerSecuritySchemeTransformer(IAuthenticationSchemeProviderauthenticationSchemeProvider):IOpenApiDocumentTransformer{publicasyncTaskTransformAsync(OpenApiDocumentdocument,OpenApiDocumentTransformerContextcontext,CancellationTokencancellationToken){varauthenticationSchemes=awaitauthenticationSchemeProvider.GetAllSchemesAsync();if(authenticationSchemes.All(authScheme =>authScheme.Name!="Bearer"))return;document.Components??=newOpenApiComponents();document.Components.SecuritySchemes??=newDictionary<string,IOpenApiSecurityScheme>();document.Components.SecuritySchemes[JwtBearerDefaults.AuthenticationScheme]=newOpenApiSecurityScheme{Type=SecuritySchemeType.Http,Name=JwtBearerDefaults.AuthenticationScheme,Scheme="bearer",In=ParameterLocation.Header,BearerFormat="JSON Web Token",Description="Bearer authentication using a JWT.",};}}/// <summary>/// Adds support for Bearer security schemes in OpenAPI documents./// </summary>/// <param name="options">The <see cref="OpenApiOptions" /> to add Bearer security scheme to.</param>/// <returns>The same <see cref="OpenApiOptions" /> returned to allow chaining.</returns>publicstaticOpenApiOptionsAddBearerSecurityScheme(thisOpenApiOptionsoptions)=>options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();}
I will be providing in another comment the way I add the Security needs per endpoints in a brief moment (updated to .NET 10 too)
And here is how I make each endpoint discover properly their SecuritySchemes (.NET 10):
usingMicrosoft.AspNetCore.Authentication;usingMicrosoft.AspNetCore.Authorization;usingMicrosoft.AspNetCore.OpenApi;usingMicrosoft.OpenApi;publicstaticclassOpenApiEndpointsSecuritySchemeResolutionTransformer{internalsealedclassEndpointsHttpSecuritySchemeResolutionTransformer(IAuthenticationSchemeProviderauthenticationSchemeProvider):IOpenApiOperationTransformer{privatestaticstring?_defaultSchemeName;publicasyncTaskTransformAsync(OpenApiOperationoperation,OpenApiOperationTransformerContextcontext,CancellationTokencancellationToken){varauthorizeAttribute=context.Description.ActionDescriptor.EndpointMetadata.OfType<AuthorizeAttribute>().FirstOrDefault();if(authorizeAttributeisnull)return;vartargetSchemes=authorizeAttribute.AuthenticationSchemes?.Split(',');if(targetSchemesisnull){_defaultSchemeName??=(awaitauthenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync())?.Name;ArgumentException.ThrowIfNullOrWhiteSpace(_defaultSchemeName,"No default authentication scheme found while one was expected.");operation.Security??=newList<OpenApiSecurityRequirement>(1);operation.Security.Add(newOpenApiSecurityRequirement{[newOpenApiSecuritySchemeReference(_defaultSchemeName,context.Document)]=[]});return;}operation.Security??=newList<OpenApiSecurityRequirement>(targetSchemes.Length);foreach(varschemeintargetSchemes.Select(x =>x.Trim())){ArgumentException.ThrowIfNullOrEmpty(scheme,"Encountered an empty authentication scheme while processing AuthorizeAttribute.");operation.Security.Add(newOpenApiSecurityRequirement{[newOpenApiSecuritySchemeReference(scheme,context.Document)]=[]});}}}/// <summary>/// Adds the security requirement for operations that have the <see cref="AuthorizeAttribute" /> applied./// </summary>/// <param name="options">The <see cref="OpenApiOptions" /> to add endpoints security scheme resolution to.</param>/// <returns>The same <see cref="OpenApiOptions" /> returned to allow chaining.</returns>publicstaticOpenApiOptionsAddEndpointsHttpSecuritySchemeResolution(thisOpenApiOptionsoptions)=>options.AddOperationTransformer<EndpointsHttpSecuritySchemeResolutionTransformer>();}
Reacted by Aleksandr Bagatka, Varun Teja, Giorgi Chakhidze and Asttear
When I use the examples of @Kuurama in .NET 10, I just get the following:
security: [
{ }
]
although I would expect something like:
security: [
{ Bearer: [] }
]
Am I missing something?
Did you try to step in the two transformers with a debugger?
Maybe you haven't properly registered the scheme?
(I did check the code I sent against what I use in production, and they are identical (Beside writting JSON as Json in one place, but that's not the issue)
Thanks for the tip.
When I just start my application and request the openapi.json, I do get the correct security thing, but when I do this via an integration test using a WebApplicationFactory, I get a slightly different result. It's fine for now, since I realise that this is also how it was in .NET 9.
When I use the examples of @Kuurama in .NET 10, I just get the following:
security: [
{ }
]
although I would expect something like:
security: [
{ Bearer: [] }
]
Am I missing something?
Did you try to step in the two transformers with a debugger?
Maybe you haven't properly registered the scheme? (I did check the code I sent against what I use in production, and they are identical (Beside writting JSON as Json in one place, but that's not the issue)
I had the very same problem and found you have to provide the doc in the OpenApiSecuritySchemeReference constructor as well to make it work:
I think it would be fair to assume that if no document is provided in the constructor, the document itself should be considered the hostDocument to resolve that reference.
When I use the examples of @Kuurama in .NET 10, I just get the following:
security: [
{ }
]
although I would expect something like:
security: [
{ Bearer: [] }
]
Am I missing something?
Did you try to step in the two transformers with a debugger?
Maybe you haven't properly registered the scheme? (I did check the code I sent against what I use in production, and they are identical (Beside writting JSON as Json in one place, but that's not the issue)
I had the very same problem and found you have to provide the doc in the OpenApiSecuritySchemeReference constructor as well to make it work:
I think it would be fair to assume that if no document is provided in the constructor, the document itself should be considered the hostDocument to resolve that reference.
Huum, no issues with my template correct? Because I do reference context.Document in there huum.
As long as you have a security scheme under the same key, it should work (notice the dictionary key "Bearer" - not to be confused with the Scheme!):
TaskSetBearerSecurityScheme(OpenApiDocumentdoc,OpenApiDocumentTransformerContextctx,CancellationTokenct){doc.Components??=newOpenApiComponents();doc.Components.SecuritySchemes??=newDictionary<string,IOpenApiSecurityScheme>();doc.Components.SecuritySchemes.TryAdd("Bearer",newOpenApiSecurityScheme(){Description="JWT Authorization header using the Bearer scheme",Type=SecuritySchemeType.Http,Scheme="bearer",});returnTask.CompletedTask;}
So you will end up with this:
"securitySchemes": {"Bearer": { # <-- this is the id to be referenced"type": "http","description": "JWT Authorization header using the Bearer scheme","scheme": "bearer"}}},"security": [{"Bearer": [ ]}]
Priority:1Work that is critical for the release, but we could probably ship withoutarea-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templatesenhancementThis issue represents an ask for new feature or an enhancement to an existing onefeature-openapi
Activity
[-]Security schemes cannot be generated for individual endpoints/actions[/-][+]Generate security schemes for individual endpoints/actions[/+]captainsafia commentedon Jun 14, 2022
Who knew auth could be so hard? 🤪
I started experimenting with some of this support in the new Microsoft.AspNetCore.OpenAPI package. The problem is generally easy to solve for cookie and JWT bearer-based authentication types, but OAuth authentication types are a lot trickier for us to derive automatic annotations for because:
We've had conversations about how to make the authentication system more self-describing for annotation purposes. There's more design scenarios to reason about here but for .NET 7 we're scoping it down to auto-generating annotations for JWT-bearer based types to align with the work we've done with
dotnet user-jwtsand the options-from-config changes.26 remaining items
Kuurama commentedon Jun 1, 2025
If anyone want a workaround to get securityScheme resolution on a per endpoint basics, here is what i personally done:
(Because not all my endpoints required authorization)
There might be a more optimized (or a different) way to do it, but it seems to work.
EDIT (Yes there was a better way haha, i didn´t check far enough to see there was an operation transformer instead):
Transformers are actually useful. For a first time migrating to minimal api and the new openapi lib, the experience isn´t too bad.
It's still a bit weird not having a proper built-in group tag description support though. (I had to add my own transformers with a WithTag() with a static dictionary)
hoharald commentedon Aug 5, 2025
I am in use of .Net 10 preview and try to get security property generated correctly. I tried my best, but I don't know how to implement it to get it done correctly in my custom
OpenApiOperationTransformer.I followed the documentation, but nothing special on that part related to references.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/customize-openapi?view=aspnetcore-9.0#use-operation-transformers
The security field for the endpoint (path) will always be an array with an empty object...
"security": [ { } ]But expect
instead, the
securitySchemesprop is generated as expectedMy try and error...
Why isn't this auth stuff generated automatically at all?
martincostello commentedon Aug 5, 2025
Here's a version of this, but for ASP.NET Core 10 preview 6 and Microsoft.OpenApi 2.0.0 (code):
That's what this issue is tracking, but it isn't going to be part of the .NET 10 release: #39761 (comment)
Kuurama commentedon Sep 17, 2025
Actually @martincostello , I think a safer approach would be this one, where it does not add the security scheme if it isn't registered, and it DOES NOT add the bearer requirements to all endpoints (.NET 10):
I will be providing in another comment the way I add the Security needs per endpoints in a brief moment (updated to .NET 10 too)
Kuurama commentedon Sep 17, 2025
And here is how I make each endpoint discover properly their SecuritySchemes (.NET 10):
dnperfors commentedon Dec 17, 2025
When I use the examples of @Kuurama in .NET 10, I just get the following:
although I would expect something like:
Am I missing something?
Kuurama commentedon Dec 17, 2025
Did you try to step in the two transformers with a debugger?
Maybe you haven't properly registered the scheme?
(I did check the code I sent against what I use in production, and they are identical (Beside writting JSON as Json in one place, but that's not the issue)
dnperfors commentedon Dec 17, 2025
Thanks for the tip.
When I just start my application and request the openapi.json, I do get the correct security thing, but when I do this via an integration test using a WebApplicationFactory, I get a slightly different result. It's fine for now, since I realise that this is also how it was in .NET 9.
m42jbz commentedon Feb 17, 2026
I had the very same problem and found you have to provide the doc in the OpenApiSecuritySchemeReference constructor as well to make it work:
I think it would be fair to assume that if no document is provided in the constructor, the document itself should be considered the hostDocument to resolve that reference.
Kuurama commentedon Feb 17, 2026
Huum, no issues with my template correct? Because I do reference context.Document in there huum.
m42jbz commentedon Feb 17, 2026
As long as you have a security scheme under the same key, it should work (notice the dictionary key "Bearer" - not to be confused with the Scheme!):
So you will end up with this: