WCF 客户端使用证书和用户名/密码凭据?

2023-12-05

我正在使用 ASP.NET 公司内部的 Web 服务。我使用 svcutil.exe 连接到服务并从 wsdl 生成绑定和类。我可以连接到开发版本,该版本不需要身份验证。现在我们正在增加安全性。我的新 URI 使用 https,但还需要用户凭据。

我对 WCF 非常陌生,正在尝试确定配置它的方法。从我的在 MSDN 上阅读,看来要走的路是使用。

更新: 这是我一直在尝试的最新代码。这包含了答案的反馈:

 <system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="svcBehavior">
         <serviceCredentials>
           <serviceCertificate storeLocation="CurrentUser"
                               storeName="My"
                               x509FindType="FindByThumbprint"
                               findValue="xx xx xx etc"/>
         </serviceCredentials>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <wsHttpBinding>
       <binding name="CustomerPaymentProgramSOAPBinding">
         <security mode="TransportWithMessageCredential">
            <message clientCredentialType="UserName" />
         </security>
       </binding>
     </wsHttpBinding>
   </bindings>
  <client>
   <endpoint address="https://***URL***"
    binding="wsHttpBinding" bindingConfiguration="CustomerPaymentProgramSOAPBinding"
    contract="CppService.CustomerPaymentProgramService" name="CustomerPaymentProgramService">
   </endpoint>
  </client>
 </system.serviceModel>

这是调用代码:

using (var svc = new CustomerPaymentProgramServiceClient())
{
    svc.ClientCredentials.UserName.UserName = "*******";
    svc.ClientCredentials.UserName.Password = "*******";
    var request = new GetServiceDataProgramRequest()
                      {
                          CustomerAccountId = Convert.ToInt64(customerAccountId)
                      };

    svc.Open();
    var response = new GetServiceDataProgramResponse();
    var metaData = new RequestMetadata()
                       {
                           ClientIPAddress = "xx.xx.xx.xx",
                           TrackingNumber = "1",
                           UserID = "1"
                       };

    svc.GetAccountData(metaData, request, out response);
}

我收到一条错误消息,指出我正在通过请求传递匿名凭据。 使用更新的代码,现在我收到一个不同的异常:

UPDATE:

进行建议的更改并从 using 块中删除服务调用后(根据this文章),我现在收到 MessageSecurityException:

Error message:
-$exception {"The HTTP request is unauthorized with client authentication scheme 'Anonymous'. 
The authentication header received from the server was 'Basic realm=\"Spring Security Application\"'."} 
System.Exception {System.ServiceModel.Security.MessageSecurityException}


Server stack trace: 
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory factory)
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan timeout)
at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)\r\n\r\nException rethrown at [0]: 
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at [ServiceName].GetAccountData(svcRequest request)
at [ServiceName].GetAccountData(GetAccountDataRequest request) 
    in c:\\[Project]\\service references\\[ServiceName]\\reference.cs:line 3480
at c:\\[Project]\\service references\\[ServiceName](RequestMetadata RequestMetadata, ServiceRequest, ServiceResponse& ServiceResponse) 
    in c:\\[Project]\\service references\\[ServiceName]\\reference.cs:line 3487
at c:\\[Project]\\service references\\[ServiceName].CheckAccountForPaymentPlan(String customerAccountId) 
    in c:\\[Project]\\service references\\[ServiceName]\\\\PlanCheckService.cs:line 32

With TransportWithMessageCredential,您指定将使用消息安全性来保护各个消息,这需要客户端凭据(用户名和密码)。您需要类似于 msdn 链接中的配置,如下所示:

<wsHttpBinding>
<binding name="WsHttpBinding_ICalculator">
        <security mode="TransportWithMessageCredential" >
           <message clientCredentialType="UserName" />
        </security>
</binding>
</wsHttpBinding>

这不需要为客户端凭据指定证书。传输安全(使用 https 和有效的 ssl 证书)的工作方式与网站的工作方式相同,它不需要用户提供额外的凭据/证书。来自受信任证书颁发机构的有效证书安装在服务器上(客户端计算机能够验证它们),并且握手过程可确保通道的安全。这不需要你设置clientCrdentials在配置中。您只需要安装一个有效的证书(或开发测试证书)并配置服务器配置以指向它,类似于:

<behaviors>
 <serviceBehaviors>
   <behavior name="mySvcBehavior">
       <serviceCredentials>
         <serviceCertificate findValue="contoso.com"
                             x509FindType="FindByIssuerName" />
       </serviceCredentials>
   </behavior>
 </serviceBehaviors>
</behaviors>

尝试删除< transport clientCredentialType="Certificate" />作为启动器,从您的服务器配置中更新服务引用并确保您的证书正常工作并正确配置。如果您仍然有问题,请发布您的实际异常和更多配置。

对于一个好的 WCF 源尝试:CodePlex,当我开始使用 WCF 时,它对我帮助很大。不同的应用场景提供了有用的清单,以帮助确保您不会错过配置中的任何步骤。

祝你好运

UPDATE:

一旦通道出现故障,就需要重新创建它,因为在重置之前您将无法与服务进行通信。因此添加一个检查来重新创建它:

If svc.State = CommunicationState.Faulted Then....

尝试删除svc.Open()行,因为我从未真正使用过它。我检查了 msdn 的使用详细信息,但得到了大约 2 行无用的信息。设置服务后,您应该能够与其通信,而无需专门打开它。但不确定这实际上会有所作为吗?!

其他需要检查的事项: - 您可以右键单击该服务并在浏览器中查看而没有问题吗? - 在IIS您可以在目录安全性中查看证书吗?没有任何问题吗? - 在进行服务调用之前进行调试,并检查凭据是否已正确分配。 - 检查服务器事件查看器以获取它可能随请求记录的任何信息(如果已经达到那么远)。

另外,这是我捕获的一些异常,用于确定问题ex.GetBaseException.GetType:

ServiceModel.EndpointNotFoundException

  • 服务器连接问题 - IIS 未运行或服务器名称无效

ServiceModel.Security.MessageSecurityException

  • 基本异常 -ServiceModel.FaultException

    • "FailedAuthentication" - 用户输入的错误凭据

    • "InvalidSecurity“ - 数据库错误 - 任一帐户都无法访问数据库,Web 配置中的数据库名称不正确,用户密码在数据库中已过期

    • "InvalidRequest“ - 证书可访问性问题 - 检查服务帐户是否有权访问证书

基本异常 -Net.WebException

  • 未经授权的访问 401 - 检查 IIS 中的匿名访问是否已打开

基本异常 -IdentityModel.Tokens.SecurityTokenValidationException

  • IIS 中未分配服务证书

基本异常 -System.ServiceModel.CommunicationException

  • 身份与服务器证书不匹配 - 例如在开发环境中,证书名为“localhost”,因此如果您输入服务的 PC 号码或 IP 地址,您将看到此信息
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WCF 客户端使用证书和用户名/密码凭据? 的相关文章

随机推荐

  • Objective-c 是否遵循操作顺序(Bedmas)?

    我只是想知道 因为我构建的应用程序做了一个相当长的方程 并且结果与在 Excel 电子表格上完成的结果不同 我在 Excel 电子表格上得到了方程 输入数字越大 差异越大 这是我在 xcode 中输入的等式 360 num1 num3 1
  • svg animateMotion 偏离路径

    I have this svg 我的目标是让盒子沿着路径移动 同时保持旋转 为了实现这一点 我添加了一个
  • PHP XML 实体编码问题

    经过几个小时的研究 我无法找到这个问题的答案 我正在尝试将 XML 字符串发送给第三方 因此我需要对一些字符进行编码 在本例中是单引号 也许还有双引号 我使用 PHP XML Dom 来实现此目的 但 saveXML 函数似乎总是对引号进行
  • 如何找到图像像素值的众数(统计数据)?

    我正在使用 opencv 并且可以通过下面的代码获取图像的像素 一个 3 维元组 但是 我不太确定如何计算图像中像素值的模式 import cv2 import numpy as np import matplotlib pyplot as
  • White Line 不断阻止 Android Studio 中的代码

    已经有一段时间了 我是 Android Studio 的新手 这条非常白的线或其他任何东西一直挡住我的视线 因为代码的可见性不断降低 迫使我继续重建我的项目 但什么也没有发生 请建议我一种可以帮助我的方法或原因 None
  • ASP.NET MVC网站从磁盘读取文件问题

    我正在阅读一个文本文件 其中包含在我正在处理的 MVC 网站中使用 C 的 SQL 插入语句 调试我正在使用的函数时工作正常并且插入发生 但是 一旦我发布该网站并在本地计算机上运行它 甚至将 IIS 设置为使用 asp net 4 0 它似
  • Shopify 中的内容安全违规

    我正在使用 Shopify 并向不同的服务器发出 ajax get 请求 我刚刚实现了它 所以我正在控制台上测试它 请求正在通过 我得到了我想要的响应 但我也收到以下消息 仅限报告 拒绝连接到 https myurl com ApiClie
  • s3- boto- 按上传时间列出存储桶内的文件

    我需要每小时从 s3 服务器下载 100 个最新文件 bucketList bucket list PREFIX 上面的代码创建了文件列表 但它不依赖于文件的上传时间 因为它是按文件名列出的 我对文件名无能为力 它是随机给出的 Thanks
  • Cuda 5.0 链接问题

    我只是想使用 cuda 5 0 预览版构建我的一个旧项目 链接时出现错误 告诉我找不到某些 cuda 函数 例如 undefined reference to cudaMalloc 我的链接命令包括以下 cuda 选项 L usr loca
  • 单击可折叠项时 jQuery Mobile 页面跳转到顶部

    我有一个带有面板导航的 jQuery Mobile 页面 最后两个元素可与其他菜单项折叠 展开或折叠这些会导致页面跳转到顶部 并且用户必须再次向下滚动才能选择显示的条目之一 我试图通过执行来抑制这种行为 preventDefault 在可折
  • 消除 Windows 中可执行文件的“发布者未经验证”警告

    我已经为 Windows 创建了一个应用程序 每次通过打开可执行文件运行该应用程序时 我都会在 Windows 中收到 发布者未经验证 警告 如果我是这个应用程序的唯一受众 那很好 但事实并非如此 有什么方法可以对我的应用程序进行编程 以便
  • D3.csv 未从本地 csv 文件加载数据

    I created a copy of the csv file in my local folder because i wanted to mess around with the data a little bit When i ge
  • 如何在 SQL Server 2005 中的一条语句中更新两个表?

    我想一次性更新两张表 如何在 SQL Server 2005 中执行此操作 UPDATE Table1 Table2 SET Table1 LastName DR XXXXXX Table2 WAprrs start stop FROM T
  • React - TypeError:无法读取未定义的属性(读取“params”)

    所以我收到一条错误消息 TypeError Cannot readproperties of undefined reading params TypeError Cannot read properties of undefined re
  • 声明多维数组时出现堆栈溢出异常

    一般来说 我对编程有点陌生 并且在声明 3D 和 4D 数组时遇到了问题 我在主函数的开头有几个这样的声明 但我已将问题范围缩小到这 4 个 string reg perm mark name 64 64 64 short reg perm
  • 按 data.frame 中连续年份的子集

    我在 R 中有一个 data frame data table 如下 df lt data frame ID c rep A 20 year c 1968 1971 1972 1973 1974 1976 1978 1980 1982 19
  • Laravel OrderBy 关系计数

    我正在尝试获取最受欢迎的黑客马拉松 这需要按相应的黑客马拉松进行排序partipants gt count 抱歉 如果这有点难以理解 我有一个具有以下格式的数据库 hackathons id name hackathon user hack
  • 获取应用程序上下文返回 null

    以下模式被认为是从我的 Android 应用程序中的任何位置获取应用程序上下文的方法 但有时做MyApp getContext 返回空值 我尝试通过删除来更改架构static from getContext 这样我会做MyApp getIn
  • GZipStream 正在切断 XML 的最后一部分

    我创建了一个名为 AddGZip 的扩展方法 如下所示 public static void AddGZip this HttpResponse response response Filter new GZipStream respons
  • WCF 客户端使用证书和用户名/密码凭据?

    我正在使用 ASP NET 公司内部的 Web 服务 我使用 svcutil exe 连接到服务并从 wsdl 生成绑定和类 我可以连接到开发版本 该版本不需要身份验证 现在我们正在增加安全性 我的新 URI 使用 https 但还需要用户