如何在运行时使用c#设置凭据使用WS Security使用Web服务?

时间:2018-03-01 16:18:34

标签: c# web-services wcf soap ws-security

我正在使用C#开发一个WCF项目,我需要使用带有ws-security的Web服务。问题是我只知道在使用Web服务之前立即在运行时使用的凭据,因此我无法真正使用webconfig文件来设置soap header安全部分。

我的webconfig文件如下所示:

<?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#代码以便能够在运行时更改凭据?

谢谢!

1 个答案:

答案 0 :(得分:0)

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

    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...
    }