WCF Web服务自定义授权

时间:2013-03-27 12:30:21

标签: wcf authorization

我有使用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());
        }
    }
}

结果图片: Result screenshot

1 个答案:

答案 0 :(得分:1)

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

相关问题