wcf - 如何将用户凭据从 WebClient 传递到 WCF REST 服务?

标签 wcf security webclient webhttpbinding

我正在尝试公开 WCT REST 服务,只有具有有效用户名和密码的用户才能访问它。用户名和密码存储在 SQL 数据库中。

以下是服务契约(Contract):

public interface IDataService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    byte[] GetData(double startTime, double endTime);
}

这是 WCF 配置:
<bindings>
  <webHttpBinding>
    <binding name="SecureBinding">
      <security mode="Transport">
        <transport clientCredentialType="Basic"/>
      </security>
    </binding>
  </webHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="DataServiceBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceCredentials>
        <userNameAuthentication
           userNamePasswordValidationMode="Custom"
           customUserNamePasswordValidatorType=
                 "CustomValidator, WCFHost" />
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="DataServiceBehavior" name="DataService">
    <endpoint address="" binding="webHttpBinding"
              bindingConfiguration="SecureBinding" contract="IDataService" />
  </service>
</services>

我通过 Silverlight 应用程序中的 WebClient 类访问该服务。但是,我无法弄清楚如何将用户凭据传递给服务。我为 client.Credentials 尝试了各种值,但它们似乎都没有触发我的自定义验证器中的代码。我收到以下错误:基础连接已关闭:发送时发生意外错误。

这是我尝试过的一些示例代码:
   WebClient client = new WebClient();
   client.Credentials = new NetworkCredential("name", "password", "domain");
   client.OpenReadCompleted += new OpenReadCompletedEventHandler(GetData);
   client.OpenReadAsync(new Uri(uriString));

如果我将安全模式设置为“无”,则整个过程都有效。我还尝试了其他 clientCredentialType 值,但没有一个起作用。我还自托管了 WCF 服务,以消除与 IIS 在服务获得机会之前尝试对用户进行身份验证相关的问题。

对潜在问题的任何评论将不胜感激。谢谢。

更新 : 感谢 Mehmet 的出色建议。这是我的跟踪配置:
 <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
      <source name="System.IdentityModel" switchValue="Information, 
               ActivityTracing" propagateActivity="true">
        <listeners>
          <add name="xml" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="xml"
           type="System.Diagnostics.XmlWriterTraceListener"
           initializeData="c:\Traces.svclog" />
    </sharedListeners>
  </system.diagnostics>

但是我没有看到来自我的 Silverlight 客户端的任何消息。至于https vs http,我使用https如下:
string baseAddress = "https://localhost:6600/";
_webServiceHost = new WebServiceHost(typeof(DataServices), 
                new Uri(baseAddress));
_webServiceHost.Open();

但是,我没有配置任何 SSL 证书。这是问题吗?

最佳答案

由于您使用的是“基本”身份验证,因此您需要在请求 header 中发送用户名和密码。手动将凭据添加到 header 的示例如下所示:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"https://localhost:6600/MyWCFService/GetData");
//Add a header to the request that contains the credentials
//DO NOT HARDCODE IN PRODUCTION!! Pull credentials real-time from database or other store.
string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("userName" + ":" + "password"));
req.Headers.Add("Authorization", "Basic " + svcCredentials);
//Parse the response and do something with it...
using (WebResponse svcResponse = (HttpWebResponse)req.GetResponse())
{
  using (StreamReader sr = new StreamReader(svcResponse.GetResponseStream()))
  {
    //Sample parses json response; your code here may be different
    JavaScriptSerializer js = new JavaScriptSerializer();
    string jsonTxt = sr.ReadToEnd();
  }
}

关于wcf - 如何将用户凭据从 WebClient 传递到 WCF REST 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/795717/

相关文章:

C# 上传带有附加数据的文件

c# - WCF 测试客户端不支持操作

.net - 在 Crystal Reports 中模拟

c# - 上传时网络客户端超时

php - 如何从另一个 php 脚本执行 php 脚本?

asp.net-mvc - asp.net mvc 应用程序中的 SameSite 属性

java - Spring WebFlux WebClient timeout() 和 exchange()

.net - WCF 消息级别安全性

wcf - 在 WCF REST 4.0 中使用 StandardEndpoints 时如何配置 MessageInspector

c# - Windows 加密容器有多安全?