Dela via


Betrott undersystem

En klient har åtkomst till en eller flera webbtjänster som är distribuerade i ett nätverk. Webbtjänsterna är utformade så att åtkomst till ytterligare resurser (till exempel databaser eller andra webbtjänster) kapslas in i webbtjänstens affärslogik. Dessa resurser måste skyddas mot obehörig åtkomst. Följande bild visar en betrodd undersystemsprocess.

Trusted subsystem

Följande steg beskriver den betrodda undersystemsprocessen enligt bilden:

  1. Klienten skickar en begäran till det betrodda undersystemet, tillsammans med autentiseringsuppgifter.

  2. Det betrodda undersystemet autentiserar och auktoriserar användaren.

  3. Det betrodda undersystemet skickar ett meddelande om begäran till fjärrresursen. Den här begäran åtföljs av autentiseringsuppgifterna för det betrodda undersystemet (eller tjänstkontot under vilket den betrodda undersystemsprocessen körs).

  4. Serverdelsresursen autentiserar och auktoriserar det betrodda undersystemet. Sedan bearbetas begäran och ett svar skickas till det betrodda undersystemet.

  5. Det betrodda undersystemet bearbetar svaret och utfärdar ett eget svar till klienten.

Characteristic beskrivning
Säkerhetsläge Meddelande
Samverkan Endast Windows Communication Foundation (WCF).
Autentisering (tjänst) Säkerhetstokentjänsten autentiserar och auktoriserar klienter.
Autentisering (klient) Det betrodda undersystemet autentiserar klienten och resursen autentiserar den betrodda undersystemtjänsten.
Integritet Ja
Sekretess Ja
Transport HTTP mellan klienten och den betrodda undersystemtjänsten.

NET. TCP mellan den betrodda undersystemtjänsten och resursen (serverdelstjänsten).
Bindning WSHttpBinding och NetTcpBinding<wsFederationHttpBinding>

Resurs (serverdelstjänst)

Kod

Följande kod visar hur du skapar en tjänstslutpunkt för resursen, som använder transportsäkerhet via TCP-transportprotokollet.

// Create a ServiceHost for the CalculatorService type and provide the base address.
using (ServiceHost host = new ServiceHost(typeof(BackendService)))
{
    BindingElementCollection bindingElements = new BindingElementCollection();
    bindingElements.Add(SecurityBindingElement.CreateUserNameOverTransportBindingElement());
    bindingElements.Add(new WindowsStreamSecurityBindingElement());
    bindingElements.Add(new TcpTransportBindingElement());
    CustomBinding backendServiceBinding = new CustomBinding(bindingElements);

    host.AddServiceEndpoint(typeof(ICalculator), backendServiceBinding, "BackendService");

    // Open the ServiceHostBase to create listeners and start listening for messages.
    host.Open();

    // The service can now be accessed.
    Console.WriteLine("The service is ready.");
    Console.WriteLine("Press <ENTER> to terminate service.");
    Console.WriteLine();
    Console.ReadLine();
    host.Close();
}
' Create a ServiceHost for the CalculatorService type and provide the base address.
Using host As New ServiceHost(GetType(BackendService), New Uri("net.tcp://localhost:8001/BackendService"))

    Dim bindingElements As New BindingElementCollection()
    bindingElements.Add(SecurityBindingElement.CreateUserNameOverTransportBindingElement())
    bindingElements.Add(New WindowsStreamSecurityBindingElement())
    bindingElements.Add(New TcpTransportBindingElement())
    Dim backendServiceBinding As New CustomBinding(bindingElements)

    host.AddServiceEndpoint(GetType(ICalculator), backendServiceBinding, "BackendService")

    ' Open the ServiceHostBase to create listeners and start listening for messages.
    host.Open()

    ' The service can now be accessed.
    Console.WriteLine("The service is ready.")
    Console.WriteLine("Press <ENTER> to terminate service.")
    Console.WriteLine()
    Console.ReadLine()
    host.Close()
End Using

Konfiguration

Följande konfiguration konfigurerar samma slutpunkt med hjälp av konfigurationen.

<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
  <system.serviceModel>  
    <services>  
      <service name="Microsoft.ServiceModel.Samples.BackendService"  
               behaviorConfiguration="BackendServiceBehavior">  
        <endpoint address="net.tcp://localhost.com:8001/BackendService"  
                  binding="customBinding"  
                  bindingConfiguration="Binding1"  
                  contract="Microsoft.ServiceModel.Samples.ICalculator"/>  
      </service>  
    </services>  
    <bindings>  
      <customBinding>  
        <binding name="Binding1">  
          <security authenticationMode="UserNameOverTransport"/>  
          <windowsStreamSecurity/>  
          <tcpTransport/>  
        </binding>  
      </customBinding>  
    </bindings>  
    <behaviors>  
      <serviceBehaviors>  
        <behavior name="BackendServiceBehavior">  
          <serviceCredentials>  
            <userNameAuthentication userNamePasswordValidationMode="Custom"  
                                    customUserNamePasswordValidatorType="Microsoft.ServiceModel.Samples.MyUserNamePasswordValidator, BackendService"/>  
          </serviceCredentials>  
        </behavior>  
      </serviceBehaviors>  
    </behaviors>  
  </system.serviceModel>  
</configuration>  

Betrott undersystem

Kod

Följande kod visar hur du skapar en tjänstslutpunkt för det betrodda undersystemet som använder meddelandesäkerhet via HTTP-protokollet och ett användarnamn och lösenord för autentisering.

Uri baseAddress = new Uri("http://localhost:8000/FacadeService");
using (ServiceHost myServiceHost = new ServiceHost(typeof(CalculatorService), baseAddress))
{
    WSHttpBinding binding = new WSHttpBinding();
    binding.Security.Mode = SecurityMode.Message;
    binding.Security.Message.ClientCredentialType =
        MessageCredentialType.UserName;
    myServiceHost.AddServiceEndpoint(typeof(CalculatorService), binding, string.Empty);
    myServiceHost.Open();
    // Wait for calls.
    myServiceHost.Close();
}
Dim baseAddress As New Uri("http://localhost:8000/FacadeService")
Using myServiceHost As New ServiceHost(GetType(CalculatorService), baseAddress)
    Dim binding As New WSHttpBinding()
    binding.Security.Mode = SecurityMode.Message
    binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName
    myServiceHost.AddServiceEndpoint(GetType(CalculatorService), binding, String.Empty)
    myServiceHost.Open()
    ' Wait for calls. 
    myServiceHost.Close()
End Using

Följande kod visar en tjänst i ett betrott undersystem som kommunicerar med en serverdelstjänst med transportsäkerhet via TCP-transportprotokollet.

public double Multiply(double n1, double n2)
{
    // Create the binding.
    BindingElementCollection bindingElements = new BindingElementCollection();
    bindingElements.Add(SecurityBindingElement.CreateUserNameOverTransportBindingElement());
    bindingElements.Add(new WindowsStreamSecurityBindingElement());
    bindingElements.Add(new TcpTransportBindingElement());
    CustomBinding backendServiceBinding = new CustomBinding(bindingElements);

    // Create the endpoint address.
    EndpointAddress ea = new
        EndpointAddress("http://contoso.com:8001/BackendService");

    // Call the back-end service.
    CalculatorClient client = new CalculatorClient(backendServiceBinding, ea);
    client.ClientCredentials.UserName.UserName = ServiceSecurityContext.Current.PrimaryIdentity.Name;
    double result = client.Multiply(n1, n2);
    client.Close();

    return result;
}
Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double _
    Implements ICalculator.Multiply
    ' Create the binding.
    Dim bindingElements As New BindingElementCollection()
    bindingElements.Add(SecurityBindingElement.CreateUserNameOverTransportBindingElement())
    bindingElements.Add(New WindowsStreamSecurityBindingElement())
    bindingElements.Add(New TcpTransportBindingElement())
    Dim backendServiceBinding As New CustomBinding(bindingElements)

    ' Create the endpoint address. 
    Dim ea As New EndpointAddress("http://contoso.com:8001/BackendService")

    ' Call the back-end service.
    Dim client As New CalculatorClient(backendServiceBinding, ea)
    client.ClientCredentials.UserName.UserName = ServiceSecurityContext.Current.PrimaryIdentity.Name
    Dim result As Double = client.Multiply(n1, n2)
    client.Close()

    Return result
End Function

Konfiguration

Följande konfiguration konfigurerar samma slutpunkt med hjälp av konfigurationen. Observera de två bindningarna: Den ena skyddar tjänsten som finns i det betrodda undersystemet och den andra kommunicerar mellan det betrodda undersystemet och serverdelstjänsten.

<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
  <system.serviceModel>  
    <services>  
      <service name="Microsoft.ServiceModel.Samples.FacadeService"  
               behaviorConfiguration="FacadeServiceBehavior">  
        <host>  
          <baseAddresses>  
            <add baseAddress="http://localhost:8000/FacadeService"/>  
          </baseAddresses>  
        </host>  
        <endpoint address="http://localhost:8000/FacadeService"  
                  binding="wsHttpBinding"  
                  bindingConfiguration="Binding1"  
                  contract="Microsoft.ServiceModel.Samples.ICalculator"/>  
      </service>  
    </services>  
    <client>  
      <endpoint name=""
                address="net.tcp://contoso.com:8001/BackendService"  
                binding="customBinding"  
                bindingConfiguration="ClientBinding"  
                contract="Microsoft.ServiceModel.Samples.ICalculator"/>  
    </client>  
    <bindings>  
      <wsHttpBinding>  
        <binding name="Binding1">  
          <security mode="Message">  
            <message clientCredentialType="UserName"/>  
          </security>  
        </binding>  
      </wsHttpBinding>  
      <customBinding>  
        <binding name="ClientBinding">  
          <security authenticationMode="UserNameOverTransport"/>  
          <windowsStreamSecurity/>  
          <tcpTransport/>  
        </binding>  
      </customBinding>  
    </bindings>  
    <behaviors>  
      <serviceBehaviors>  
        <behavior name="FacadeServiceBehavior">  
          <serviceMetadata httpGetEnabled="True"/>  
          <serviceCredentials>  
            <serviceCertificate findValue="Contoso.com"  
                                storeLocation="LocalMachine"  
                                storeName="My"  
                                x509FindType="FindBySubjectName" />  
            <userNameAuthentication userNamePasswordValidationMode="Custom"  
                                    customUserNamePasswordValidatorType="Microsoft.ServiceModel.Samples.MyUserNamePasswordValidator, FacadeService"/>  
          </serviceCredentials>  
        </behavior>  
      </serviceBehaviors>  
    </behaviors>  
  </system.serviceModel>  
</configuration>  

Klient

Kod

Följande kod visar hur du skapar klienten som kommunicerar med det betrodda undersystemet med hjälp av meddelandesäkerhet via HTTP-protokollet och ett användarnamn och lösenord för autentisering.

// Create the binding.
WSHttpBinding subsystemBinding = new WSHttpBinding();
subsystemBinding.Security.Mode = SecurityMode.Message;
subsystemBinding.Security.Message.ClientCredentialType =
    MessageCredentialType.UserName;

// Create the endpoint address.
EndpointAddress ea = new
    EndpointAddress("http://www.cohowinery.com:8000/FacadeService");

CalculatorClient client = new CalculatorClient(subsystemBinding, ea);

// Configure client with valid machine or domain account (username,password)
client.ClientCredentials.UserName.UserName = username;
client.ClientCredentials.UserName.Password = password.ToString();

// Call the Multiply service operation.
double value1 = 39D;
double value2 = 50.44D;
double result = client.Multiply(value1, value2);
Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result);

//Closing the client gracefully closes the connection and cleans up resources
client.Close();
' Create the binding.
Dim subsystemBinding As New WSHttpBinding()
subsystemBinding.Security.Mode = SecurityMode.Message
subsystemBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName

' Create the URI for the endpoint.
Dim ea As New EndpointAddress("http://www.cohowinery.com:8000/FacadeService")

Dim client As New CalculatorClient(subsystemBinding, ea)

' Configure client with valid machine or domain account (username,password)
client.ClientCredentials.UserName.UserName = username
client.ClientCredentials.UserName.Password = password.ToString()

' Call the Multiply service operation.
Dim value1 As Double = 39
Dim value2 As Double = 50.44
Dim result As Double = client.Multiply(value1, value2)
Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result)


'Closing the client gracefully closes the connection and cleans up resources
client.Close()

Konfiguration

Följande kod konfigurerar klienten för att använda meddelandesäkerhet via HTTP-protokollet och ett användarnamn och lösenord för autentisering. Användarnamnet och lösenordet kan bara anges med hjälp av kod (det kan inte konfigureras).

<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
  <system.serviceModel>  
    <client>  
        <endpoint name=""
                  address="http://www.cohowinery.com:8000/FacadeService"  
                  binding="wsHttpBinding"  
                  bindingConfiguration="Binding1"  
                  behaviorConfiguration="ClientUserNameBehavior"  
                  contract="Microsoft.ServiceModel.Samples.ICalculator"/>  
    </client>  
    <bindings>  
      <wsHttpBinding>  
        <binding name="Binding1">  
          <security mode="Message">  
            <message clientCredentialType="UserName"/>  
          </security>  
        </binding>  
      </wsHttpBinding>  
    </bindings>  
    <behaviors>  
      <endpointBehaviors>  
        <behavior name="ClientUserNameBehavior">  
          <clientCredentials>  
            <serviceCertificate>  
              <authentication certificateValidationMode="PeerOrChainTrust"/>  
            </serviceCertificate>  
          </clientCredentials>  
        </behavior>  
      </endpointBehaviors>  
    </behaviors>  
  </system.serviceModel>  
</configuration>  

Se även