【问题标题】:Using Windows Role authentication in the App.config with WCF在带有 WCF 的 App.config 中使用 Windows 角色身份验证
【发布时间】:2026-01-18 19:15:01
【问题描述】:

我正在使用 WCF 服务和 net.tcp 端点,并将 serviceAuthentication 的主体 PermissionMode 设置为 UseWindowsGroups。

目前在服务的实现中,我使用 PrincipalPermission 属性来设置每个方法的角色要求。

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
        [OperationBehavior(Impersonation = ImpersonationOption.Required)]
        public string method1()

我正在尝试做几乎完全相同的事情,除了在 app.config 中设置角色的配置。有什么方法可以做到这一点并且仍然使用 Windows 组身份验证?

谢谢

【问题讨论】:

    标签: wcf app-config windows-authentication


    【解决方案1】:

    如果您在 IIS 中托管 WCF 服务,它将在 ASP.NET 工作进程中运行,这意味着您可以像使用 ASMX Web 服务一样配置身份验证和授权:

    <system.Web>
        <authentication mode="Windows"/>
        <authorization>
            <allow roles=".\Administrators"/>
            <deny users="*"/>
        </authorization>
    </system.Web>
    

    然后,您必须在 IIS 中禁用对您的端点的匿名访问,而改为启用 Windows 集成身份验证
    在 IIS 管理控制台中,您可以通过调出 '您的虚拟目录的“属性”对话框。然后,您将在“目录安全”选项卡中找到安全设置。

    当然,唯一可用的通信渠道是 HTTP。客户端必须在传输级别的请求中提供其 Windows 身份,并使用以下设置:

    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WindowsSecurity">
                    <security mode="Transport">
                        <transport clientCredentialType="Windows" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://localhost/myservice"
                      binding="wsHttpBinding"
                      bindingConfiguration="WindowsSecurity"
                      contract="IMyService" />
         </client>
    </system.serviceModel>
    

    请注意,如果您的服务端点使用 wsHttpBinding,那么您还必须将 SSL 添加到您的端点,因为这是 WCF 在您使用传输级安全性时强制执行的要求。
    如果您改为使用 basicHttpBinding,则可以使用 WCF 中提供的 不太安全 身份验证模式,称为 TransportCredentialOnly,其中 SSL 不支持需要更长的时间。

    如需更多详细信息,here 很好地概述了 WCF 中的安全基础结构。

    【讨论】:

    • 请注意,如果您想这样做,您需要在您的 web.config 文件中启用 ASP.NET 兼容模式。否则它就不会工作(也不会抛出错误)。
    • 注意:要使此功能起作用,system.web/roleManager/@enabled 必须为 false 或省略,否则角色将是 IIS .Net 角色,而不是 Windows 组。
    【解决方案2】:

    Lars Wilhelmsen 已针对此问题发布了解决方案。看一下 http://www.larswilhelmsen.com/2008/12/17/configurable-principalpermission-attribute/

    【讨论】:

    【解决方案3】:

    如果我理解得很好,您想在运行时选择角色。这可以通过 WCF 操作中的permission 需求来完成。例如

    public string method1()
    {
        PrincipalPermission p = new PrincipalPermission(null, "Administrators");
        p.Demand();
        ...
    

    【讨论】: