Condividi tramite


Sicurezza del trasporto con autenticazione di base

La figura seguente mostra un servizio e un client windows Communication Foundation (WCF). Il server richiede un certificato X.509 valido che può essere usato per Secure Sockets Layer (SSL) e i client devono considerare attendibile il certificato del server. Inoltre, il servizio Web dispone già di un'implementazione SSL che può essere usata. Per altre informazioni sull'abilitazione dell'autenticazione di base in Internet Information Services (IIS), vedere Autenticazione di base.

Screenshot che mostra la sicurezza del trasporto con l'autenticazione di base.

Caratteristica Descrizione
Modalità di sicurezza Trasporto
Interoperabilità Con i client e i servizi del servizio Web esistenti
Autenticazione (server)

Autenticazione (client)
Sì (con HTTPS)

Sì (tramite Nome utente/Password)
Integrità
Riservatezza
Trasporto HTTPS
Vincolo WSHttpBinding

Servizio

Il codice e la configurazione seguenti devono essere eseguiti in modo indipendente. Esegui una delle operazioni seguenti:

  • Creare un servizio autonomo usando il codice senza alcuna configurazione.

  • Creare un servizio usando la configurazione fornita, ma non definire alcun endpoint.

Codice

Il codice seguente illustra come creare un endpoint di servizio che usa un nome utente di dominio Windows e una password per la sicurezza del trasferimento. Si noti che il servizio richiede un certificato X.509 per l'autenticazione al client. Per altre informazioni, vedere Utilizzo dei certificati e Procedura: Configurare una porta con un certificato SSL.

// Create the binding.
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType =
    HttpClientCredentialType.Basic;

// Create the URI for the endpoint.
Uri httpUri = new Uri("https://localhost/Calculator");

// Create the service host and add an endpoint.
ServiceHost myServiceHost = new ServiceHost(
    typeof(ServiceModel.Calculator), httpUri);
myServiceHost.AddServiceEndpoint(
    typeof(ServiceModel.ICalculator), binding, "");

// Open the service.
myServiceHost.Open();
Console.WriteLine("Listening...");
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();

// Close the service.
myServiceHost.Close();
' Create the binding.
Dim binding As New WSHttpBinding()
binding.Security.Mode = SecurityMode.Transport
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic

' Create the URI for the endpoint.
Dim httpUri As New Uri("https://localhost/Calculator")

' Create the service host and add an endpoint.
Dim myServiceHost As New ServiceHost(GetType(ServiceModel.Calculator), httpUri)
myServiceHost.AddServiceEndpoint(GetType(ServiceModel.ICalculator), binding, "")

' Open the service.
myServiceHost.Open()
Console.WriteLine("Listening...")
Console.WriteLine("Press Enter to exit.")
Console.ReadLine()

' Close the service.
myServiceHost.Close()

Configurazione

Di seguito viene configurato un servizio per l'uso dell'autenticazione di base con la sicurezza a livello di trasporto:

<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
    <system.serviceModel>  
        <bindings>  
            <wsHttpBinding>  
                <binding name="UsernameWithTransport">  
                    <security mode="Transport">  
                        <transport clientCredentialType="Basic" />  
                    </security>  
                </binding>  
            </wsHttpBinding>  
        </bindings>  
        <services>  
            <service name="BasicAuthentication.Calculator">  
                <endpoint address="https://localhost/Calculator"  
                          binding="wsHttpBinding"
                          bindingConfiguration="UsernameWithTransport"  
                          name="BasicEndpoint"
                          contract="BasicAuthentication.ICalculator" />  
            </service>  
        </services>  
    </system.serviceModel>  
</configuration>  

Cliente

Codice

Il codice seguente mostra il codice client che include il nome utente e la password. Si noti che l'utente deve fornire un nome utente e una password di Windows validi. Il codice per restituire il nome utente e la password non vengono visualizzati qui. Usare una finestra di dialogo o un'altra interfaccia per richiedere informazioni all'utente.

Annotazioni

Il nome utente e la password possono essere impostati solo usando il codice.

// Create the binding.
WSHttpBinding myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Transport;
myBinding.Security.Transport.ClientCredentialType =
    HttpClientCredentialType.Basic;

// Create the endpoint address. Note that the machine name
// must match the subject or DNS field of the X.509 certificate
// used to authenticate the service.
EndpointAddress ea = new
    EndpointAddress("https://machineName/Calculator");

// Create the client. The code for the calculator
// client is not shown here. See the sample applications
// for examples of the calculator code.
CalculatorClient cc =
    new CalculatorClient(myBinding, ea);
// The client must provide a user name and password. The code
// to return the user name and password is not shown here. Use
// a database to store the user name and passwords, or use the
// ASP.NET Membership provider database.
cc.ClientCredentials.UserName.UserName = ReturnUsername();
cc.ClientCredentials.UserName.Password = ReturnPassword();
try
{
    // Begin using the client.
    cc.Open();
    Console.WriteLine(cc.Add(100, 11));
    Console.ReadLine();

    // Close the client.
    cc.Close();
}
' Create the binding.
Dim myBinding As New WSHttpBinding()
myBinding.Security.Mode = SecurityMode.Transport
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic

' Create the endpoint address. Note that the machine name
' must match the subject or DNS field of the X.509 certificate
' used to authenticate the service.
Dim ea As New EndpointAddress("https://machineName/Calculator")

' Create the client. The code for the calculator
' client is not shown here. See the sample applications
' for examples of the calculator code.
Dim cc As New CalculatorClient(myBinding, ea)

' The client must provide a user name and password. The code
' to return the user name and password is not shown here. Use
' a database to store the user name and passwords, or use the
' ASP.NET Membership provider database.
cc.ClientCredentials.UserName.UserName = ReturnUsername()
cc.ClientCredentials.UserName.Password = ReturnPassword()

' Begin using the client.
Try
    cc.Open()

    Console.WriteLine(cc.Add(100, 11))
    Console.ReadLine()

    ' Close the client.
    cc.Close()
Catch tex As TimeoutException
    Console.WriteLine(tex.Message)
    cc.Abort()
Catch cex As CommunicationException
    Console.WriteLine(cex.Message)
    cc.Abort()
Finally
    Console.WriteLine("Closed the client")
    Console.ReadLine()
End Try

Configurazione

Il codice seguente illustra la configurazione client.

Annotazioni

Non è possibile usare la configurazione per impostare il nome utente e la password. La configurazione illustrata di seguito deve essere aumentata usando il codice per impostare il nome utente e la password.

<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
  <system.serviceModel>  
    <bindings>  
      <wsHttpBinding>  
        <binding name="WSHttpBinding_ICalculator" >  
          <security mode="Transport">  
            <transport clientCredentialType="Basic" />  
          </security>  
        </binding>  
      </wsHttpBinding>  
    </bindings>  
    <client>  
      <endpoint address="https://machineName/Calculator"
                binding="wsHttpBinding"  
                bindingConfiguration="WSHttpBinding_ICalculator"
                contract="ICalculator"  
                name="WSHttpBinding_ICalculator" />  
    </client>  
  </system.serviceModel>  
</configuration>  

Vedere anche