Condividi tramite


Protezione dei messaggi tramite client con tipo di credenziale UserName

Nella figura seguente sono illustrati un servizio e un client Windows Communication Foundation (WCF) protetti tramite protezione a livello di messaggio. Il servizio viene autenticato con un certificato X.509. Il client esegue l'autenticazione utilizzando un nome utente e una password.

Per un'applicazione di esempio, vedere Sicurezza dei messaggi tramite nome utente.

Sicurezza dei messaggi con l'autenticazione del nome utente

Caratteristica Descrizione

Modalità di sicurezza

Messaggio

Interoperabilità

Solo Windows Communication Foundation (WCF)

Autenticazione (server)

La negoziazione iniziale richiede l'autenticazione server

Autenticazione (client)

Nome utente/password

Integrità

Sì, utilizzando un contesto di sicurezza condiviso

Riservatezza

Sì, utilizzando un contesto di sicurezza condiviso

Trasporto

HTTP

Associazione

WSHttpBinding

Servizio

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

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

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

Codice

Nel codice seguente viene illustrato come creare un endpoint del servizio che utilizza la protezione del messaggio.

' Create the binding.
Dim binding As New WSHttpBinding()
binding.Security.Mode = SecurityMode.Message
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName

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

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

' Specify a certificate to authenticate the service.
myServiceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, _
StoreName.My, X509FindType.FindBySubjectName, "Contoso.com")

myServiceHost.Open()
Console.WriteLine("Listening...")
Console.ReadLine()

' Close the service. 
myServiceHost.Close()
// Create the binding.
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType =
     MessageCredentialType.UserName;

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

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

// Specify a certificate to authenticate the service.
myServiceHost.Credentials.ServiceCertificate.
    SetCertificate(StoreLocation.LocalMachine,
    StoreName.My,
    X509FindType.FindBySubjectName,
    "Contoso.com");

myServiceHost.Open();
Console.WriteLine("Listening...");
Console.ReadLine();

// Close the service. 
myServiceHost.Close();

Configurazione

Invece del codice, è possibile utilizzare la configurazione seguente:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceCredentialsBehavior">
          <serviceCredentials>
            <serviceCertificate findValue="Contoso.com" 
                                storeLocation="LocalMachine"
                                storeName="My"   
                                x509FindType="FindBySubjectName" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceCredentialsBehavior"
               name="ServiceModel.Calculator">
        <endpoint address="https://localhost/Calculator"
                  binding="wsHttpBinding"
                  bindingConfiguration="MessageAndUserName"
                  name="SecuredByTransportEndpoint"
                  contract="ServiceModel.ICalculator" />
      </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="MessageAndUserName">
          <security mode="Message">            
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client />
  </system.serviceModel>
</configuration>

Client

Codice

Il codice seguente crea il client. L'associazione riguarda la protezione della modalità messaggio e il tipo di credenziale client è impostato su UserName. Il nome utente e la password possono essere specificati solo tramite codice (non è configurabile). Il codice per restituire il nome utente e la password non è riportato qui perché deve essere eseguito a livello di applicazione. Utilizzare, ad esempio, una finestra di dialogo Window Form per chiedere all'utente i dati.

' Create the binding.
Dim myBinding As New WSHttpBinding()
myBinding.Security.Mode = SecurityMode.Message
myBinding.Security.Message.ClientCredentialType = _
   MessageCredentialType.UserName

' Create the endpoint address. 
Dim ea As New EndpointAddress("http://machineName/Calculator")

' Create the client. 
Dim cc As New CalculatorClient(myBinding, ea)

' Set the user name and password. The code to 
' return the user name and password is not shown here. Use
' an interface to query the user for the information.
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
// Create the binding.
WSHttpBinding myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Message;
myBinding.Security.Message.ClientCredentialType =
    MessageCredentialType.UserName;

// Create the endpoint address. 
EndpointAddress ea = new
    EndpointAddress("http://machineName/Calculator");

// Create the client. 
CalculatorClient cc =
    new CalculatorClient(myBinding, ea);

// Set the user name and password. The code to 
// return the user name and password is not shown here. Use
// an interface to query the user for the information.
cc.ClientCredentials.UserName.UserName = ReturnUsername();
cc.ClientCredentials.UserName.Password = ReturnPassword();

// Begin using the client.
try
{
    cc.Open();
    Console.WriteLine(cc.Add(200, 1111));
    Console.ReadLine();

    // Close the client.
    cc.Close();
}

Configurazione

Il codice seguente configura il client. L'associazione riguarda la protezione della modalità messaggio e il tipo di credenziale client è impostato su UserName. Il nome utente e la password possono essere specificati solo tramite codice (non è configurabile).

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_ICalculator" >
          <security mode="Message">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://machineName/Calculator" 
                binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_ICalculator" 
                contract="ICalculator"
                name="WSHttpBinding_ICalculator">
        <identity>
          <dns value ="Contoso.com" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>

Vedere anche

Attività

Sicurezza dei messaggi tramite nome utente

Concetti

Cenni preliminari sulla sicurezza
Identità del servizio e autenticazione

Altre risorse

<identity>
Sicurezza e protezione