Thinktecture.IdentityModel.Hawk NuGet Package

With Thinktecture.IdentityModel V.Next out, Hawk authentication implementation in Thinktecture IdentityModel gets its own NuGet package. It is currently in pre-release and here is the NuGet Gallery link. The OWIN middleware code that has been a part of the samples is now moved into Thinktecture.IdentityModel and is a part of this NuGet package.

Let’s now see how we can create a simple web API (ValuesController, of course) and OWIN-host it with hawk authentication plugged in using the OWIN middleware that is part of this NuGet package.

Create a console application and add the Thinktecture.IdentityModel.Hawk package using PM Console like so: Install-Package Thinktecture.IdentityModel.Hawk -Pre. Also, add Microsoft.AspNet.WebApi.OwinSelfHost and Microsoft.Owin.Security, so that your packages.config is like this.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi.Client" version="5.0.0"
        targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.0.0"
        targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.0.0"
        targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.OwinSelfHost" version="5.0.0"
        targetFramework="net45" />
  <package id="Microsoft.Owin" version="2.0.1" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.HttpListener" version="2.0.1"
        targetFramework="net45" />
  <package id="Microsoft.Owin.Hosting" version="2.0.1"
        targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.0.1"
        targetFramework="net45" />
  <package id="Newtonsoft.Json" version="4.5.11"
        targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />
  <package id="Thinktecture.IdentityModel.Core" version="1.0.0-beta1"
        targetFramework="net45" />
  <package id="Thinktecture.IdentityModel.Hawk" version="1.0.0-beta1"
        targetFramework="net45" />
</packages>

And, here is the Program class of the console app.

using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Thinktecture.IdentityModel.Hawk.Core;
using Thinktecture.IdentityModel.Hawk.Core.Helpers;
using Thinktecture.IdentityModel.Hawk.Owin;
using Thinktecture.IdentityModel.Hawk.Owin.Extensions;

namespace Your.Namespace.Goes.Here
{
    class Program
    {
        static void Main(string[] args)
        {
            const string baseUrl = "http://localhost:12345/";

            using (WebApp.Start<Startup>(new StartOptions(baseUrl)))
            {
                Console.WriteLine("Press Enter to terminate.");
                Console.Read();
            }
        }
    }

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var credentialStorage = new List<Credential>()
            {
                new Credential()
                {
                    Id = "dh37fgj492je",
                    Algorithm = SupportedAlgorithms.SHA256,
                    User = "Steve",
                    Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn"
                }
            };

            var options = new Options()
            {
                ClockSkewSeconds = 60,
                LocalTimeOffsetMillis = 0,
                CredentialsCallback = (id) => credentialStorage
                                        .FirstOrDefault(c => c.Id == id)
            };

            app.UseHawkAuthentication(
                            new HawkAuthenticationOptions(options));

            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                "DefaultWebApi",
                "{controller}/{id}",
                new { id = RouteParameter.Optional });

            app.UseWebApi(config);


        }
    }

    [Authorize]
    public class ValuesController : ApiController
    {
        public HttpResponseMessage Get()
        {
            return Request.CreateResponse<string>(HttpStatusCode.OK,
                                       "Hello, " + User.Identity.Name);
        }

        public HttpResponseMessage Post([FromBody]string name)
        {
            string message = String
                   .Format("Hello, {0}. Thanks for flying Hawk", name);
            return Request.CreateResponse<string>(HttpStatusCode.OK,
                                                                message);
        }
    }
}

With that, if you run the console app, your web API is OWIN-hosted and ready to receive requests. Create another console app to act as the client and send a request or two to the web API. Add Thinktecture.IdentityModel.Hawk and Microsoft.AspNet.WebApi.Client packages. Here is the Program class of the client.

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using Thinktecture.IdentityModel.Hawk.Client;
using Thinktecture.IdentityModel.Hawk.Core;
using Thinktecture.IdentityModel.Hawk.Core.Helpers;
using Thinktecture.IdentityModel.Hawk.WebApi;

namespace Your.ClientApp.Namespace.Goes.Here
{
    class Program
    {
        static void Main(string[] args)
        {
            string uri = "http://localhost:12345/values";

            var credential = new Credential()
            {
                Id = "dh37fgj492je",
                Algorithm = SupportedAlgorithms.SHA256,
                User = "Steve",
                Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn"
            };

            var options = new ClientOptions()
            {
                CredentialsCallback = () => credential
            };

            var handler = new HawkValidationHandler(options);
            HttpClient client = HttpClientFactory.Create(handler);

            var response = client.GetAsync(uri).Result;
            Console.WriteLine(
                        response.Content.ReadAsStringAsync().Result);

            response = client.PostAsJsonAsync(uri, credential.User)
                                                             .Result;
            Console.WriteLine(
                        response.Content.ReadAsStringAsync().Result);

            Console.Read();
        }
    }
}

HawkValidationHandler in the client side takes care of adding the necessary Authorization header in hawk scheme and the Hawk OWIN middleware in the server side does the authentication. With the NuGet packages in place, app.UseHawkAuthentication(new HawkAuthenticationOptions(options)); line is all it is needed to get the OWIN middleware execute in the pipeline and authenticate the requests. Of course, you will need to create the Options object and specify your options. For the full sample, go to https://github.com/thinktecture/Thinktecture.IdentityModel/tree/master/samples/Hawk.

Advertisements

One thought on “Thinktecture.IdentityModel.Hawk NuGet Package

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s