Partager via


Comment : utiliser la sécurité du message avec le transport de messagerie Exchange Server WCF

Mise à jour : novembre 2007

Cet exemple montre comment utiliser la sécurité des messages SOAP avec le transport de messagerie Exchange Server Windows Communication Foundation (WCF).

Exemple

L'exemple suivant s'exécute sur le bureau et montre comment envoyer et recevoir un message en utilisant la sécurité de message.

Cet exemple suppose qu'un certificat d'une source fiable est présent dans le magasin de certificats, et que les références au certificat dans le code ont été mises à jour convenablement.

Lorsque vous créez un message, vous devez sérialiser le message dans l'appel CreateMessage en transmettant un sérialiseur personnalisé comme un paramètre supplémentaire. Sur le bureau, vous pouvez utiliser un sérialiseur personnalisé ou des attributs pour créer des données sérialisées. Toutefois, nous vous recommandons d'utiliser le même sérialiseur à la fois pour le périphérique et le bureau.

Le sérialiseur personnalisé n'est pas spécifique au transport de messagerie Exchange Server WCF et n'est pas inclus dans cet exemple. Pour obtenir un exemple de sérialiseur personnalisé, consultez Comment : sérialiser des messages dans des applications WCF.

Class Program
    Private Shared ChannelName As String = "Channel1"
    Private Shared ServiceEmailAddress As String = "service@fabrikam.com"

    Private Shared serializer As New CFMessagingSerializer(GetType(String))


    Shared Sub Main(ByVal args() As String) 
        Dim factory As IChannelFactory(Of IOutputChannel)
        Dim output As IOutputChannel
        Dim bpc As BindingParameterCollection
        Dim message As Message
        Dim binding As ExchangeWebServiceMailBinding
        Dim clientEmailServer As New Uri("http://mail.example.com")
        Dim clientEmailAddress As String = "client@example.com"
        Dim password As String = "password"

        binding = New ExchangeWebServiceMailBinding(clientEmailServer, New NetworkCredential(clientEmailAddress, password))
        binding.Security.Mode = MailSecurityMode.Message
        bpc = New BindingParameterCollection()

        Dim cc As New ClientCredentials()

        cc.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName, "example.com")
        cc.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.ChainTrust
        cc.ServiceCertificate.SetDefaultCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName, "fabrikam.com")

        Dim cpr As New ChannelProtectionRequirements()
        ' Sign and encrypt body for *all* messages
        cpr.OutgoingSignatureParts.AddParts(New MessagePartSpecification(True), "*")
        cpr.IncomingSignatureParts.AddParts(New MessagePartSpecification(True), "*")
        cpr.OutgoingEncryptionParts.AddParts(New MessagePartSpecification(True), "*")
        cpr.IncomingEncryptionParts.AddParts(New MessagePartSpecification(True), "*")

        bpc.Add(cc)
        bpc.Add(cpr)

        factory = binding.BuildChannelFactory(Of IOutputChannel)(bpc)

        factory.Open()

        Dim sendAddress As New EndpointAddress(MailUriHelper.CreateUri(ChannelName, ServiceEmailAddress), EndpointIdentity.CreateX509CertificateIdentity(cc.ServiceCertificate.DefaultCertificate))
        output = factory.CreateChannel(sendAddress)

        message = System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.Default, "urn:Test", "Hello, World!", serializer)
        output.Open()
        output.Send(message)

        output.Close()
        factory.Close()

        binding.Close()


        ' Receiving message on the server side
        '
        Dim listener As IChannelListener(Of IInputChannel)
        Dim input As IInputChannel
        Dim serviceEmailServer As New Uri("http://mail.fabrikam.com")

        binding = New ExchangeWebServiceMailBinding(serviceEmailServer, New NetworkCredential(ServiceEmailAddress, password), MailSecurityMode.Message)

        ' Create credential for the listening side
        Dim sc As New ServiceCredentials()
        sc.ServiceCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName, "fabrikam.com")
        sc.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None

        bpc = New BindingParameterCollection()
        bpc.Add(sc)
        bpc.Add(cpr)

        listener = binding.BuildChannelListener(Of IInputChannel)(MailUriHelper.CreateUri(ChannelName, ""))
        listener.Open()

        input = listener.AcceptChannel()
        input.Open()

        message = input.Receive()
        Dim data As String = message.GetBody(Of String)(serializer)

        input.Close()
        listener.Close()

        binding.Close()

    End Sub
End Class
class Program
{
    private static string ChannelName = "Channel1";
    private static string ServiceEmailAddress = "service@fabrikam.com";

    private static CFMessagingSerializer serializer = new CFMessagingSerializer(typeof(string));

    static void Main(string[] args)
    {
        IChannelFactory<IOutputChannel> factory;
        IOutputChannel output;
        BindingParameterCollection bpc;
        Message message;
        ExchangeWebServiceMailBinding binding;
        Uri clientEmailServer = new Uri("http://mail.example.com");
        string clientEmailAddress = "client@example.com";
        string password = "password";

        binding = new ExchangeWebServiceMailBinding(clientEmailServer,
                                                   new NetworkCredential(clientEmailAddress, password));
        binding.Security.Mode = MailSecurityMode.Message;
        bpc = new BindingParameterCollection();

        ClientCredentials cc = new ClientCredentials();

        cc.ClientCertificate.SetCertificate(
              System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
        System.Security.Cryptography.X509Certificates.StoreName.My,
        System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
              "example.com");
        cc.ServiceCertificate.Authentication.CertificateValidationMode =
            System.ServiceModel.Security.X509CertificateValidationMode.ChainTrust;
        cc.ServiceCertificate.SetDefaultCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
        System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
              "fabrikam.com");

        ChannelProtectionRequirements cpr = new ChannelProtectionRequirements();
        // Sign and encrypt body for *all* messages
        cpr.OutgoingSignatureParts.AddParts(new MessagePartSpecification(true), "*");
        cpr.IncomingSignatureParts.AddParts(new MessagePartSpecification(true), "*");
        cpr.OutgoingEncryptionParts.AddParts(new MessagePartSpecification(true), "*");
        cpr.IncomingEncryptionParts.AddParts(new MessagePartSpecification(true), "*");

        bpc.Add(cc);
        bpc.Add(cpr);

        factory = binding.BuildChannelFactory<IOutputChannel>(bpc);

        factory.Open();

        EndpointAddress sendAddress = new EndpointAddress(MailUriHelper.CreateUri(ChannelName,
            ServiceEmailAddress), EndpointIdentity.CreateX509CertificateIdentity(cc.ServiceCertificate.DefaultCertificate));
        output = factory.CreateChannel(sendAddress);

        message = Message.CreateMessage(MessageVersion.Default, "urn:Test", "Hello, World!", serializer);
        output.Open();
        output.Send(message);

        output.Close();
        factory.Close();

        binding.Close();


        // Receiving message on the server side
        //

        IChannelListener<IInputChannel> listener;
        IInputChannel input;
        Uri serviceEmailServer = new Uri("http://mail.fabrikam.com");

        binding = new ExchangeWebServiceMailBinding(serviceEmailServer,
                                                   new NetworkCredential(ServiceEmailAddress, password),
                                                   MailSecurityMode.Message);

        // Create credential for the listening side
        ServiceCredentials sc = new ServiceCredentials();
        sc.ServiceCertificate.SetCertificate(
            System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
            System.Security.Cryptography.X509Certificates.StoreName.My,
            System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
            "fabrikam.com");
        sc.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

        bpc = new BindingParameterCollection();
        bpc.Add(sc);
        bpc.Add(cpr);

        listener = binding.BuildChannelListener<IInputChannel>(MailUriHelper.CreateUri(ChannelName, ""), bpc);
        listener.Open();

        input = listener.AcceptChannel();
        input.Open();

        message = input.Receive();
        string data = message.GetBody<string>(serializer);

        input.Close();
        listener.Close();

        binding.Close();

    }
}

Compilation du code

Cet exemple nécessite des références aux espaces de noms suivants :

Sécurité

Pour plus d'informations sur les options de sécurité, consultez Transport de messagerie Exchange Server WCF.

Voir aussi

Tâches

Procédure pas à pas : utilisation du transport de messagerie Exchange Server WCF

Autres ressources

Développement Windows Communication Foundation (WCF) et le .NET Compact Framework