Procedura: creare una sessione protetta

Ad eccezione del binding <basicHttpBinding>, i binding forniti dal sistema in Windows Communication Foundation (WCF) usano automaticamente sessioni sicure quando la sicurezza dei messaggi è abilitata.

Per impostazione predefinita, le sessioni protette non restano attive quando un server Web viene riciclato. Quando si stabilisce una sessione protetta, il client e il servizio memorizzano nella cache la chiave associata alla sessione protetta. Durante lo scambio dei messaggi, viene scambiato solo un identificatore della chiave memorizzata nella cache. Se il server Web viene riciclato, anche la cache viene riciclata, pertanto il server Web non può recuperare la chiave memorizzata nella cache per l'identificatore. In questo caso, al client viene restituita un'eccezione. Le sessioni protette che usano un token del contesto di sicurezza (SCT) con stato possono restare attive quando un server Web viene riciclato. Per altre informazioni sull'uso di un token SCT con stato in una sessione protetta, vedere Procedura: Creare un token di contesto di sicurezza per una sessione sicura.

Per specificare che un servizio usa sessioni protette mediante una delle associazioni fornite dal sistema

  • Configurare un servizio per l'uso di un'associazione fornita dal sistema che supporta la protezione dei messaggi.

    Ad eccezione di binding <basicHttpBinding>, quando i binding forniti dal sistema sono configurati per l'uso della sicurezza dei messaggi, WCF usa automaticamente sessioni sicure. Nella tabella seguente vengono elencate le associazioni fornite dal sistema che supportano la protezione dei messaggi e viene indicato se la protezione del messaggio è il meccanismo di sicurezza predefinito.

    Associazione fornita dal sistema Elemento di configurazione Sicurezza dei messaggi attivata per impostazione predefinita
    BasicHttpBinding <basicHttpBinding> No
    WSHttpBinding <wsHttpBinding>
    WSDualHttpBinding <wsDualHttpBinding>
    WSFederationHttpBinding <wsFederationHttpBinding>
    NetTcpBinding <netTcpBinding> No
    NetMsmqBinding <netMsmqBinding> No

    Nell'esempio di codice seguente viene usata la configurazione per specificare un binding denominato wsHttpBinding_Calculator che usa <wsHttpBinding>, la sicurezza dei messaggi e le sessioni protette.

    <bindings>  
      <WSHttpBinding>  
       <binding name = "wsHttpBinding_Calculator">  
         <security mode="Message">  
           <message clientCredentialType="Windows"/>  
         </security>  
        </binding>  
      </WSHttpBinding>  
    </bindings>  
    

    Nell'esempio di codice seguente viene specificato che le sessioni <wsHttpBinding>, sicurezza dei messaggi e sicurezza vengono usate per proteggere il servizio secureCalculator.

    WSHttpBinding myBinding = new WSHttpBinding();
    myBinding.Security.Mode = SecurityMode.Message;
    myBinding.Security.Message.ClientCredentialType =
        MessageCredentialType.Windows;
    
    // Create the Type instances for later use and the URI for
    // the base address.
    Type contractType = typeof(ICalculator);
    Type serviceType = typeof(Calculator);
    Uri baseAddress = new
        Uri("http://localhost:8036/serviceModelSamples/");
    
    // Create the ServiceHost and add an endpoint, then start
    // the service.
    ServiceHost myServiceHost =
        new ServiceHost(serviceType, baseAddress);
    myServiceHost.AddServiceEndpoint
        (contractType, myBinding, "secureCalculator");
    myServiceHost.Open();
    
    Dim myBinding As New WSHttpBinding()
    myBinding.Security.Mode = SecurityMode.Message
    myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows
    
    ' Create the Type instances for later use and the URI for 
    ' the base address.
    Dim contractType As Type = GetType(ICalculator)
    Dim serviceType As Type = GetType(Calculator)
    Dim baseAddress As New Uri("http://localhost:8036/serviceModelSamples/")
    
    ' Create the ServiceHost and add an endpoint, then start
    ' the service.
    Dim myServiceHost As New ServiceHost(serviceType, baseAddress)
    myServiceHost.AddServiceEndpoint(contractType, myBinding, "secureCalculator")
    myServiceHost.Open()
    

    Nota

    Le sessioni sicure possono essere disattivate per <wsHttpBinding> impostando l'attributo establishSecurityContext su false. Per le altre associazioni fornite dal sistema, è possibile disattivare le sessioni protette solo creando un'associazione personalizzata.

Per specificare che un servizio usa sessioni protette mediante un'associazione personalizzata

  • Creare un'associazione personalizzata che specifica che i messaggi SOAP sono protetti mediante una sessione protetta.

    Per altre informazioni sulla creazione di un binding personalizzata, vedere Procedura: Personalizzare un binding fornito dal sistema.

    Nell'esempio di codice seguente viene usata la configurazione per specificare un'associazione personalizzata che protegge i messaggi mediante una sessione protetta.

    <bindings>  
      <!-- configure a custom binding -->  
      <customBinding>  
        <binding name="customBinding_Calculator">  
          <security authenticationMode="SecureConversation" />  
          <secureConversationBootstrap authenticationMode="SspiNegotiated" />  
          <textMessageEncoding messageVersion="Soap12WSAddressing10" writeEncoding="utf-8"/>  
          <httpTransport/>  
        </binding>  
      </customBinding>  
    </bindings>  
    

    Nell'esempio di codice seguente viene creata un'associazione personalizzata che usa la modalità di autenticazione MutualCertificate per l'avvio automatico di una sessione protetta.

    SecurityBindingElement security = SecurityBindingElement.CreateMutualCertificateBindingElement();
    
    // Use a secure session.
    security = SecurityBindingElement.CreateSecureConversationBindingElement(security, true);
    
    // Specify whether derived keys are required.
    security.SetKeyDerivation(true);
    
    // Create the custom binding.
    CustomBinding myBinding = new CustomBinding(security, new HttpTransportBindingElement());
    
    // Create the Type instances for later use and the URI for
    // the base address.
    Type contractType = typeof(ICalculator);
    Type serviceType = typeof(Calculator);
    Uri baseAddress = new
        Uri("http://localhost:8036/serviceModelSamples/");
    
    // Create the ServiceHost and add an endpoint, then start
    // the service.
    ServiceHost myServiceHost =
        new ServiceHost(serviceType, baseAddress);
    myServiceHost.AddServiceEndpoint
        (contractType, myBinding, "secureCalculator");
    myServiceHost.Open();
    
    Dim security As SecurityBindingElement = SecurityBindingElement.CreateMutualCertificateBindingElement()
    
    ' Use a secure session.
    security = SecurityBindingElement.CreateSecureConversationBindingElement(security, True)
    
    ' Specify whether derived keys are required.
    security.SetKeyDerivation(True)
    
    ' Create the custom binding.
    Dim myBinding As New CustomBinding(security, New HttpTransportBindingElement())
    
    ' Create the Type instances for later use and the URI for 
    ' the base address.
    Dim contractType As Type = GetType(ICalculator)
    Dim serviceType As Type = GetType(Calculator)
    Dim baseAddress As New Uri("http://localhost:8036/serviceModelSamples/")
    
    ' Create the ServiceHost and add an endpoint, then start
    ' the service.
    Dim myServiceHost As New ServiceHost(serviceType, baseAddress)
    myServiceHost.AddServiceEndpoint(contractType, myBinding, "secureCalculator")
    myServiceHost.Open()
    

Vedi anche