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

求助:Azure Functions V3中Swagger UI与Azure AD的代码集成实现

集成Azure AD与Swagger UI到Azure Functions V3

我来帮你搞定Azure AD和Swagger在Azure Functions V3里的集成,其实核心就是让Swagger UI支持Azure AD的OAuth2授权流程,这样你在Swagger里就能直接登录调用接口了。下面是一步步的具体操作:

1. 确认必要的NuGet包

首先确保你的项目已经安装了SwashBuckle.AspNetCore.Functions包(建议用最新稳定版),这个包是Azure Functions专用的SwashBuckle实现。如果还没安装,可以通过NuGet包管理器或者命令行安装:

Install-Package SwashBuckle.AspNetCore.Functions

2. 更新Startup中的Swagger配置

你现有的Swagger配置需要扩展,添加Azure AD OAuth2的安全定义、安全要求,以及Swagger UI的授权设置。修改你的代码如下:

using Microsoft.OpenApi.Models;
using System.Reflection;

builder.AddSwashBuckle(Assembly.GetExecutingAssembly(), opts => 
{ 
    opts.SpecVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0; 
    opts.Title = "Platform Data Operations";

    // 替换成你的Azure AD租户ID和应用注册客户端ID
    string tenantId = "your-azure-ad-tenant-id";
    string clientId = "your-app-registration-client-id";
    string apiScope = $"api://{clientId}/access_as_user"; // 替换成你定义的API范围

    // 1. 添加Azure AD OAuth2安全定义
    opts.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            AuthorizationCode = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize"),
                TokenUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"),
                Scopes = new Dictionary<string, string>
                {
                    { apiScope, "Access Platform Data Operations API as user" }
                }
            }
        }
    });

    // 2. 添加全局安全要求,让所有接口默认需要OAuth2授权
    opts.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference 
                { 
                    Type = ReferenceType.SecurityScheme, 
                    Id = "oauth2" 
                }
            },
            new[] { apiScope }
        }
    });

    // 3. 配置Swagger UI的OAuth2参数
    opts.SwaggerUiOptions.OAuthClientId = clientId;
    opts.SwaggerUiOptions.OAuthAppName = "Platform Data Operations API";
    opts.SwaggerUiOptions.OAuthUsePkce = true; // 推荐启用PKCE增强安全性
});

关键参数说明:

  • tenantId: 你的Azure AD租户ID,可以在Azure门户的Azure Active Directory -> 概述里找到。
  • clientId: 你在Azure门户注册的应用程序的客户端ID,在应用注册的概述页面获取。
  • apiScope: 这个是你在应用注册的“公开API”选项卡中定义的API范围,格式一般是api://{clientId}/{scope-name},确保和你配置的权限一致。

3. 配置Azure AD应用注册的重定向URI

Swagger UI在授权完成后需要回调地址,你需要把这个地址添加到Azure AD应用注册的重定向URI中:

  • 生产环境: https://<your-function-app-name>.azurewebsites.net/swagger/oauth2-redirect.html
  • 本地调试: http://localhost:<your-local-port>/swagger/oauth2-redirect.html

添加时注意选择**单页应用(SPA)**类型(因为Swagger UI是SPA应用),保存配置。

4. 测试集成效果

启动你的Azure Functions应用:

  1. 打开Swagger UI页面(生产环境是https://<your-function-app-name>.azurewebsites.net/swagger,本地是http://localhost:<port>/swagger)。
  2. 点击页面右上角的Authorize按钮,勾选你定义的API范围,然后点击Authorize。
  3. 会跳转到Azure AD的登录页面,登录成功后会自动回到Swagger UI,此时你就可以调用带有[Authorize]属性的接口了。

如果你的HTTP触发器需要认证,记得给函数添加[Authorize]属性,Swagger会自动识别这些接口并显示锁形图标,提示需要授权才能调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:22:49