0

我有使用 Windows 身份验证和自定义 ServiceAuthorizationManager 的 WCF Web 服务。一切正常,但如果重写 CheckAccessCore 返回 false,我会收到错误 500,而不是我预期的 401。服务不实现任何服务级别的错误处理。如何发送 401 而不是 500 标头?

服务配置:

    <!-- App configuration-->
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <customErrors mode="Off" />
    </system.web>

    <appSettings>
        <!-- Allowed users divided by comma -->
        <add key="allowedUsers" value="DOMAIN\User1, DOMAIN\User2" />
    </appSettings>

    <!--Webservice-->
    <system.serviceModel>
        <services>
            <service name="WebService.ApiService">
                <endpoint binding="basicHttpBinding" bindingConfiguration="AuthenticatedBinding" bindingNamespace="http://namespace.com/customapi" contract="WebService.IApiService" />
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior>
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                    <serviceAuthorization serviceAuthorizationManagerType="WebService.Model.Services.AuthorizationService, WebService" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <bindings>
            <basicHttpBinding>
                <binding name="AuthenticatedBinding">
                    <security mode="TransportCredentialOnly">
                        <transport clientCredentialType="Windows" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>

</configuration>

自定义授权管理器:

class AuthorizationService : ServiceAuthorizationManager
{
    private List<string> allowedUsers = new List<string>();

    public AuthorizationService() : base()
    {
        Configure();
    }

    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        base.CheckAccessCore(operationContext);

        return allowedUsers.Contains(operationContext.ServiceSecurityContext.WindowsIdentity.Name);
    }

    private void Configure()
    {
        var configRow = ConfigurationManager.AppSettings["allowedUsers"];
        var parts = configRow.Split(',');

        if (parts.Length > 0)
        {
            foreach (var part in parts)
                allowedUsers.Add(part.Trim());
        }
    }
}

结果图片: 结果截图

4

1 回答 1

1

我在网上发现错误代码 500 是发送 SOAP 错误响应的正确方法。所以我的网络服务一切正常(我收到“拒绝访问”错误,错误代码为 500)。

于 2013-03-28T11:46:38.710 回答