You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8独立进程模型中OpenApiSecurity('bearer_auth')失效求助

解决Azure .NET 8 Functions中OpenApiSecurity装饰器无效及Swagger授权错误的方案

问题根源

你遇到的错误源于两方面:一是OpenApiSecurity装饰器的参数配置存在冲突,二是缺少全局安全方案定义——仅在函数上添加装饰器不足以让Swagger识别Bearer认证类型,必须配合全局配置完成安全定义的注册。

修复步骤

1. 修正函数上的OpenApiSecurity装饰器

移除冗余的SecuritySchemeType.Http参数,直接指定Scheme为Bearer,同时显式声明认证信息的位置,避免Swagger解析歧义:

[OpenApiSecurity("bearer_auth", 
    Scheme = OpenApiSecuritySchemeType.Bearer, 
    BearerFormat = "JWT",
    In = OpenApiSecurityLocation.Header)]

2. 添加全局安全方案定义

根据你的项目模式选择配置方式:

传统Startup类模式

在Startup.cs中注册全局Bearer认证方案:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Configurations;

[assembly: FunctionsStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddOpenApiDocument(config =>
            {
                // 注册Bearer认证方案
                config.AddSecurity("bearer_auth", new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer",
                    BearerFormat = "JWT",
                    Description = "输入JWT令牌,格式为Bearer {token}"
                });

                // 全局应用安全要求
                config.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("bearer_auth"));
            });
        }
    }
}

.NET 8顶级语句模式

在Program.cs中配置:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        services.AddOpenApiDocument(config =>
        {
            config.AddSecurity("bearer_auth", new OpenApiSecurityScheme
            {
                Type = SecuritySchemeType.Http,
                Scheme = "bearer",
                BearerFormat = "JWT",
                Description = "输入JWT令牌,格式为Bearer {token}"
            });
            config.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("bearer_auth"));
        });
    })
    .Build();

host.Run();

3. 验证函数端点的安全配置

确保函数同时添加OpenApiOperation装饰器,明确绑定安全要求:

[FunctionName("ProtectedFunction")]
[OpenApiOperation(OperationId = "ProtectedFunction", Tags = new[] { "Protected" }, Security = new[] { "bearer_auth" })]
[OpenApiSecurity("bearer_auth", Scheme = OpenApiSecuritySchemeType.Bearer, BearerFormat = "JWT", In = OpenApiSecurityLocation.Header)]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(string), Description = "成功响应")]
public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "protected")] HttpRequest req,
    ILogger log)
{
    // 函数逻辑
    return new OkObjectResult("Authenticated access granted");
}

关键注意事项

  • 确保安装适配.NET 8的Microsoft.Azure.WebJobs.Extensions.OpenApi NuGet包
  • 全局安全定义的名称("bearer_auth")必须和函数装饰器中的名称完全一致
  • 避免在OpenApiSecurity中同时指定SecuritySchemeType.Http和Scheme参数,二者重复会导致Swagger解析错误

内容的提问来源于stack exchange,提问作者Gunner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 15:00:10