Monthly Archives: November 2013

Azure Application Framework

As I’ve worked with Azure over the last 18 months there is a bunch of plumbing I’ve found to be commonplace but with which, other than effort, their is little inherent intellectual property value. Examples include dependency injectable patterns for resource access, configuring components across multiple projects and servers, deployment, separation of concerns, sending emails, fault diagnosis and a management dashboard, to name just a few.

The AccidentalFish.ApplicationSupport framework is my attempt to bring solutions to these common requirements into a reusable package in order to bootstrap my own, and hopefully others, future work. The code is all purpose written specifically for this framework and with reuse in mind and it’s heavily focussed on an asynchronous programming model.

Different parts of the framework are at different states of maturity but moving quite quickly as since deciding to author this code as a framework I’m using it in this form in two personal projects, one of which is the previously alluded to companion application for this website.

The framework itself continues to evolve as I continue to learn more about Azure and as Azure itself moves forward and it’s covered by the permissive MIT License so is free to use in open source and commercial applications. The source code can be found on GitHub.

Documentation is currently scant but that is a priority for me – I hope I can provide documentation to a similar standard as I have written for Simple Paging Grid as I think that’s played a big part in it’s modest success.

I’m publishing early basically so some friends can make use of it and so that I can pull it out of my applications to manage separately, but if you have any feedback let me know. Bug fix submissions greatly welcomed!

And finally for those who are wandering – Accidental Fish is the moniker (and UK Limited Company) under which I publish applications on the iOS App Store and under which I place the copyright for most of my open source work. Somehow using it in namespaces seems less egotistical than my own name or initials, though as I’m the sole employee it is me and I am it.

How To: Use Azure Table Storage as an OAuth Identity Store with Web API 2

In my previous post I looked at how to register, login and authenticate using the new OWIN based ASP.Net architecture underpinning MVC 5 and Web API 2. The default website provided was configured to use SQL database which is why we needed to configure a SQL Database within Azure as we deployed our website.

There’s a fair chance, if you’re experienced with Azure, that you’re wondering if you can swap that out and use Table Storage, fortunately one of the improvements in this latest version of ASP.Net is to better abstract storage away from management.

There is however a fair bit of leg work to doing so. I’m going to firstly touch on how you go about this, then look at the NuGet package I’ve put online (source code in GitHub) that means you don’t have to do this leg work!, and finally we’ll look at the changes you would need to make in the Web API 2 sample project we introduced in the previous post. I’m going to make reference to that code so you can quickly grab it from GitHub if that’s useful.

1) Implementing a New Identity Store

The clue to how to go about this can, again, be found at the top of the Startup.Auth.cs file in the App_Start folder:

Step1

A factory function is assigned and asked to return a user manager and a user store.

The UserManager is a core class of the identity framework (Microsoft.AspNet.Identity.Core) and works with classes that describe users through the IUser interface (another core class) and persists them with implementations of the IUserStore interface.

The core identity framework provides no storage implementation and the UserStore class that is being instantiated here is provided by Microsoft.AspNet.Identity.EntityFramework as is the IdentityUser class.

In fact if we look at the Microsoft.AspNet.Identity.Core assembly we can see it’s really very focussed on managing abstract interfaces:

Step2

It’s not difficult to see where we’re going at this point – to implement our own store we need to provide implementations for a number of interfaces. If we want to replicate full local identity management in the same way as the Entity Framework supplied implementation then realistically we need to implement most of the interfaces shown above – IRole, IRoleStore, IUser, IUserClaimStore, IUserLoginStore, IUserPasswordStore, IUserRoleStore, IUserSecurityStampStore and IUserStore.

That’s not as daunting as it sounds as most of the interfaces are quite simple, for example IUserStore:

Step3

The remaining interfaces also follow this asynchronous CRUD pattern and are fairly simple to implement, here’s the Entity Framework implementation for CreateAsync:

Step4

And by way of contrast here’s a Table Storage implementation:

Step5

Pretty much the same I think you’ll agree, however it’s still a lot of boilerplate code to write so I’ve wrapped it into a NuGet package called AccidentalFish.AspNet.Identity.Azure which can also be found on GitHub.

2) Using AccidentalFish.AspNet.Identity.Azure

To get started either download the package from NuGet using the package manager in Visual Studio or download the source from GitHub and attach the project to your solution. The NuGet package manager console to install the package is:

Install-Package accidentalfish.aspnet.identity.azure

You can use the package in commercial or open source projects as it’s published under the permissive MIT license though as ever I do appreciate an email or GitHub star if it’s useful to you – yes I’m that vain (and I like to hear about my code being used).

Once you’ve got the package installed you’ll find there is still a little work to do to integrate it into your Web API 2 project as although the Microsoft.AspNet.Identity framework is nice and clean it seems that whoever put the Web API 2 project template didn’t think it made sense to keep a nice level of abstraction and have tied it tightly to the Entity Framework implementation in a few places.

However it’s not too onerous (just a couple of steps) and I’ve built the package with replacement in mind. To help I’ve included the Web API 2 project from my previous post and commented out the old Entity Framework code that bleeds into the MVC host site. I’ll walk through these changes below.

Firstly we need to visit the Startup.Auth.cs file and make three changes at the start:

Step6

1) Update the factory assignment to return a UserManager that manipulates users of type TableUser and users a data store of type TableUserStore. Pass it your Azure connection string. The constructor is overloaded with parameters for table names and whether or not to create them if they don’t exist – by default it will.

2) Replace the ApplicationOAuthProvider with a generic version of it contained within the package. This code is exactly the same but replaces the fixed IdentityUser types with a generic (you can see what I was referring to in regard to the template – this ought to have been this way out of the box).

3) Update the declaration for the factory to return a UserManager manipulating users of type TableUser.

At this point we’ve done the bulk of the OAuth work but unfortunately the MVC AccountController also has a, needless, hard dependency on the Entity Framework library so we need to sort that out. To do this either go through the class and replace the type declarations of IdentityUser and IdentityUserLogin with TableUser and TableUserLogin respectively. Alternatively you can “cheat” and remove the Microsoft.AspNet.Identity.EntityFramework using reference and add a pair of aliases:

Step7

That’s it you’re done. Identity information should now be persisted in Azure Table Storage.

I’ll be doing some more work on this package in the coming weeks – I want to test it at scale and I know I need to build at least one index for one of the IUserStore calls which queries in the reverse way to which the partition and row key are set up: I’ve tried to set up the partition and row keys for the most commonly used methods.

If you find any problems or have any feedback then please let me know.

 

How To: Register and Authenticate with Web API 2, OAuth and OWIN

The latest release of Asp.Net introduces some fundamental architectural changes that have a significant effect on frameworks such as MVC and Web API as Asp.Net now sits on top of the OWIN stack.

As part of this change Microsoft have yet again changed the authentication and authorisation model. Yes you still use the Authorize attribute within your MVC and Web API controllers but the workflow around authentication has been rejigged considerably.

If, like me, you have a penchant for writing mobile apps that consume Web API based services hosted in Azure chances are you’ll want to register and authenticate with your services from the device. This is really simple to achieve with Web API 2 and OWIN, in fact it’s all in place out of the box, but the trouble is that it’s barely documented.

Having spent a morning going through significant pain figuring this out I’ve put this How To guide together to show how to do this. For added fun I’ve built the client in Xamarin as an iOS application but the approach will work on any platform including from Windows 8, JavaScript, whatever you like. In fact the C# code that I outline below can be lifted straight from the Xamarin project and dropped into any other C# application. If you want to skip ahead to the example code it can be found on GitHub.

We’ll get started by creating a Web API project. In Visual Studio create a new solution and pick ASP.Net Web Application. On the ASP.Net project type page select the Web API template and change the authentication type to Individual User Accounts:

Step1

Inside this project will be a API controller called ValuesController – this is the normal Web API sample. You’ll notice the class has an Authorize attribute which will protect it from anonymous access. Your exact URL will vary depending on what port IIS Express has been set up with but enter the URL to get the values from the controller (in my case http://localhost:5287/api/Values) and you should see some XML (I’m using Chrome):

<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>

So far so good – we need to be logged in to access the API which is what we want. In order to login first we’re going to need to register a user.

If you visit the help page for the API (for example http://localhost:5287/Help) you’ll see that there is an Account API that fronts lots of interesting methods – one of which is Register:

Step2

So if we post the right data to that action we should be able to register an account and believe it or not we’re done with the website so publish it to a free website in Azure and take note of the URL you’ve dropped it on. I recommend using VS2013 and the latest version of the Azure SDK (2.2 at the time of writing) as the tools make this really simple. The only real gotcha to watch out for is to point your website at a SQL Database rather than the local file approach that will be configured within your website. To point to a real database just make sure that you pick, or create as in the example below, a real database server:

Step4

And then make sure that the DefaultConnection is updated:

Step5

With the website deployed and ready it’s time to create an iOS application. You can use either Xamarin Studio or the Visual Studio plugin. I used the Hello World template for my application and targetted iOS 7 which I then reworked to give me the user interface below:

ReworkedUI

I’m not going to spend too much time talking about the user interface of the Xamarin application (it’s not really the focus of this How To) but all I really did was update it with the user interface above and added the Json.Net component from the Xamarin Component Store (if you’re from the .Net world – think NuGet, looking forward to a PCL version of Json.Net!). None of the connectivity code was Xamarin specific.

For the  application to register a user it needs to send the right model to the Register action we located earlier. The website contains a class called RegisterBindingModel which we’re going to replicate in our Xamarin application (in a production application I recommend pulling these models out into a Portable Class Library rather than copying and pasting code) in a class called RegisterModel:

class RegisterModel
{
    public string UserName { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
}

We’re going to form up a HttpWebRequest with the registration information and send it to the controller. As long as we don’t get a HTTP error then registration has been successful. I’ve wrapped this in a class called RegisterServiceClient:

class RegisterService
{
    public async Task Register(string username, string password, string confirmPassword)
    {
        RegisterModel model = new RegisterModel
        {
            ConfirmPassword = confirmPassword,
            Password = password,
            UserName = username
        };
 
        HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}api/Account/Register", Constants.BaseAddress)));
        request.Method = "POST";
        request.ContentType = "application/json";
        request.Accept = "application/json";
        string json = JsonConvert.SerializeObject(model);
        byte[] bytes = Encoding.UTF8.GetBytes(json);
        using(Stream stream = await request.GetRequestStreamAsync())
        {
            stream.Write(bytes, 0, bytes.Length);
        }
 
        try
        {
            await request.GetResponseAsync();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}

That will register user but how do we log in. If we refer back to our websites API help page although there are a lot of interesting looking methods there is no Login method.

This is where OWIN comes in. If you take a look at the code that was generated for the website you’ll see that in MVC 5 / Web API 2 there is a new file in the solution (compared to MVC 4) called Startup.Auth.cs:

Step7

This is where the configuration for authentication and authorization takes place with OWIN and the real interesting bit for us is the section towards the top where OAuthOptions are set:

Step8

Essentially OWIN is running an OAuth authentication server within our website and setting up OAuth endpoints for us. I’m not going to dwell on OAuth but essentially to authenticate we need to request a token using our username and password to identify ourselves and then in subsequent service calls supply this token as a HTTP header in the request.

The token end point we need to call can be seen in the image above: it’s /Token. We need to pass it the username and password and also an additional piece of information: the grant type. We need the grant type to be password. The endpoint responds to form data and we make the call as shown below:

class LoginService
{
    public async Task Login(string username, string password)
    {
        HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}Token", Constants.BaseAddress)));
        request.Method = "POST";
 
        string postString = String.Format("username={0}&amp;password={1}&amp;grant_type=password", HttpUtility.HtmlEncode(username), HttpUtility.HtmlEncode(password));
        byte[] bytes = Encoding.UTF8.GetBytes(postString);
        using (Stream requestStream = await request.GetRequestStreamAsync())
        {
            requestStream.Write(bytes, 0, bytes.Length);
        }
 
        try
        {
            HttpWebResponse httpResponse =  (HttpWebResponse)(await request.GetResponseAsync());
            string json;
            using (Stream responseStream = httpResponse.GetResponseStream())
            {
                json = new StreamReader(responseStream).ReadToEnd();
            }
            TokenResponseModel tokenResponse = JsonConvert.DeserializeObject(json);
            return tokenResponse.AccessToken;
        }
        catch (Exception ex)
        {
            throw new SecurityException("Bad credentials", ex);
        }
    }
}

In response to a successful call on the Token endpoint the OAuth server will return us JSON data that includes the access token and some additional information, I’m deserializing it into a class called TokenResponseModel but the thing we’re really interested in is the access token. The full response is modelled like this:

class TokenResponseModel
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }
 
    [JsonProperty("token_type")]
    public string TokenType { get; set; }
 
    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }
 
    [JsonProperty("userName")]
    public string Username { get; set; }
 
    [JsonProperty(".issued")]
    public string IssuedAt { get; set; }
 
    [JsonProperty(".expires")]
    public string ExpiresAt { get; set; }
}

Now we’ve got that access token we can use it against any future requests that require authentication and authorization – so finally we can return to our attempt to access the ValuesController. We need to supply the access token in a HTTP header called Authorization and the value for the header must have the format “Bearer {token}”, the space between Bearer and the token is significant – if you miss it authorization will fail. Here’s how we use the token to retrieve the list of values from the controller:

class ValuesService
{
    public async Task&lt;IEnumerable&gt; GetValues(string accessToken)
    {
        HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}api/Values", Constants.BaseAddress)));
        request.Method = "GET";
        request.Accept = "application/json";
        request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken));
 
        try
        {
            HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
            string json;
            using (Stream responseStream = httpResponse.GetResponseStream())
            {
                json = new StreamReader(responseStream).ReadToEnd();
            }
            List values = JsonConvert.DeserializeObject&lt;List&gt;(json);
            return values;
        }
        catch (Exception ex)
        {
            throw new SecurityException("Bad credentials", ex);
        }
    }
}

Obviously I’ve cut out a lot of error handling and have taken some short cuts to stay focussed on the topic but really it’s quite simple, just appallingly documented at the moment.

You can find the full code on GitHub.