在集成测试中测试自托管WCF服务的身份验证

时间:2014-07-29 17:47:57

标签: c# wcf authentication

我正在尝试使用SSL和集成测试中的自定义身份验证验证程序来使用自托管的WCF应用程序。到目前为止,我能够自我托管服务,但我无法弄清楚如何使用它。

这是自托管代码(据我所知,它不依赖于Web.Config):

[ClassInitialize]
public static void TestClassInitialize(TestContext testContext)
{
    const string serviceAddress = "https://localhost/SelfHostedService";
    Uri _svcEndpointUri = new Uri(serviceAddress);
    var binding = new WSHttpBinding
    {
        Security =
        {
            Mode = SecurityMode.TransportWithMessageCredential,
            Message = {ClientCredentialType = MessageCredentialType.UserName}
        }
    };
    ServiceDebugBehavior debugBehavior = new ServiceDebugBehavior
    {
        IncludeExceptionDetailInFaults = true
    };
    MyServiceApi _api = new MyServiceApi();
    ServiceHost _svcHost = new ServiceHost(_api, _svcEndpointUri);
    _svcHost.Description.Behaviors.Remove<ServiceDebugBehavior>();
    _svcHost.Description.Behaviors.Add(debugBehavior);

    // Ensure that SSL certificate & authentication interceptor get used
    ServiceCredentials credentials = new ServiceCredentials();
    credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
    credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new MyCustomAuthenticationValidator();
    credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "SubjectName");
    _svcHost.Description.Behaviors.Remove<ServiceCredentials>();
    _svcHost.Description.Behaviors.Add(credentials);

    // Add IUbiquity and mex endpoints
    Uri endpointAddress = new Uri(serviceAddress + "/UbiquityApi.svc");
    _svcHost.AddServiceEndpoint(typeof (IUbiquityApi), binding, endpointAddress);


    // Specify InstanceContextMode, which is required to self-host
    var behavior = _svcHost.Description.Behaviors.Find<ServiceBehaviorAttribute>();
    behavior.InstanceContextMode = InstanceContextMode.Single;
    _svcHost.Open();
}

我希望能做的事情看起来像这样,但我不知道我将如何做到这一点:

[TestMethod]
public void TestAuthentication(){
    var api = _svcHost.MagicallyRetrieveServiceInstance();
    api.Credentials = new MagicCredentials("my username", "my password");
    Assert.AreEqual(3, api.AddNumbers(1,2));
    // Also assert that I am authenticated 

    api.Credentials = new MagicCredentials("my username", "my password");
    bool exceptionWasThrown = false;
    try {
       api.AddNumbers(1,2);
    }
    catch(NotLoggedInException l){ // or something
       exceptionWasThrown = true;
    }
    Assert.IsTrue(exceptionWasThrown);
}

我理想的解决方案允许我从服务主机检索服务合同,并允许我设置用于服务合同的凭据。我只需要向服务合同提供一次凭证,然后我应该能够直接调用方法,就像我通过线路进行通信一样(从而使这成为集成测试)。我应该怎么做呢?

1 个答案:

答案 0 :(得分:0)

要使用Web服务,只需将服务添加为服务引用,然后使用服务引用客户端。

如果做得好,这将处理身份验证所需的绑定,从而有效地对WCF配置进行测试。