Archive

Archive for the ‘Azure’ Category

Transient faults and testing

October 31, 2014 1 comment

In this post I am going to talk about the transient fault exception handling block and how we can unit test using mock. So we start by getting the Transient Fault Handling Application from Nuget.

PM> Install-Package EnterpriseLibrary.TransientFaultHandling

Although in the package description it mentions about windows azure but it can be used for any .Net component. In fact if you are doing any serious .net enterprise development I highly recommend using this in your application. And as it happens to be that I am working on a On-Premise Windows Service Bus and I had to build a robust capability of handling transient faults so I used it for my service bus code as well as for SQL Server, SQL Azure, Blob Storage, SFTP etc.

The one simple rule for using this application block is that you have define an error detection strategy (a class) which implements the ITransientErrorDetectionStrategy interface and then wire it with retry policy class of the application block and that’s it you are up and running.

So the code I am going to write is a simple OrderService which picks up Orders which are in the state of "Not Processed" and takes the Id’s of the orders and send the message to the bus. For brevity I have left all the details and specific and just wrote this demo like code. The main focus of this post is on writing effective unit tests for fail/retry logic.

Lets start cutting some code with our Order POCO class, some interface to mock EntityFramework context and a OrderService which will coordinate the whole task.

OrderStatus.cs

public enum OrderStatus
{
    NotProcessed,
    InTransition,
    Shipped
}

IOrderContext.cs

public interface IOrderContext
{
    DbSet<Order> Order { get; set; }
}

Order.cs

public class Order
{
    public int Id { get; set; }

    // omitted for brevity
    public OrderStatus Status { get; set; }
}

IServiceBus.cs

public interface IServiceBus
{
    void Send(BrokeredMessage messages, string queueName);
}


Now we will define our error detection strategy as following.

MessagingCommunicationErrorDetectionStrategy.cs

public class MessagingCommunicationErrorDetectionStrategy 
                : ITransientErrorDetectionStrategy
{
    public bool IsTransient(Exception ex)
    {
        var commException = 
                    ex as MessagingCommunicationException;

        if (commException != null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

And this is order service which will fetch some unprocessed orders using EntityFramework and send them to the service bus.

OrderService .cs

public class OrderService : IOrderService
{
    private readonly IServiceBus serviceBus;

    private readonly IOrderContext orderContext;

    public OrderService(IServiceBus serviceBus, IOrderContext orderContext)
    {
        this.serviceBus = serviceBus;
        this.orderContext = orderContext;
    }

    public void Process()
    {
        var orders = orderContext
                        .Order
                        .Where(x => x.Status == OrderStatus.NotProcessed)
                        .ToList();

        var retryPolicy = 
            new RetryPolicy<MessagingCommunicationErrorDetectionStrategy>(5);

        orders.ForEach(o => 
                retryPolicy.ExecuteAction(() => 
                                            this.serviceBus.Send
                                            (
                                                new BrokeredMessage
                                                    {
                                                        MessageId = o.Id.ToString()
                                                    },
                                                    "orderqueue")
                                            ));
    }
}

As you can see for quick demo purpose I have hard coded the creation of the retry policy but in a real production application I would refactor that into an interface and inject it using Dependency Injection.

Now lets write some unit tests to cover following scenarios.

  • Happy case where everything runs smoothly and no exceptions happens.
  • Exception is thrown from our test but retry logic takes care of it.
  • Exception is thrown and all the retry attempts are exhausted.

I am going to use Moq to mock and in-memory list of orders and wire that up to EntityFrameWork DbSet so that when the service asks the OrderContext to get order records, it retrieves it from the in-memory list rather than going to a physical database. In the happy case scenario I will fetch 5 records from the in-memory database and process them and verify that the service bus Send() method is called exactly the same number of times as we have records in the DbSet. However in the second test I will just fetch only one record to verify that the service bus send method is called twice as the first call did failed due to the exception.

WhenUsingOrderService.cs

  [TestClass]
  public class WhenUsingOrderService
  {
      private Mock<IServiceBus> serviceBusMock;

      private Mock<IOrderContext> contextMock;

      private Mock<DbSet<Order>> dbSetMock;

      private OrderService orderService;

      [TestInitialize]
      public void Setup()
      {
          contextMock = new Mock<IOrderContext>();
          dbSetMock = new Mock<DbSet<Order>>();
          serviceBusMock = new Mock<IServiceBus>();
      }

      [TestMethod]
      public void ShouldBeAbleToSendMessage()
      {
          this.BuildDbSetMock(5);
          orderService = new OrderService(serviceBusMock.Object,
                                          contextMock.Object);

          orderService.Process();

          serviceBusMock.Verify(
                              x => x.Send(It.IsAny<BrokeredMessage>(),
                              "orderqueue"),
                              Times.Exactly(dbSetMock.Object.Count()));
      }

      [TestMethod]
      public void ShouldBeAbleToHandleMessagingCommunicationException()
      {
          bool firstTimeExecuteCalled = true;

          serviceBusMock
              .Setup(
                      x => x.Send(It.IsAny<BrokeredMessage>(),
                      "orderqueue"))
              .Callback(() =>
              {
                  if (firstTimeExecuteCalled)
                  {
                      firstTimeExecuteCalled = false;
                      throw new
                          MessagingCommunicationException("CommunicationException");
                  }
              });
          this.BuildDbSetMock(1);
          orderService = new OrderService(serviceBusMock.Object,
                                          contextMock.Object);

          orderService.Process();

          serviceBusMock.Verify(
                              x => x.Send(It.IsAny<BrokeredMessage>(),
                                          "orderqueue"),
                                          Times.Exactly(2));
      }

      [TestMethod]
      public void ShouldBeAbleToReachMaximumRetries()
      {
          int callCount = 1;
          serviceBusMock
                  .Setup(
                          x => x.Send(It.IsAny<BrokeredMessage>(),
                          "orderqueue"))
                  .Callback(() =>
                  {
                      if (callCount < 5)
                      {
                          callCount++;
                          throw new MessagingCommunicationException("CommunicationException");
                      }
                  });
          this.BuildDbSetMock(1);
          orderService = new OrderService(serviceBusMock.Object,
                                          contextMock.Object);
          try
          {
              orderService.Process();
          }
          catch (Exception ex)
          {
              Trace.WriteLine(ex.Message);
          }

          Trace.WriteLine(string.Format("Reached the maximun reties count of {0}", callCount));
          
          serviceBusMock.Verify(
                              x => x.Send(It.IsAny<BrokeredMessage>(),
                                          "orderqueue"),
                                          Times.Exactly(5));
      }

      private void BuildDbSetMock(int numberOfOrders)
      {
          var orders = OrderDataProvider.GetOrders()
                                        .Take(numberOfOrders)
                                        .AsQueryable();

          dbSetMock.As<IQueryable<Order>>()
                   .Setup(m => m.Provider)
                   .Returns(orders.Provider);

          dbSetMock.As<IQueryable<Order>>()
                   .Setup(m => m.Expression)
                   .Returns(orders.Expression);

          dbSetMock.As<IQueryable<Order>>()
                   .Setup(m => m.ElementType)
                   .Returns(orders.ElementType);

          dbSetMock.As<IQueryable<Order>>()
                   .Setup(m => m.GetEnumerator())
                   .Returns(orders.GetEnumerator());

          contextMock.Setup(x => x.Order)
                     .Returns(dbSetMock.Object);
      }
  }

As you can see, it’s a pretty slick test to cover up all the scenarios and I am using the Callback() method in our mock setup to create failure scenarios and throw exception. The complete source code is available at my skydrive.

Windows Service Bus Setup Guide

September 30, 2014 Leave a comment

In this post I am going to show you step by step installation of Windows Service Bus on a Windows 8.Windows Service Bus is the On-Premise version of Azure Service Bus and it is a nice way for companies to start using the on premise service bus specially in Australia where the Azure Data Center is still not available.I think it will also benefits businesses to see the potential of the service bus in terms of integration and they can start planning their systems for the cloud.This will make their system migration more manageable and less risky.

The good thing from a developer point of view is that with this setup guide you can do a quick proof of concept without having full-blown Windows Server 2012 and SQL Server and start showing its capability for building up an Enterprise Service Bus.

So lets first start with installing SQL 2012 Express and you can download a copy from here. Just run the installer and select all the features to be installed as shown below.

SQL Server all features

For all of my development work I prefer to have mixed mode authentication for SQL Server and in the wizard select the mixed mode authentication and continue with rest of the installation steps.If everything goes smoothly you will see the SQL Server installation is complete.

SQL Server successfully installed

Before we can start installing the windows service bus make sure you have Web Platform Installer (WPI) on your machine and I know if you are doing any .NET development you probably have it.Search for Service Bus from WPI search and you will see the following results.

search for service bus

Select the first and third option i.e. "Windows Azure Pack:Service Bus 1.1" and the update associated with this pack and follow the installation as shown below.

search for service bus

search for service bus

search for service bus

search for service bus

Now through your Windows Search look for "Service Bus" and you should be able to see two results as shown below.

Select Create a New Farm and continue.

search for service bus

It will show you the SQL Server instance running on your machine and click to test whether the connection to the database server is working or not.

Along with the "Service Bus Configuration" you also get "Service Bus Powershell" so lets open up the Service Bus Powershell and type in the following command.

PS C:\Program Files\Service Bus\1.1> Get-SBClientConfiguration

This will give you the connection string to your service bus and you are good to go. So now you have a service bus environment up and running on your developer machine.

Please follow my Azure Service Bus post to see how we can send and receive messages from the service bus and how to use the "Service Bus Explorer".

That is all for today folks.

Securing Web API using Azure Part – 3: Building the solution

Continuing with my Securing Web API series in this post I am going to start setting up the solution in visual studio and start building up the Simple Web Token Library. The idea behind this library is to build a reusable library which can be used with Azure ACS but can easily be extended for any identity provider which provides a simple web token based security.

In the first part we learned how to configure simple web tokens using Azure and in the second part we looked into designing interfaces which gives us a nice separation of concern.

Just to recap…

Securing Web API using Azure Part – 1: Simple Web Tokens (Azure Configuration)

Securing Web API using Azure Part – 2: Designing Interfaces (Web Token Orchestration)

So as usual I will start with File > New > ASP.Net Web Application and then select ASP.NET Web Api as shown below.

File new project web api

and now I am going to add a new class library “SimpleWebTokenLibrary” to the solution and create some folders as shown below.

Solution Structure

The structure is pretty straight forward and most of the interfaces, web token constant class, I have already covered in my previous post. The only interface which I haven’t covered is the ISettings interface which allows me to decouple the dependency on app config or web config. This may seems like a simple thing but it helps a lot when you are doing a lot of testing and don’t have to copy around your app settings into your test project.

ISettings.cs

public interface ISettings
{
    string GetSettings(string key);
}

and the implementation class just acts as a facade to the .net configuration manager class.

public class AppSettingsProvider : ISettings
{
    public string GetSettings(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }
}

Also to avoid passing magic string for config settings key I am going to encapsulate that into a settings name class for better readability of code and reducing the magic string code smell.

SettingNames.cs

public static class SettingNames
{
    public const string ServiceNamespace = "ServiceNamespace";

    public const string IdpHostName = "IdpHostName";

    public const string TrustedTokenPolicyKey = "TrustedTokenPolicyKey";

    public const string TrustedAudience = "TrustedAudience";

    public const string ServiceUserId = "ServiceUserId";

    public const string ServiceUserPassword = "ServiceUserPassword";

    public const string RealmScope = "RealmScope";
}

Now I am going to create another class in the Common folder call ResponseManager which will help generating the appropriate http response messages and the http header based on different scenarios.

ResponseManager.cs

public class ResponseManager
{
    public static Task<HttpResponseMessage> GenerateTaskResponse(
                    string message, 
                    CancellationToken cancellationToken)
    {
        return Task.Factory.StartNew(
                () => new HttpResponseMessage(HttpStatusCode.Unauthorized) 
                { 
                    Content = new StringContent(message) 
                },cancellationToken);
    }
}

And to encapsulate identity provider settings like host name, service namespace, relying application etc. I am going to create the following class.

IdentityProviderSettings.cs

public class IdentityProviderSettings
{
    public IdentityProviderSettings(ISettings settings)
    {
        IdpHostName = settings.GetSettings(SettingNames.IdpHostName);
        ServiceNamespace = settings.GetSettings(SettingNames.ServiceNamespace);
        TrustedAudienceValue = settings.GetSettings(SettingNames.TrustedAudience);
        TrustedSigningKey = settings.GetSettings(SettingNames.TrustedTokenPolicyKey);
    }

    public string TrustedAudienceValue { get; set; }

    public string TrustedSigningKey { get; set; }

    public string IdpHostName { get; set; }

    public string ServiceNamespace { get; set; }

    public string TrustedTokenIssuer
    {
        get
        {
            return string.Format(WebTokenConstant.UrlFormat, 
                                this.ServiceNamespace.ToLowerInvariant(), 
                                this.IdpHostName.ToLowerInvariant());
        }
    }
}

So now we are all done with our basic classes lets look into the WebTokenProvider class whose responsibility is to use the service username and password to build and OAuth request and retrieve a token which contains information like the encrypted token, relying party, identity provider etc.

WebTokenProvider.cs

public class WebTokenProvider : IWebTokenProvider
{
    private readonly ISettings settings;

    public WebTokenProvider(ISettings settings)
    {
        this.settings = settings;
    }

    public string GenerateToken()
    {
        var wrapPassword = settings.GetSettings(SettingNames.ServiceUserPassword);
        var wrapUsername = settings.GetSettings(SettingNames.ServiceUserId);
        var scope = settings.GetSettings(SettingNames.RealmScope);

        var client = new WebClient
        {
            BaseAddress = string.Format(
                            WebTokenConstant.UrlFormat,
                            settings.GetSettings(SettingNames.ServiceNamespace),
                            settings.GetSettings(SettingNames.IdpHostName))
        };

        var values = new NameValueCollection
        {
            { WebTokenConstant.WrapName, wrapUsername },
            { WebTokenConstant.WrapPassword, wrapPassword },
            { WebTokenConstant.WrapScope, scope }
        };

        var responseBytes = client.UploadValues(
                                    WebTokenConstant.WrapVersion09,
                                    WebTokenConstant.Post, values);

        var response = Encoding.UTF8.GetString(responseBytes);

        return HttpUtility.UrlDecode(
            response.Split('&')
            .Single(value => value.StartsWith(
                                    WebTokenConstant.WrapAccessToken,
                                    StringComparison.OrdinalIgnoreCase))
            .Split('=')[1]);
    }
}

The above implementation looks very straight forward and quite neat. As you can see all the extra effort we put around constants and removing magic string code smell paid off and it is quite easy to read and understand.

Now lets look into token validator class.

TokenValidator.cs

public class TokenValidator : ITokenValidator
{
    private readonly string trustedSigningKey;

    private readonly string trustedTokenIssuer;

    private readonly string trustedAudienceValue;

    public TokenValidator(IdentityProviderSettings identityProviderSettings)
    {
        trustedSigningKey = identityProviderSettings.TrustedSigningKey;
        trustedTokenIssuer = identityProviderSettings.TrustedTokenIssuer;
        trustedAudienceValue = identityProviderSettings.TrustedAudienceValue;
    }

    public bool Validate(string token)
    {
        var isExpired = this.IsExpired(token);

        return IsHMACValid(token, Convert.FromBase64String(this.trustedSigningKey))
               && (!this.IsExpired(token)
               && (this.IsIssuerTrusted(token)
               && this.IsAudienceTrusted(token)));
    }

    public Dictionary<string, string> GetNameValues(string token)
    {
        if (string.IsNullOrEmpty(token))
        {
            throw new ArgumentException();
        }

        return token.Split('&').Aggregate(
            new Dictionary<string, string>(),
            (dict, rawNameValue) =>
            {
                if (rawNameValue == string.Empty)
                {
                    return dict;
                }

                var nameValue = rawNameValue.Split('=');

                if (nameValue.Length != 2)
                {
                    throw new ArgumentException(
                                WebTokenConstant.InvalidFormEncoding);
                }

                if (dict.ContainsKey(nameValue[0]))
                {
                    throw new ArgumentException(
                                WebTokenConstant.DuplicateNameValuePair);
                }

                dict.Add(HttpUtility.UrlDecode(
                                        nameValue[0]), 
                                        HttpUtility.UrlDecode(nameValue[1]));
                return dict;
            });
    }

    private static ulong GenerateTimeStamp()
    {
        var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToUInt64(ts.TotalSeconds);
    }

    private bool IsAudienceTrusted(string token)
    {
        var tokenValues = this.GetNameValues(token);

        string audienceValue;

        tokenValues.TryGetValue(
                        WebTokenConstant.AudienceLabel, 
                        out audienceValue);

        return !string.IsNullOrEmpty(audienceValue) && 
                            audienceValue.Equals(
                                this.trustedAudienceValue, 
                                StringComparison.Ordinal);
    }

    private bool IsIssuerTrusted(string token)
    {
        var tokenValues = this.GetNameValues(token);

        string issuerName;

        tokenValues.TryGetValue(WebTokenConstant.IssuerLabel, out issuerName);

        if (string.IsNullOrEmpty(issuerName))
        {
            return false;
        }

        return issuerName.Equals(this.trustedTokenIssuer);
    }

    public static bool IsHMACValid(string swt, byte[] sha256HMACKey)
    {
        var swtWithSignature = swt.Split(new[] { "&" + WebTokenConstant.HmacSha256Label + "=" }, 
                                                    StringSplitOptions.None);

        if (swtWithSignature.Length != 2)
        {
            return false;
        }

        var hmac = new HMACSHA256(sha256HMACKey);

        var locallyGeneratedSignatureInBytes = hmac.ComputeHash(
                                              Encoding.ASCII.GetBytes(swtWithSignature[0]));

        var locallyGeneratedSignature = HttpUtility.UrlEncode(
                                        Convert.ToBase64String(locallyGeneratedSignatureInBytes));

        return locallyGeneratedSignature == swtWithSignature[1];
    }

    private bool IsExpired(string swt)
    {
        try
        {
            var nameValues = this.GetNameValues(swt);
            var expiresOnValue = nameValues[WebTokenConstant.ExpiresLabel];
            var expiresOn = Convert.ToUInt64(expiresOnValue);
            var currentTime = Convert.ToUInt64(GenerateTimeStamp());

            return currentTime > expiresOn;
        }
        catch (KeyNotFoundException)
        {
            throw new ArgumentException();
        }
    }
}

As you can see the above code is an anatomy of simple web tokens and we are parsing the return web token to retrieve information like whether the issuer is trusted or not, whether the encrypted token and the signing key matches or not etc.

Finally the TokenHeaderValidiator class.

TokenHeaderValdiator.cs

public class TokenHeaderValidator : ITokenHeaderValidator
{
    public bool Validate(HttpRequestMessage request, 
                         CancellationToken cancellationToken, 
                         out string headerValue, 
                         out string[] nameValuePair, 
                         out Task<HttpResponseMessage> taskHttpResponseMessage)
    {
        nameValuePair = new string[] { };
        headerValue = request.Headers
                             .GetValues(WebTokenConstant.Authorization)
                             .First();

        if (string.IsNullOrEmpty(headerValue))
        {
            taskHttpResponseMessage = ResponseManager.GenerateTaskResponse(
                                        WebTokenConstant.AuthorizationHeaderIsEmpty, 
                                        cancellationToken);
            return false;
        }

        if (!headerValue.StartsWith(WebTokenConstant.AuthorizationProtocol))
        {
            taskHttpResponseMessage = ResponseManager.GenerateTaskResponse(
                                        WebTokenConstant.InvalidToken, 
                                        cancellationToken);
            return false;
        }

        nameValuePair = headerValue.Substring(WebTokenConstant.AuthorizationProtocol.Length)
                                   .Split(new[] { '=' }, 2);

        if (nameValuePair.Length != 2 || nameValuePair[0] != WebTokenConstant.AccessToken || 
            !nameValuePair[1].StartsWith("\"") || !nameValuePair[1].EndsWith("\""))
        {
            throw new ApplicationException(WebTokenConstant.Unauthorized);
        }

        taskHttpResponseMessage = null;
        return true;
    }
}

The two classes TokenValidator and TokenHeaderValidator will be injected into the TokenValidationHandler class which will sit in the ASP.NET Web API pipeline and will make sure that the token is authentic and everything is right before passing the request to the ApiController. If you are not sure how this all fits together then please have a look at SWT Token Orchestration diagram I provided in the previous post..

I know it’s a lot of code but I hope to complete the solution in my next post. I’ll also upload the whole solution with some test to my skydrive so that it is easy to understand the code and relate the concepts in a more manageable way.

Securing Web API using Azure Part – 2: Designing Interfaces

June 30, 2014 1 comment

This is the part 2 of my 3 part series of Securing Web API using Azure .If you haven’t read the previous post then I highly recommend reading that one as in that post we look into security configuration using the Azure portal as well as developed some understanding of Simple Web Tokens (SWT Tokens).

The link to the first part is at:-

https://prashantbrall.wordpress.com/2014/05/31/securing-web-api-using-azure-part-1-security-web-tokens/

First,I am going to start with a high level overview of the orchestration behind the authentication process and then we will look into our design. This authentication process is bit complex and it involves the three different parties namely.

  1. Client:- Is the consumer of your service.
  2. Azure ACS:- Is the Identity Provider and will provide the SWT Token.
  3. ASP.Net Web Api:- Your hosted ASP.NET Web Api which will validate the SWT Token.

And to represent all the interaction between the above parties at different point of execution I have put together a quick swim lane diagram to show how it all fits together.

SWT Token orchestration

As you can see from the above swim lane diagram I have added some colors and legend to represent what interfaces/classes I am going to define later. Lets examine what are the different steps involved in the SWT Token authentication orchestration process.

      1) Consumer of the web api request a SWT Token from Azure ACS.
      2) Adds the returned SWT Token into the HTTP Request headers with an OAuth specification header.
      3) Consumer makes the call to rest end point i.e. the web api controller action.
      4) ASP.NET pipeline intercept the token request through TokenValidationHandler as it is derived from the Delegation Handler base class defined in the System.Net.Http namespace
      5) TokenValidationHandler delegates the header token to our custom TokenHeaderValidator class.
      6) If the header is in correct format the TokenValdationHandler delegates the token validation to our custom TokenValidator class.
      7) If the token is valid then the control goes back to ASP.NET Web api routing and the requested action is executed.
      8)The results are send back to the client as HTTP response.

Now coming to our design decision the first thing is to have a clear separation of concern and secondly the code is easy to unit test. This is the reason I decided to separate some of the responsibility like token header validation or token validation into its own classes. It is always a good practice to break code into smaller classes so that we follow the Single Responsibility Principle (SRP) and it makes easy to unit test the class.

Lets look into some of these interfaces and classes in their skeleton structure.

IWebTokenProvider.cs

public interface IWebTokenProvider
{
     string GenerateToken();
}

ITokenHeaderValidator.cs

public interface ITokenHeaderValidator
{
    bool Validate(
        HttpRequestMessage request,
        CancellationToken cancellationToken,
        out string headerValue,
        out string[] nameValuePair,
        out Task<HttpResponseMessage> taskHttpResponseMessage);
}

ITokenValidator.cs

public interface ITokenValidator
{
    bool Validate(string token);
}

TokenValidationHandler.cs

public class TokenValidationHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
    }
}

One of the code refactoring I like to do right in the beginning of coding is to remove magic string with string literal constants, this way the code is tidy and it is easy to change in just one class rather than searching and replacing in your entire code base. This client/web services interaction involves a lot of magic string and as a result of that I have wrapped all the constants inside a class as shown below.

WebTokenConstant.cs

public static class WebTokenConstant
{
    public const string Unauthorized = "Unauthorized";

    public const string Authorization = "Authorization";

    public const string AuthorizationHeaderIsEmpty = "Authorization header is empty";

    public const string AuthorizationProtocol = "WRAP ";

    public const string AccessToken = "access_token";

    public const string InvalidToken = "Invalid token";

    public const string AuthorizationHeaderWasNotSent = "The authorization header was not sent";

    public const string InvalidFormEncoding =
        "Invalid form encoded string - contains a name/value pair missing an = character";

    public const string DuplicateNameValuePair = "Repeated name/value pair in form";

    public const string UrlFormat = "https://{0}.{1}/";

    public const string WrapName = "wrap_name";

    public const string WrapPassword = "wrap_password";

    public const string WrapScope = "wrap_scope";

    public const string WrapAccessToken = "wrap_access_token=";

    public const string WrapVersion09 = "WRAPv0.9/";

    public const string Post = "POST";

    public const string AccessTokenHeader = "WRAP access_token=\"{0}\"";

    public const string ClientAuthorizationHeader = "Authorization";

    public const string IssuerLabel = "Issuer";

    public const string ExpiresLabel = "ExpiresOn";

    public const string AudienceLabel = "Audience";

    public const string HmacSha256Label = "HMACSHA256";
}

That’s it for now and in my next post I’ll cover all the implementation of generating and validating SWT Token.

Securing Web API using Azure Part – 1: Simple Web Tokens

May 31, 2014 3 comments

In this post I am going to talk about some of the nuances of securing web API using Azure and in order to keep my post short and sweet I am going to cover how to configure relying party and generating the SWT Token using Azure.

First I went and created a new ASP.NET Web API Project in Visual Studio 2013 and I am going to go my azure management portal to configure this newly created web application as a Relying Party. This configuration of Relying party is similar to my previous post Implementing Single Sign-On using Azure and I highly recommend to read it before you read this one.

Next I am going to add a service identity with username and password and the simple web token will be generated using this identity information for authentication.

Service Identity for the ASP.NET Web API Service

Now we are going add our ASP.NET Web API Service as relying party as shown below.

Configure our ASP.NET Web API as Relying Party.

As you can see above that I am using SWT as the token format and use the Windows Azure Access Control Service as my Identity Provider also we need to create a rule group so we click on “Rule groups” and add a description and save the rule.

Create rule group

Now we are going to map incoming claims to outgoing claims like we did in the previous post, except that instead of an Azure website it is an ASP.NET Web API Service.

Claim Mapping in Rule

As you can see above nothing special here all I am saying is that when an input identifier claims has a value of “ServiceUser” then we want to return “prashant.brall” to action claim value. This is done just for illustration purposes only and in real life application the claim mapping can be assigning a specific API Key per consumer so that this key is sent as part of the SWT token for additional verification purposes.

Now we are going to the “Application Integration” option of the Azure Access Control Service and going to use the OAuth WRAP (Web Resource Authorization Protocol) as shown below.

OAuth Web Resource Authorization Protocol.

Lets put it all together and see the SWT Token live in action and instead of writing a program to test I am going to use Fiddler as I really like to see what is going across the wire at the raw http post level.

Generate SWT Token using Fiddler

and this is how the SWT Token looks like when I open in notepad.

Returned SWT Token from Azure ACS

As you can see I have highlighted the return claim value as “prashant.brall” and some returned encrypted token which we will cover in the next post. Also below is raw http post using Fiddler in case you want to use in your own Access Control Service.

POST https://prashantbrall.accesscontrol.windows.net/WRAPv0.9/ HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: prashantbrall.accesscontrol.windows.net
Content-Length: 95
Expect: 100-continue
Connection: Keep-Alive

wrap_name=ServiceUser&wrap_password=*********&wrap_scope=http%3a%2f%2flocalhost%3a51388%2f

Implementing Single Sign-On (SSO) using Azure

April 27, 2014 3 comments

In this post I am going to show you how you can secure On-Premises or Cloud based web application using Windows Azure Active Directory which provides identity and access management capability in the cloud.And depending on your requirements you may have various On-Premises or Cloud Federation Identity Management scenarios and it is hard to cover all of them,but hopefully this post will give you some insight into the cloud based identity management and may be useful for your projects.

Before we deep dive into it I assume you have some idea of this type of identity management and are familiar with terms like Identity Provider, Relying Party, Windows Identity Foundation, WS-Federation and the orchestration behind such authentication process. If you are new to this topic and need a bit of background then I highly recommend reading the book Programming Windows Identity Foundation.

Lets browse to the Azure Management Portal and start configuring Windows Azure Active Directory (WAAD) by clicking New > App Service > Active Directory > Access Control > Quick Create and I am going to create a new namespace as shown below.

Access Control Namespace

Once the namespace is created click on "Manage" so that we can configure and administrate Identity Providers, Relying party, Federation Metadata Endpoint etc.

Manage Access Control namespace

Lets take a quick look into various options in Azure ACS and the first thing you will notice is that by default there are three major Identity Providers i.e. Microsoft, Google and Yahoo and if you like you can easily add Facebook or any WS-Federation based Identity Provider like your own Active Directory Federation Server.

List of Identity Providers

Additional Identity Providers such as Facebook or any WS-Federation Identity Provider

Last October I posted about creating a simple website using ASP.NET MVC and deploying it into Azure. I am going to use the same website and secure the website using Windows Azure ACS. If you haven’t read that post I recommend you to have a look so that you would know how to publish your website to Windows Azure.

First thing we are going to do is to add our website as relying party, which means that this website relies on the Windows Azure ACS to manage and authenticate user and the website doesn’t do the identity management and authentication on its own.

Add local website as relying party.

As you can see from the above screenshot I have just added my local IIS website as relying party, the realm and the return URL, this is just the configuration and the actual website will be created in Visual Studio later.

Add relying party additional information.

As you can see in above screenshot there is nothing special going on, we can see all the three providers for this relying party and we can see "Create new rule group" automatically selected. At this moment we will just click "Save" and will tackle the rule group next.

In the "rule group" we are going to specify how input claims in Windows Azure ACS are transformed into output claims so that our application can read these claims and work out additional task based on the user claims.

Generally all the incoming claims will map straight to out going claims and you don’t have to do anything special but I am just showing what can be done through configuration.

Edit rule group for HIIT system

On this "Edit rule group" page we will click on "Generate" and it will populated some rules as shown below.

Automatically generated claim rules

Now I am going to add one more rule and the reason behind this rule is that as part of Microsoft Live Id provider it only returns the nameidentifier claim value and doesn’t return a username due to security reasons. Where as providers like Google and Yahoo do provide the claim value name with user’s first name, last name as well as the email address. Anyways we need to fix this as
WIF manages behind the scenes orchestration of authentication and mapping claim principal to ASP.NET User principal.

If the claim name is blank and as part of the post authentication process when WIF tries to map the name to the User.Identity.Name we are going to get an exception and hence I am mapping the name identifier to the name claim value.

The above fix is done just for this end to end demonstration and in a real life application you have to take nameidentifier claim from Microsoft and use Windows Live Id APIs to get username and map it to the name claim programmatically.

generate rules mapping for windows live id.

and here is the final output with our custom rule for windows live id.

final rule group output with custom name mapping for windows live id.

Before we jump into programming last thing we have to do is to go to the "Application Integration" page and get the WS-Federation Metadata endpoint as shown below. We will copy this URL as we will need this endpoint when we configure the identity management for our application.

WS Federatiom metadata endpoint

Lots of configuration and looks a bit complicated but once you have grasp the concept it is quite straight forward. Lets start with File > New Project > Web Application > ASP.MVC and click on the "Change Authentication" button and a new dialog window will pop-up as shown below.

setup federation metadata in visual studio

Select "Organizational Account", choose the On-Premises options from the drop down and provide the federation metadata endpoint we copied in the above step.

After this configuration you can see there are some additional assembly and bunch of configuration added to the web.config. The one which stands out is a whole new section for system.identityModel which has all the WS-Federated related information.

Also you can see there are two new HTTP module added to the config and they are WSFederationAuthenticationModule and SessionAuthenticationModule which are part of the System.IdentityModel.Services assembly and sits under the ASP.Net pipeline.

Next thing we will do is to set the website to run with local IIS server as shown below.

Set to use local IIS

Lets browse to the website and you will see it will redirect to the federation login page and present you with which identity providers you wish to log in.

Federated Login page

I am going to choose yahoo as my identity provider and it will take me to the yahoo log in page.

Yahoo log in page

So I enter my credential and can see it is all good and it redirects back to my website but when the redirect completes we get this following error.

Server Error in ‘/HIIT’ Application.


ID3206: A SignInResponse message may only redirect within the current web application: ‘/HIIT’ is not allowed.

WIF known exception

This is a well-known issue with WIF and it is a very easy fix, all we have to do is to append a ‘/’ to the returned URL and here is the code.

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    private void Application_BeginRequest(object sender, EventArgs e)
    {
        if (string.Compare(Request.Path, Request.ApplicationPath, 
            StringComparison.InvariantCultureIgnoreCase) == 0
            && !Request.Path.EndsWith("/"))
        {
            Response.Redirect(Request.Path + "/");
        }
    }
}

And this time now when I log in it takes me back to home page without any exceptions and you can see the username on the top right hand corner.

HIIT system - logged in page

Lets look a bit deep into the whole WIF behind the scenes orchestration through fiddler. When I browse to the website the WSFederationAuthenticationModule kicks in and it does a 302 i.e. http redirect to the access control service as shown below.

Fiddler browse to the website

From here based on the identity provider I choose it takes me to their login page and if it is all good then it uses the return url to do another post authentication redirect.

Fiddler post authentication redirect

Of course this is just the tip of the iceberg and there is a lot going on under the cover, specially with WIF and the ASP.NET pipeline.

If you are interested in playing around with this project the source code is available at http://1drv.ms/1lR5uqb. Unzip the file, run Visual Studio as Administrator and on project properties under Web click "Create Virtual Directory".

The live version of the demo is available at https://prashantbrall.azurewebsites.net/

Enjoy !!!

On-Premises Cloud Integration

I am working on a very interesting project which is a hybrid cloud application and runs on premises and in the cloud. The bulk of system is in the cloud with service bus orchestration and the Azure website however we have one windows service which runs on the client premise i.e. in client’s DMZ and polls for a specific FTP folder and then sends the message to the cloud service bus. If you are new to Azure Service Bus I recommend to read my previous post on Azure Service Bus.

One of the major gotcha was that our windows service when tested from our internal network was able to send the message to Azure Service Bus without any problem but when the service was deployed in the clients DMZ we were getting some problem related to net TCPIP binding. I was bit confused and decided to replicate the problem and then figure out what is going on under the hood.

So the exception was related to network socket exception and this is what the exception was.


Could not connect to net.tcp://prashantbrall.servicebus.windows.net:9354/. The connection attempt lasted for a time span of 00:00:00.0140062. TCP error code 10013: An attempt was made to access a socket in a way forbidden by its access permissions xx.xx.xx.127:9354.

First thing what I did was to create a firewall rule to block the port 9354 and see what happens, so I went to windows firewall advance properties and on outbound rule right clicked and select new rule and added the rule as shown below.

port block general properties

firewall port 9354 configuration

I name the rule with a prefix “—” so that it is always on the top of the firewall rule, otherwise it is hard to scroll through so many firewall rules to find out which one you just added.

Windows Firewall port 9354 added rule.

As soon as I did that and I tried sending a message to the Azure Service Bus and I got the same exception. So I figure out the port was blocked on the client’s DMZ and it would take a lot of effort/meeting and infrastructure change request to finally get the port open. So I decided that let’s use the code and try to use the HTTP binding rather than the TCPIP binding and apparently it was much easier than I thought, in fact it is just one line of code.

ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

Just add this code before you create a QueueClient object and below is the complete code.

Program.cs

class Program
{
    const string QueueName = "OrderQueue";
    static void Main(string[] args)
    {
        try
        {
            ServiceBusEnvironment.SystemConnectivity.Mode = 
                                    ConnectivityMode.Http;

            var queueClient = QueueClient.Create(QueueName);
            SendMessage(queueClient);
            while (true)
            {
                var message = queueClient.Peek();
                
                if (message != null)
                {
                    Thread.Sleep(10000);
                    var orderMessage = message.GetBody();
                    Console.WriteLine("Order with Id = {0} and Qty = {1} " + 
                            "has been received..",
                            orderMessage.OrderId, 
                            orderMessage.Qty);
                }
            }
        }
        catch (Exception ex)
        {
           Console.WriteLine(ex.Message + "\n" + ex.StackTrace);
        }

        Console.ReadLine();
    }

    static void SendMessage(QueueClient queueClient)
    {
        var newOrder = new OrderMessage
            {
                OrderId = 123, Qty = 20
            };

        queueClient.Send(new BrokeredMessage(newOrder));
    }
}

Happy Azuring !!!