Skip to content

Automatically infer OpenApiSecuritySchemes from authentication configuration #39761

Description

@captainsafia

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.

Provide metadata support for parts of the specification documented in https://swagger.io/docs/specification/authentication/.

Activity

  1. added
    enhancement
    old-area-web-frameworks-do-not-use
    on Jan 25, 2022
  2. added this to the 7.0-preview2 milestone on Jan 25, 2022
  3. changed the title [-]Security schemes cannot be generated for individual endpoints/actions[/-] [+]Generate security schemes for individual endpoints/actions[/+] on Feb 2, 2022
  4. added
    Priority:1
    on Feb 10, 2022
  5. captainsafia commented on Jun 14, 2022

    @captainsafia
    ContributorAuthor

    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 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.

  6. 26 remaining items

  7. Kuurama commented on Jun 1, 2025

    @Kuurama

    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)

    public static OpenApiOptions AddEndpointsSecuritySchemeResolution(this OpenApiOptions options)
        {
            options.AddDocumentTransformer<EndpointsSecuritySchemeResolutionTransformer>();
            return options;
        }
    
        internal sealed class EndpointsSecuritySchemeResolutionTransformer(
            IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer
        {
            public async Task TransformAsync(
                OpenApiDocument document, OpenApiDocumentTransformerContext context,
                CancellationToken cancellationToken)
            {
                var defaultScheme = await authenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync();
    
                foreach (var operation in document.Paths.Values.SelectMany(pathItem => pathItem.Operations.Values))
                {
                    if (!TryGetAuthorizeAttribute(operation, context, out var authorizeAttribute))
                        continue;
    
                    var targetScheme = authorizeAttribute.AuthenticationSchemes;
                    targetScheme ??= defaultScheme?.Name;
    
                    if (targetScheme == null)
                        continue;
    
                    operation.Security.Add(new OpenApiSecurityRequirement
                    {
                        [new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = targetScheme
                            }
                        }] = []
                    });
                }
            }
    
            private static bool TryGetAuthorizeAttribute(
                OpenApiOperation operation,
                OpenApiDocumentTransformerContext context,
                [NotNullWhen(true)] out AuthorizeAttribute? authorizeAttribute)
            {
                if (!operation.Annotations.TryGetValue("x-aspnetcore-id", out var aspNetCoreId))
                {
                    authorizeAttribute = null;
                    return false;
                }
    
                var id = aspNetCoreId as string;
                authorizeAttribute = context.DescriptionGroups
                    .SelectMany(group => group.Items)
                    .Where(endpoint => endpoint.ActionDescriptor.Id == id)
                    .Select(endpoint => endpoint.ActionDescriptor.EndpointMetadata
                        .OfType<AuthorizeAttribute>()
                        .FirstOrDefault())
                    .FirstOrDefault();
    
                return authorizeAttribute != null;
            }
        }
    }

    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):

    public static class OpenApiEndpointsSecuritySchemeResolution
    {
        internal sealed class EndpointsHttpSecuritySchemeResolutionTransformer(
            IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiOperationTransformer
        {
            private static string? _defaultSchemeName;
    
            public async Task TransformAsync(
                OpenApiOperation operation, OpenApiOperationTransformerContext context,
                CancellationToken cancellationToken)
            {
                var authorizeAttribute = context.Description.ActionDescriptor.EndpointMetadata
                    .OfType<AuthorizeAttribute>()
                    .FirstOrDefault();
    
                if (authorizeAttribute is null)
                    return;
    
                var targetScheme = authorizeAttribute.AuthenticationSchemes?.Split(',')
                    .FirstOrDefault();
    
                if (string.IsNullOrEmpty(targetScheme))
                {
                    _defaultSchemeName ??=
                        (await authenticationSchemeProvider
                            .GetDefaultAuthenticateSchemeAsync())?.Name
                        ?? throw new InvalidOperationException(
                            "No default authentication scheme found.");
    
                    targetScheme = _defaultSchemeName;
                }
    
                operation.Security ??= new List<OpenApiSecurityRequirement>(1);
                operation.Security.Add(new OpenApiSecurityRequirement
                {
                    [new OpenApiSecurityScheme
                    {
                        Type = SecuritySchemeType.Http,
                        Reference = new OpenApiReference
                        {
                            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>
        public static OpenApiOptions AddEndpointsHttpSecuritySchemeResolution(this OpenApiOptions options)
            => 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)

  8. hoharald commented on Aug 5, 2025

    @hoharald

    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

    "security": [
          { "ApiKeyScheme": [] }
         ]

    instead, the securitySchemes prop is generated as expected

        "securitySchemes": {
          "ApiKeyScheme": {
            "type": "apiKey",
            "name": "X-Api-Key",
            "in": "header"
          }
        }

    My try and error...

    // No Swashbuckel or other deps, only the following
    
    using Microsoft.OpenApi;
    using Microsoft.AspNetCore.OpenApi;
    
    // 1. Create security scheme and add to document
    var scheme = new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.ApiKey,
        Scheme = ApiKeyAuthenticationOptions.SchemeName,
        In = ParameterLocation.Header,
        Name = ApiKeyAuthenticationOptions.ApiKeyHeaderName
    };
    
    context.Document.Components ??= new OpenApiComponents();
    context.Document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
    
    if (!context.Document.Components.SecuritySchemes.ContainsKey(ApiKeyAuthenticationOptions.SchemeName))
    {
        context.Document.Components.SecuritySchemes.Add(
            ApiKeyAuthenticationOptions.SchemeName,
            scheme);
    }
    
    // 2. Create the OpenApiReference object
    var openApiReference = new OpenApiReferenceWithDescription
    {
        Type = ReferenceType.SecurityScheme,
        Id = ApiKeyAuthenticationOptions.SchemeName
    };
                    
    var securitySchemeReference = new OpenApiSecuritySchemeReference(ApiKeyAuthenticationOptions.SchemeName)
    {
        Reference = openApiReference
    };
    
    // 3. Create the security requirement
    var securityRequirement = new OpenApiSecurityRequirement
    {
        // Use the securitySchemeReference as the key
        { securitySchemeReference, new List<string>() }
    };
    
    operation.Security ??= new List<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?

  9. martincostello commented on Aug 5, 2025

    @martincostello
    Member

    An inline document transformer is also how I went about it: https://github.com/martincostello/aspnetcore-openapi/blob/d87b42a236762ac32d833e6b482500b4d97f118c/src/TodoApp/OpenApi/AspNetCore/AspNetCoreOpenApiEndpoints.cs#L35-L53

    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 JWT
    var scheme = new OpenApiSecurityScheme()
    {
        BearerFormat = "JSON Web Token",
        Description = "Bearer authentication using a JWT.",
        Scheme = "bearer",
        Type = SecuritySchemeType.Http,
    };
    
    
    var referenceId = "Bearer";
    var reference = new OpenApiSecuritySchemeReference(referenceId, document);
    
    document.Components ??= new();
    document.Components.SecuritySchemes ??= new Dictionary<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)

  10. Kuurama commented on Sep 17, 2025

    @Kuurama

    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):

    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.OpenApi;
    using Microsoft.OpenApi;
    
    public static class OpenApiBearerSecuritySchemeTransformer
    {
        internal sealed class BearerSecuritySchemeTransformer(
            IAuthenticationSchemeProvider authenticationSchemeProvider)
            : IOpenApiDocumentTransformer
        {
            public async Task TransformAsync(
                OpenApiDocument document, OpenApiDocumentTransformerContext context,
                CancellationToken cancellationToken)
            {
                var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync();
                if (authenticationSchemes.All(authScheme => authScheme.Name != "Bearer"))
                    return;
    
                document.Components ??= new OpenApiComponents();
                document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
                document.Components.SecuritySchemes[JwtBearerDefaults.AuthenticationScheme] = new OpenApiSecurityScheme
                {
                    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>
        public static OpenApiOptions AddBearerSecurityScheme(this OpenApiOptions options)
            => 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)

  11. Kuurama commented on Sep 17, 2025

    @Kuurama

    And here is how I make each endpoint discover properly their SecuritySchemes (.NET 10):

    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.OpenApi;
    using Microsoft.OpenApi;
    
    public static class OpenApiEndpointsSecuritySchemeResolutionTransformer
    {
        internal sealed class EndpointsHttpSecuritySchemeResolutionTransformer(
            IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiOperationTransformer
        {
            private static string? _defaultSchemeName;
    
            public async Task TransformAsync(
                OpenApiOperation operation,
                OpenApiOperationTransformerContext context,
                CancellationToken cancellationToken)
            {
                var authorizeAttribute = context.Description.ActionDescriptor.EndpointMetadata
                    .OfType<AuthorizeAttribute>()
                    .FirstOrDefault();
    
                if (authorizeAttribute is null)
                    return;
    
                var targetSchemes = authorizeAttribute.AuthenticationSchemes?.Split(',');
                if (targetSchemes is null)
                {
                    _defaultSchemeName ??= (await authenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync())?.Name;
                    ArgumentException.ThrowIfNullOrWhiteSpace(
                        _defaultSchemeName,
                        "No default authentication scheme found while one was expected."
                    );
    
                    operation.Security ??= new List<OpenApiSecurityRequirement>(1);
                    operation.Security.Add(new OpenApiSecurityRequirement
                    {
                        [new OpenApiSecuritySchemeReference(_defaultSchemeName, context.Document)] = []
                    });
    
                    return;
                }
    
                operation.Security ??= new List<OpenApiSecurityRequirement>(targetSchemes.Length);
                foreach (var scheme in targetSchemes.Select(x => x.Trim()))
                {
                    ArgumentException.ThrowIfNullOrEmpty(
                        scheme,
                        "Encountered an empty authentication scheme while processing AuthorizeAttribute."
                    );
                    operation.Security.Add(new OpenApiSecurityRequirement
                    {
                        [new OpenApiSecuritySchemeReference(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>
        public static OpenApiOptions AddEndpointsHttpSecuritySchemeResolution(this OpenApiOptions options)
            => options.AddOperationTransformer<EndpointsHttpSecuritySchemeResolutionTransformer>();
    }
  12. dnperfors commented on Dec 17, 2025

    @dnperfors
    Contributor

    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?

  13. Kuurama commented on Dec 17, 2025

    @Kuurama

    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)

  14. dnperfors commented on Dec 17, 2025

    @dnperfors
    Contributor

    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.

  15. m42jbz commented on Feb 17, 2026

    @m42jbz

    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:

        Task AddBearerSecurityRequirement(OpenApiDocument doc, OpenApiDocumentTransformerContext ctx, CancellationToken ct)
        {
            doc.Security ??= [];
            doc.Security.Add(new OpenApiSecurityRequirement()
            {
                {
                    new OpenApiSecuritySchemeReference("Bearer", doc),
                    []
                }
            });
    
            return Task.CompletedTask;
        }
      "security": [
        {
          "Bearer": [ ]
        }
      ]

    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.

  16. Kuurama commented on Feb 17, 2026

    @Kuurama

    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:

    Task AddBearerSecurityRequirement(OpenApiDocument doc, OpenApiDocumentTransformerContext ctx, CancellationToken ct)
    {
        doc.Security ??= [];
        doc.Security.Add(new OpenApiSecurityRequirement()
        {
            {
                new OpenApiSecuritySchemeReference("Bearer", doc),
                []
            }
        });
    
        return Task.CompletedTask;
    }
    

    "security": [
    {
    "Bearer": [ ]
    }
    ]

    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.

  17. m42jbz commented on Feb 17, 2026

    @m42jbz

    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!):

        Task SetBearerSecurityScheme(OpenApiDocument doc, OpenApiDocumentTransformerContext ctx, CancellationToken ct)
        {
            doc.Components ??= new OpenApiComponents();
            doc.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
            doc.Components.SecuritySchemes.TryAdd("Bearer", new OpenApiSecurityScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme",
                Type = SecuritySchemeType.Http,
                Scheme = "bearer",
            });
    
            return Task.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": [ ]
        }
      ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Priority:1area-minimalarea-mvcenhancementfeature-openapi

    Projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions