Saturday, January 4, 2014

Calling a WCF Web Service secured with Azure ACS


This is some sample code for a client console application calling a WCF web service that is secured with Windows Azure Access Control Service.  In fact all I need is to pass the username and password in the client credentials and my web service will do the authentication for me.  If I supply an incorrect password then a MessageSecurityException is created so I need to ensure I have captured that an handled it in some way.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ACE.TestClient.ACS
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                VirtualService.VirtualInterfaceClient c = new VirtualService.VirtualInterfaceClient();
                c.ClientCredentials.UserName.UserName = "MyService";
                c.ClientCredentials.UserName.Password = "Hydrogen1";

                VirtualService.Event input = new VirtualService.Event() { Date = DateTime.Now, Id = "123", Name = "Peter Rabbit" };
                string result = c.PostEvent(input);
                Console.WriteLine("Service Returned: " + result);
            }
            catch (System.ServiceModel.Security.MessageSecurityException mex)
            {
                Console.WriteLine("Failed to authenticate." );
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

No comments: