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

如何从已注册Azure AD的.NET 6应用访问受Azure AD保护的WCF服务

服务端(.NET Framework 4.8 WCF)前置配置校验

首先确认WCF服务端已经适配Azure AD Bearer令牌校验,跳过WCF原生认证逻辑,将鉴权交给OWIN中间件处理:

  • 安装NuGet包Microsoft.Owin.Security.ActiveDirectory,在Startup.cs中配置Azure AD JWT校验:
public void Configuration(IAppBuilder app)
{
    app.UseWindowsAzureActiveDirectoryBearerAuthentication(
        new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        {
            Tenant = "<你的Azure AD租户ID>",
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidAudience = "<WCF服务端的应用ID URI,格式一般为api://<服务端应用客户端ID>>"
            }
        });
}
  • 修改Web.config中WCF的basicHttpBinding配置,关闭原生认证,适配HTTPS传输:
<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding name="AzureAdCompatibleBinding">
        <security mode="Transport"> <!-- 生产环境必须用HTTPS,测试用HTTP的话改为None -->
          <transport clientCredentialType="None" />
        </security>
      </binding>
    </basicHttpBinding>
  </bindings>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <!-- 关闭WCF原生权限校验,交由OWIN中间件处理 -->
        <serviceAuthorization principalPermissionMode="None" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>
  • 确认WCF服务所在Web应用的Web.config已经开启OWIN自动启动,没有配置禁止认证拦截的规则。

客户端(.NET 6 Web应用)配置与调用流程

不需要配置WCF原生的ClientCredentials参数,直接将Azure AD令牌注入到HTTP请求头即可,具体步骤如下:

  1. 安装必要NuGet包:
    Microsoft.Identity.Client(用于获取Azure AD访问令牌)、System.ServiceModel.Http(WCF客户端基础依赖)
  2. 从Azure AD获取WCF服务的访问令牌:
// 配置参数
var tenantId = "<Azure AD租户ID>";
var clientAppId = "<.NET 6应用的客户端ID>";
var clientAppSecret = "<.NET 6应用的客户端密钥>";
var wcfServiceScope = "api://<WCF服务端应用的ID URI>/.default";

// 初始化MSAL客户端获取令牌
var msalClient = ConfidentialClientApplicationBuilder
    .Create(clientAppId)
    .WithClientSecret(clientAppSecret)
    .WithAuthority($"https://login.microsoftonline.com/{tenantId}")
    .Build();
var tokenResult = await msalClient.AcquireTokenForClient(new[] { wcfServiceScope }).ExecuteAsync();
var accessToken = tokenResult.AccessToken;
  1. 初始化WCF客户端并注入Bearer令牌调用接口:
// 配置绑定和客户端
var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); // 测试用HTTP的话改为BasicHttpSecurityMode.None
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
var endpoint = new EndpointAddress("<WCF服务的完整HTTPS地址>");
var wcfClient = new 你生成的WCF客户端类名(binding, endpoint);

// 调用接口时注入Authorization头
using (var scope = new OperationContextScope(wcfClient.InnerChannel))
{
    var requestProperty = new HttpRequestMessageProperty();
    requestProperty.Headers["Authorization"] = $"Bearer {accessToken}";
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
    
    // 执行WCF接口调用
    var result = await wcfClient.你的接口方法名(参数);
}

如果需要统一为所有WCF调用添加令牌,可以实现IClientMessageInspector拦截器,在请求发送前自动注入头,无需每次调用重复编写注入逻辑。


常见问题排查

  • 确认Azure AD中.NET 6客户端应用已经被授予WCF服务端暴露的API权限,且管理员已经完成同意授权
  • 401报错时可以将令牌复制到JWT解析工具,校验aud(受众)、iss(签发者)、权限声明是否和服务端配置匹配
  • 生产环境必须使用HTTPS传输,禁止明文传递Bearer令牌

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:54:04