如何在运行时使用 WS 安全性在 c# 中设置凭据的 Web 服务



我正在使用 C# 开发一个 WCF 项目,我需要使用具有 ws-security 的 Web 服务。问题是我只会在使用 Web 服务之前知道在运行时要使用的凭据,所以我不能真正使用 webconfig 文件来设置 soap 标头安全部分。

我的网络配置文件如下所示:

<?xml version="1.0"?>
<configuration>    
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1"/>
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="GuiaAcompanhamentoImplServiceSoapBinding1" maxReceivedMessageSize="1000000" useDefaultWebProxy="false">
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />            
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://qualsiliamb.apambiente.pt/egar/services/GuiaAcompanhamentoWs/v2"
        binding="basicHttpBinding" bindingConfiguration="GuiaAcompanhamentoImplServiceSoapBinding1"
        contract="APAeGARv2.GuiaAcompanhamentoWs" name="GuiaAcompanhamentoWsPort1" >
        <headers>
          <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <wsse:UsernameToken>
              <wsse:Username>XXXXXXXXXX</wsse:Username>
              <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">XXXXXXXXXX</wsse:Password>
            </wsse:UsernameToken>
          </wsse:Security>
        </headers>
      </endpoint>    
    </client>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>    
  </system.webServer>    
</configuration>

我的 C# 代码如下所示:

public string egAnularGuia2(string token, string nifInterveniente, string idUser, int idInstalacao, int idPda, string idMatricula, string numeroGuia, string codigoVerificacao, string Observacoes)
{
    APAeGARv2.GuiaAcompanhamentoWsClient ws = new APAeGARv2.GuiaAcompanhamentoWsClient();
    // I'd like to insert credencials for ws-security here, but don't know how
    APAeGARv2.anularGuiaInput inp = new APAeGARv2.anularGuiaInput();
    inp.tokenCertificacao = tokenCertificacao;
    inp.nifInterveniente = nifInterveniente;
    inp.idGuia = new APAeGARv2.identificadorGuia();
    inp.idGuia.numeroGuia = numeroGuia;
    inp.idGuia.codigoVerificacao = codigoVerificacao;
    inp.observacoes = Observacoes;
    APAeGARv2.anularGuiaOutput outp = new APAeGARv2.anularGuiaOutput();
    try
    {
        outp = ws.anularGuia(inp);
    }
    catch (Exception Erro)
    {
        outp.result = ErroOutput2(outp.result, Erro);
    }
    return SerializeOutput(outp);
}

使用此方法效果很好。但正如我所提到的,我仅限于在设计时在 webconfig 文件中设置的凭据。

我的问题是:如何更改 C# 代码以便能够在运行时更改凭据?

谢谢!

经过一些研究并询问了几个同事,有人提出了一个解决方案,我测试了它并且效果很好:

    public string egAnularGuia2(string token, string nifInterveniente, string idUser, int idInstalacao, int idPda, string idMatricula, string numeroGuia, string codigoVerificacao, string Observacoes)
    {
        EndpointAddress address = new EndpointAddress("https://qualsiliamb.apambiente.pt/egar/services/GuiaAcompanhamentoWs/v2");
        BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
        CustomBinding customBinding = new CustomBinding(binding);
        SecurityBindingElement element = customBinding.Elements.Find<SecurityBindingElement>();
        element.IncludeTimestamp = false;
        APAeGARv2.GuiaAcompanhamentoWsClient ws = new APAeGARv2.GuiaAcompanhamentoWsClient(customBinding, address);
        ws.ClientCredentials.UserName.UserName = "XXXXXXXXX";
        ws.ClientCredentials.UserName.Password = "XXXXXXXXX";
        APAeGARv2.GuiaAcompanhamentoWsClient ws = new APAeGARv2.GuiaAcompanhamentoWsClient();
        // the rest remains the same...
    }

相关内容

  • 没有找到相关文章

最新更新