<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Reid Peryam - Software Development Blog]]></title><description><![CDATA[Reid Peryam - Software Development Blog]]></description><link>http://Blaug.azurewebsites.net/</link><generator>Ghost 0.5</generator><lastBuildDate>Wed, 15 Apr 2026 21:49:11 GMT</lastBuildDate><atom:link href="http://Blaug.azurewebsites.net/author/reid-peryam/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Transformation @ Microsoft]]></title><description><![CDATA[<p><img src="http://blaug.azurewebsites.net/content/images/2014/Mar/logos.png" alt="Microsoft Logos"></p>

<p>I wanted to offer my take on important changes I perceive at Microsoft.</p>

<h3 id="pastelbecamepasse">Pastel Became Passe</h3>

<p>Microsoft is evolving to stay relevant within a technological oligarchy ruled alongside Google, Apple, Amazon, Facebook. Like the movie, <a href="http://en.wikipedia.org/wiki/Miami_Vice_(2006_film)">Miami Vice</a>, whose protagonists Sonny and Tubbs were transformed as gritty, cerebral and laconic -- in stark contrast to their original, television counterparts -- Microsoft realized that <em>Yesterday's Microsoft</em> would not survive <em>Today</em>.  Beyond survival, in order to thrive the company must transform.</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Mar/405010954_593f442ebe.png" alt="Then vs. Now" title=""></center></p>

<p>And indeed <a href="http://en.wikipedia.org/wiki/Microsoft_Bob">Bob</a>, <a href="http://en.wikipedia.org/wiki/Office_Assistant">Clippy</a>, <a href="http://jamesinlogistics.blogspot.com/2011/10/adventures-with-microsoft-xp-search-dog.html">Rover</a> and the faceless, androgenous, interspecific <a href="http://goo.gl/cQhoL4">progenitor that spawned them</a> were euthanized; collateral damage of self-reinvention. Here's a highlight of other changes at Microsoft that separately may go unnoticed but together redefine the company's direction moving forward:</p>

<h4 id="thetreeisntfarfromtheapple">The Tree Isn't Far from the Apple</h4>

<p><a href="http://www.flatvsrealism.com/">Microsoft finally beat Apple at design (once)</a> and is <a href="http://www.microsoft.com/design/">refocusing efforts</a> to improve user experience -- comparatively its most-glaring software deficiency. Is Microsoft also stumbling along the way? <a href="http://goo.gl/FGZaC2">Undoubtedly</a> -- while also improving. </p>

<h4 id="ammunitionandnowguns">Ammunition and Now Guns</h4>

<p>With the <a href="http://goo.gl/K9lwnb">acquisition</a> of Nokia's devices and service division and release of the <a href="http://www.microsoft.com/surface/en-us">Surface</a> family of consumer hardware products Microsoft is suddenly <a href="http://goo.gl/BbfIFN">also a devices company</a>. While still lagging behind the likes of Samsung and Sony, it is playing ball on the same field as the big leaguers.</p>

<h4 id="sharingiscaring">Sharing is Caring</h4>

<p><a href="http://www.microsoft.com/opensource/directory.aspx">Microsoft has embraced open source software development</a> as a value. More on this and why it maters later.</p>

<h4 id="theirfootinmoredoors">Their Foot In More Doors</h4>

<p><a href="http://goo.gl/LAhyGM">Microsoft is invading living rooms</a> -- Xbox continues to position the company within the increasingly unsettled consumer entertainment market prior to the (inevitable) collapse of cable TV. <a href="http://support.microsoft.com/kb/2748075/en-us">The acquisition of Yammer</a> affords Microsoft social networking capabilities within B2B which it already dominates; heretofore a space that LinkedIn has championed uncontested. </p>

<h4 id="epluribusunum">E Pluribus Unum</h4>

<p>Even Microsoft products and brands, a perpetually disparate spaghetti, are transcending into integrated service offerings (<a href="http://office.microsoft.com/en-us/pc/microsoft-office-365-FX104129952.aspx">Office</a>, <a href="http://www.visualstudio.com/en-us/products/visual-studio-online-overview-vs.aspx">Visual Studio</a> are now available on the Cloud -- <a href="http://www.gamespot.com/articles/xbox-one-cloud-servers-absolutely-essential-to-titanfall/1100-6418222/">XBox on Azure</a>, <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681690(v=vs.105).aspx">common UX between Windows phone and Windows</a> etc) that play nicely with eachother. Additionally, at long last the branding of these product offerings is consistent! </p>

<p><center> <br>
<img src="http://blaug.azurewebsites.net/content/images/2014/Mar/BrandingTransition-1.png" alt="Microsoft Branding">
</center></p>

<h4 id="stevestevewho">"Steve? Steve Who?"</h4>

<p><a href="http://en.wikipedia.org/wiki/Satya_Nadella">Microsoft hired a new CEO</a> - only the third in its history. Gone is the bombastic, odd Steve Ballmer; in his place a pragmatic, 'more efficiently designed' engineer Satya Nadella. </p>

<p>In Summary the transformative reinvention of Microsoft, a company long considered awkward and uncool, is occuring: </p>

<p><center>  </center></p>

<iframe width="520" height="415" src="http://www.youtube.com/embed/WvoKFiDTQx4" frameborder="0" allowfullscreen></iframe>  

<p></p>

<h4 id="theresjustonemorething">There's Just One More Thing...</h4>

<p>Is this perspective into the transformation of Microsoft profound? No. However, I believe the changes the company is making are deserving of notice. This capable, overlooked Microsoft might just be the Coloumbo that solves the mystery of how to succeed across a myriad of competitive landscapes where others have not; the Cladius that ascends to power, the <a href="https://www.youtube.com/watch?v=dGdQ4HhyojY">Steve Urkel who hits a game winner</a>.</p>

<p><center> <br>
<img src="http://blaug.azurewebsites.net/content/images/2014/Mar/ColumboCladius.png" alt="columbo and Cladius">
</center></p>

<p>My next post will center upon developing enterprise software on Microsoft's tech stack from the context of these evolving paradigms.</p>]]></description><link>http://Blaug.azurewebsites.net/dfsdf/</link><guid isPermaLink="false">3501214d-d59b-499b-9ea5-54a4ad0c0c3e</guid><dc:creator><![CDATA[Reid Peryam]]></dc:creator><pubDate>Thu, 13 Mar 2014 21:10:35 GMT</pubDate></item><item><title><![CDATA[Integrating Azure Active Directory Security Into NancyFx (part I)]]></title><description><![CDATA[<h2 id="introduction">Introduction</h2>

<p>This is the first in a series of posts focusing on two .Net development technologies: Azure Active Directory (<a href="http://www.windowsazure.com/en-us/documentation/services/active-directory/">AAD</a>) and NancyFx (aka <a href="http://nancyfx.org/">Nancy</a>). Nancy  has emerged as a scalable web-development framework affording what it labels the "Super Duper Happy Path" (SDHP) for simplistic creation of web applications. AAD is a Azure/cloud-hosted <a href="http://en.wikipedia.org/wiki/Directory_service">directory service</a> supplying authentication as a service (<a href="http://en.wikipedia.org/wiki/Software_as_a_service">SaaS</a>). We are securing a Nancy web application with AAD; the code presented in this series is available <a href="https://github.com/TheFastCat/AzureActiveDirectoryWithNancyFxStatelessAuthentication">here</a>.</p>

<ul>
<li>In <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">Part I: Azure Active Directory Configuration</a> we configure a new AAD tenant for our use</li>
<li>In <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part2">Part II: AAD From a Nancy Web Application</a> we take the first steps to integrate a Nancy web application with AAD</li>
<li>In <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part3">Part III: Nancy Statless Authentication With AAD</a> we implement Nancy's stateless authentication to leverage AAD</li>
</ul>

<h2 id="partiazureactivedirectoryconfiguration">Part I: Azure Active Directory Configuration</h2>

<p>This post covers the setup and configuration of a new Azure Active Directory account and tenant to support our use within a new web application.</p>

<h3 id="authenticatingusers">Authenticating Users</h3>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/mclovin.jpg" alt="mclovin" title=""></center></p>

<p>Verifying that a person who <em>wants</em> access to secured resources <em>should be allowed access</em> typically necessitates substantial development effort to support; within the context of a web application:</p>

<ol>
<li>First we would create a UI view to support accepting a user id and password.  </li>
<li>Next we might create a database repository holding all authorized user names and passwords against which to verify those credentials.  </li>
<li>Finally our application requires logic to determine whether or not this particular user has required authorization and handle each case accordingly.</li>
</ol>

<p>...or instead we can offload this work to AAD -- a cloud-hosted directory service which can manage such burdens as a proxy on behalf of our application. Think of AAD as the security officer blocking access to a Customs checkpoint within the international arrival section of an airport. Without valid proof of your identification (passport) as well as authorization to enter the country (ie citizenship, travel visa etc) you will not be permitted entry. In similiar manner AAD can restrict access to our application.</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/immigrationOfficer.jpg" alt="AAD = Immigration officer" title=""></center></p>

<p>As an added incentive this service is practically free (<a href="http://www.windowsazure.com/en-us/pricing/details/active-directory/">seriously</a>!).</p>

<h3 id="configuringanazureactivedirectoryaccountandtenant">Configuring an Azure Active Directory Account and Tenant</h3>

<p>(Before continuing be sure you have an active <a href="http://www.windowsazure.com/en-us/overview/what-is-windows-azure/?WT.mc_id=azurebg_us_sem_bing_br_solutions_nontest_whatisazure">Windows Azure</a> account)</p>

<p>In order for AAD to handle authentication for our application we need to create an <a href="http://technet.microsoft.com/en-us/library/jj573650.aspx">AAD tenant</a> within which applications and authorized users that access them are configured. An AAD tenant can be conceptualized as an ecosystem containing users and applications that interact. Users within the tenant have access to applications within that tenant; furthermore such applications may be configured to allow interactions between eachother as trusted clients. </p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/tenant_JPG.jpg" alt="ecosystem" title=""></center></p>

<p>An important concept to understand is that in order for a user or application to interact with components of the tenant ecosystem it must first exist within it. Another useful way to conceptualize a tenant as a domain - in fact an AAD tenant is often reffered to as an (Active Directory) domain.</p>

<h4 id="createanewactivedirectoryaccounttenant">Create a new Active Directory Account &amp; Tenant</h4>

<ol>
<li>Login to the <a href="https://manage.windowsazure.com/">Windows Azure Management portal</a>.  </li>
<li>Navigate to the "Active Directory" section using the navigation bar.  </li>
<li>Create a new Active Directory account and tenant using the <strong>ADD</strong> icon.  </li>
<li><p>Within the "Add directory" dialog populate the following:</p>

<ul><li>DIRECTORY = <strong>Create new directory</strong></li>
<li>NAME = <strong>MyOrganization</strong></li>
<li>DOMAIN NAME = [<strong>SOMEAVAILABLENAME</strong>].onmicrosoft.com</li>
<li>COUNTRY OR REGION = [YOUR COUNTRY]</li></ul>

<p><em>NOTE: AS OF THIS WRITING ACTIVE DIRECTORY ACCOUNTS &amp; TENANTS CANNOT BE DELETED OR RENAMED AFTER CREATION. WHILE THIS IS PLANNED TO CHANGE, IN THE MEANTIME PICK "<strong>SOMEAVAILABLENAME</strong>" THAT WON'T BOTHER YOUR OCD TOO MUCH.</em></p></li>
</ol>

<p>What do did was create an Active Directory Account (named <strong>NAME</strong>) containing a tenant (<strong>DOMAIN NAME</strong>). An AAD Account can house multiple tenants:</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/AAD_ACCOUNT_HIERARCHY.jpg" alt="AAD account" title=""></center></p>

<h4 id="addausertoyouraadtenant">Add a User to Your AAD Tenant</h4>

<p>One of the benefits of AAD is that it can be synced with an on-premises Active Directory to leverage existing user information. In this tutorial though we will manually create a user within our tenant to use throughout the rest of this blog series.</p>

<ol>
<li>Within the "Active Directory" section of the <a href="https://manage.windowsazure.com/">Windows Azure Management portal</a> select the AAD Tenant we created above.  </li>
<li>Navigate to the "USERS" tab and click the <strong>ADD USER</strong> icon.  </li>
<li>At the "Tell us about this user" prompt populate the following: <br>
<ul><li>TYPE OF USER = <strong>New user in your organization</strong></li>
<li>USER NAME = <strong>Test</strong>@<strong>YOURTENANTNAME</strong>.onmicrosoft.com</li>
<li>At the "user profile" prompt dialog populate the following:</li>
<li>FIRST NAME = <strong>Testy</strong></li>
<li>LAST NAME = <strong>Testo</strong></li>
<li>DISPLAY NAME = <strong>Lord Testington</strong></li>
<li>ROLE = <strong>Global Administrator</strong></li></ul></li>
<li>At the "ADD USER Get temporary password" prompt click the <strong>create</strong> button.  </li>
<li>Select the newly-created user and overwrite the temporary password with a strong password that is easily rememberable.</li>
</ol>

<h4 id="addanapplicationtoyouraadtenant">Add an Application to Your AAD Tenant</h4>

<p>After creating a user within our tenant we also need to configure information about the application we want AAD to provide user authentication for. Here's how:</p>

<ol>
<li>Within the "Active Directory" section of the <a href="https://manage.windowsazure.com/">Windows Azure Management portal</a> select the AAD Tenant we created above.  </li>
<li>Navigate to the "APPLICATIONS" tab and click the "ADD" icon.  </li>
<li>Click "Add an application my organization is developing".  </li>
<li>Enter <strong>NAME</strong>=WebApp and select "WEB APPLICATION AND/OR WEB API" before clicking the <strong>-></strong>  </li>
<li>At the "ADD APPLICATION App properties" dialog populate the following: <br>
<ul><li>APP URL = <a href="http://localhost:1234/">http://localhost:1234</a> [the url of your Nancy Web App]</li>
<li>APP ID URI = https://<strong>YOURTENANTNAME</strong>.onmicrosoft.com/WebApp</li></ul></li>
<li>At the "ADD APPLICATION Directory access" dialog populate the following: <br>
<ul><li>SINGLE SIGN-ON</li></ul></li>
<li>After creation navigate to "CONFIGURE" and modify the <strong>Reply URL</strong> of the application to be <a href="http://localhost:1234/Authenticated">http://localhost:1234/Authenticated</a> this is the url that will be called after a user has been authenticated by AAD. Click the SAVE icon to persist changes.  </li>
<li>At the very bottom of the application's configuration you’ll see a list of the Web APIs provisioned within the same tenant. If you have none, this would be a good opportunity to create one for testing purposes. You can do that by repeating the steps in this block while altering steps 4 &amp; 5 to reference instead "WebAppResource". After creation, specify WebAppResource is a WEB API ACCESSED BY THIS APPLICATION from the WebApp configuration page. Click the SAVE icon to persist changes.  </li>
<li>There's one more piece of information we need to configure for use in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part2">part II</a>; we will generate a shared key that our application will use to prove to AAD that it is trusted (by us). You can generate this key within the WebApp tenant configuration  inside the "keys" section:</li>
</ol>

<p>One... <br>
<center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/generateKeys.png" alt="keys1" title=""></center> <br>
Two... <br>
<center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/generateKeys2.png" alt="keys2" title=""></center> <br>
(click the "SAVE" icon to persist)</p>

<p>Three... <br>
<center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/generateKeys3.png" alt="keys3" title=""></center></p>

<p>After generation copy and paste the key to a temporary <a href="http://notepad-plus-plus.org/">notepad++</a> document because upon renavigation it will be hidden (but you can generate a new one): </p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/generateKeys4.png" alt="keys4" title=""></center></p>

<p>Now you should have two applications configured within your tenant like so:</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/tenantApps.jpg" alt="tenant apps" title=""></center></p>

<h2 id="conclusion">Conclusion</h2>

<p>This post covered the necessary configurations for Azure Active Directory to support authentication on behalf of a web application (that we have yet to create). In the next post, <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part2">part II</a>, we will create a simplistic NancyFx web application and use AAD to authorize users.</p>]]></description><link>http://Blaug.azurewebsites.net/aad-security-with-nancyfx-part1/</link><guid isPermaLink="false">1bb8ae78-60af-4a4e-ab5f-3e08440bd898</guid><dc:creator><![CDATA[Reid Peryam]]></dc:creator><pubDate>Thu, 16 Jan 2014 22:27:44 GMT</pubDate></item><item><title><![CDATA[Integrating Azure Active Directory Security Into NancyFx (part II)]]></title><description><![CDATA[<h2 id="introduction">Introduction</h2>

<p>This is the second in a series of posts focusing on two .Net development technologies: Azure Active Directory (<a href="http://www.windowsazure.com/en-us/documentation/services/active-directory/">AAD</a>) and NancyFx (aka <a href="http://nancyfx.org/">Nancy</a>). Nancy  has emerged as a scalable web-development framework affording what it labels the "Super Duper Happy Path" (SDHP) for simplistic creation of web applications and APIs; AAD is a Azure/cloud-hosted <a href="http://en.wikipedia.org/wiki/Directory_service">directory service</a> affording native client and web client application authentication as a service (<a href="http://en.wikipedia.org/wiki/Software_as_a_service">SaaS</a>). We are securing a Nancy web application with AAD; the code presented in this series is available <a href="https://github.com/TheFastCat/AzureActiveDirectoryWithNancyFxStatelessAuthentication">here</a>.</p>

<ul>
<li>In <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">Part I: Azure Active Directory Configuration</a> we configure a new AAD tenant for our use</li>
</ul>

<h2 id="partiiaadfromanancywebapplication">Part II: AAD From a Nancy Web Application</h2>

<p>This post covers the creation of a new Nancy web application that will leverage the AAD configurations we created in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a> to authorize users to access secured resources.</p>

<h3 id="makeanancywebapplication">Make a Nancy Web Application</h3>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/nancy_horizontal_framed_bf.png" alt="nancyFx" title=""></center></p>

<ol>
<li>Within Visual Studio create a Console Application named "WebApp".  </li>
<li>Install the Nancy.Hosting.Self nuget package.  </li>
<li><p>Add a reference to Nancy.Hosting.Self and within Program.Main add the following:</p>

<pre><code>using (var host = new NancyHost(new Uri("http://localhost:1234")))
{
   host.Start();
   Console.ReadLine();
}
</code></pre></li>
<li><p>Add a new class named SampleModule.cs to handle an HTTP request to the default route:</p>

<pre><code>public class SampleModule : Nancy.NancyModule
{
   public SampleModule()
   {
      Get["/"] = _ =&gt; "Hello World!";
   }
}   
</code></pre>

<p>This class inherits <code>NancyModule</code> -- the mechanism by which Nancy handles HTTP verbs to different places. Our project now looks like this within Visual Studio:</p></li>
</ol>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/csproj.png" alt="Nancy .csproj" title=""></center></p>

<p>F5 to launch the console application and navigate to <a href="http://localhost:1234/">http://localhost:1234/</a> to see Nancy say "Hello World!"</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/NancyhelloWorld.jpg" alt="Nancy Hello World" title=""></center></p>

<h3 id="integratingaadintoournancywebapplication">Integrating AAD into our Nancy Web Application</h3>

<p>Now that we have AAD configured and a functional web application it's time to integrate them.</p>

<p>Create a new class within WebApp.csproj named AADHelper containing the following boiler plate code that will be used to leverage AAD from within our web application:</p>

<pre><code>public static class AADHelper
{
  public static string GetAuthorizationURL()
  {
    string authorizationUrl = string.Format("https://login.windows.net/{0}/"+
    "oauth2/authorize?api-version=1.0&amp;response_type=code&amp;client_id={1}&amp;"+
    "resource={2}&amp;redirect_uri={3}",
    AAD.TENANT_ID,
    AAD.CLIENT_ID,
    AAD.APP_ID_URI,
    AAD.REPLY_URL);
    return authorizationUrl;
  }          
  public struct AAD
  {
    public static readonly string TENANT_ID  
    = "????????-????-????-????-????????????"
    public static readonly string CLIENT_ID  
    = "???????????????????????????????";
    public static readonly string APP_ID_URI 
    = "https://?????.onmicrosoft.com/WebAppResource";
    public static readonly string REPLY_URL  
    =  "http://localhost:1234/Authenticated";
    public static readonly string CLIENT_KEY 
    = "???????????????????????????????";
  }        
}
</code></pre>

<p>Before proceeding populate the variables within the "AAD" struct to match those of your own AAD configuration. Here's where to locate them:</p>

<ul>
<li><strong>TENANT ID</strong>  - an Azure Active Directory "tenant" (aka Domain) which is      identified by us as a key (which can be found via) :
<ul><li>Azure Management Portal -> 
<ul><li>Active Directory ->
<ul><li>Applications ->
<ul><li>View Endpoints (at the bottom, center of the screen)
the TENANT_ID appears sandwiched within the various end point urls as a guid-like key</li></ul></li></ul></li></ul></li></ul></li>
<li><strong>CLIENT ID</strong>  - this is the Client ID for the WebApp (we configured within AAD in Part I).</li>
<li><strong>APP ID URI</strong> - this is the APP ID URI for WebAppResource (we configured within AAD in Part I).</li>
<li><strong>REPLY URL</strong>  - this is the Reply URL  for the WebApp</li>
<li><strong>CLIENT KEY</strong>  - This is the 'secret' configured within AAD to associate the calling code with the configured application. We configured this in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a> within the "keys" section of our WebApp application.</li>
</ul>

<h4 id="createasecurenancymodule">Create a Secure Nancy Module</h4>

<p>A good first step in securing access to our web application is to block unknown parties from accessing private information. Let's do this within WebApp.csproj by creating a new <code>NancyModule</code> with some simple security logic to accomplish this. Create a new class named SecureModule.cs :</p>

<pre><code>    using Nancy;
    using Nancy.Responses;
    using System;

    public class SecureModule : NancyModule
    {
        Before += ctx =&gt;
        {
            return ctx.CurrentUser == null ||
                   String.IsNullOrWhiteSpace(ctx.CurrentUser.UserName)
                ? new RedirectResponse("/login")
                // else allow request to continue unabated
                : null;
        };

        public SecureModule()
        {
            Get["/Private"] = _ =&gt;
            {
                return "Secret stuff!";
            };
        }
    } 
</code></pre>

<p>We created a new HTTP route, "/Private" that will execute when a user navigates to <a href="http://localhost:1234/Private">http://localhost:1234/Private</a> -- but notice the code block beforehand starting with <code>Before +=</code>. This code is invoked before each HTTP request within this NancyModule (only) reaches its destination. It redirects requests from unidentified users to a "/login" route. Only if the initiating request is associated with a valid user it is allowed to continue to its destination. </p>

<p>We haven't yet coded support for a /Login route that unauthenticated users are redirected to; let's do so now because this is where the rubber hits the road between our Nancy Web Application and AAD.</p>

<h4 id="invokeaadloginscreenfromourwebapp">Invoke AAD Login Screen From our Web App</h4>

<p>Now our application supports redirecting an unidentified client to /login. Let's take it a step further and utilize AAD to present a login dialog to authenticate users against those AAD configurations we previously defined. </p>

<p>Add a new HTTP route within the SampleModule.cs file we created within WebApp.cs (below <code>Get["/"] ... "Hello World!";</code>):</p>

<pre><code>    Get["/login"] = _ =&gt;
    {
      return new Nancy.Responses.
      RedirectResponse(AADHelper.GetAuthorizationURL());
    };
</code></pre>

<p>Now when a user is redirected to this /login route the web browser will redirect a client to be authorized by the AAD tenant we point it to. F5 the application and navigate to <a href="http://localhost:1234/login">http://localhost:1234/login</a> to see what happens. If everything is configured correctly you will be prompted with a web dialog page asking you to sign in.</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/AAD_Login_Dialog.png" alt="AAD login dialog" title=""></center></p>

<p>There are a couple of things to notice about this web dialog.</p>

<ol>
<li>The address for this page is served from login.microsoftonline.com ; this isn't anything from within our WebApp or Nancy - this page is served as a callback by AAD to our browser redirection within /login.  </li>
<li>Multiple account credentials are visible. My hotmail address is there in addition to a user I have for an AAD tenant. If I login with either of these credentials I will not be provided authorization to the WebApp. This is because these two accounts/users do not exist within our WebApp tenant on AAD. They are outside of our application's ecosystem.</li>
</ol>

<p>Try to sign in using various usernames and passwords; you will notice that AAD prohibits you from proceeding further until you enter a valid login for a user and password authorized for the WebApp (that we configured within our tenant in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a>). Only after logging in with "Test@<strong>YOURTENANTNAME</strong>.onmicrosoft.com" and the associated password will you be allowed to continue (be sure to logout of any other associated microsoft accounts that might be cached within your browser).</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/ld215_security_blockade.jpg" alt="security blockade" title=""></center></p>

<p>This is great! AAD is basically playing the part of a guard dog on our behalf. It stonewalls any attempt to access our web application until a user proves he should be permitted access by providing valid user credentials associated with the applicable AAD tenant's configuration.</p>

<p>After providing correct credentials for the user we previously configured, you will be redirected to the following screen:</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/AAD_Reply_404-2.jpg" alt="Nancy Authenticated 404 " title=""></center></p>

<p>What looks like an error actually isn't - this is success! It means that AAD effectively authenticated a user and redirected him to the <strong>REPLY_URL</strong> configured for our WebApp (see <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a>); unfortunately we haven't configured a route within our SecureModule.cs that matches "/Authenticated" -- ergo Nancy's cute 404 monster cartoon. Take a look at something else -- AAD sent us an authorization "code" as a query parameter as well.</p>

<p>Things are starting to get fun here - what is this mysterious code? What will we do with it? What part does Nancy play?</p>

<h2 id="conclusion">Conclusion</h2>

<p>In this post we created a NancyFx web application, referenced AAD tenant configuration we initialized in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a> and leveraged AAD to authorize clients. What comes next is to more fully integrate security behavior between Nancy and AAD. We do that next in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part3">part III</a>.</p>]]></description><link>http://Blaug.azurewebsites.net/aad-security-with-nancyfx-part2/</link><guid isPermaLink="false">6cc5888e-6730-4414-a21f-4ec5470d0202</guid><dc:creator><![CDATA[Reid Peryam]]></dc:creator><pubDate>Thu, 16 Jan 2014 22:27:35 GMT</pubDate></item><item><title><![CDATA[Integrating Azure Active Directory Security Into NancyFx (part III)]]></title><description><![CDATA[<h2 id="introduction">Introduction</h2>

<p>This is the third in a series of posts focusing on two .Net development technologies: Azure Active Directory (<a href="http://www.windowsazure.com/en-us/documentation/services/active-directory/">AAD</a>) and NancyFx (aka <a href="http://nancyfx.org/">Nancy</a>). Nancy  has emerged as a scalable web-development framework affording what it labels the "Super Duper Happy Path" (SDHP) for simplistic creation of web applications. AAD is a Azure/cloud-hosted <a href="http://en.wikipedia.org/wiki/Directory_service">directory service</a> supplying authentication as a service (<a href="http://en.wikipedia.org/wiki/Software_as_a_service">SaaS</a>). We are securing a Nancy web application with AAD; the code presented in this series is available <a href="https://github.com/TheFastCat/AzureActiveDirectoryWithNancyFxStatelessAuthentication">here</a>.</p>

<ul>
<li>In <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">Part I: Azure Active Directory Configuration</a> we configure a new AAD tenant for our use</li>
<li>In <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part2">Part II: AAD From a Nancy Web Application</a> we took the first steps to integrate a Nancy web application with AAD</li>
</ul>

<h2 id="partiiiintegratingnancystatelessauthenticationwithaad">Part III: Integrating Nancy Stateless Authentication with AAD</h2>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/three.jpg" alt="Mr Owl" title=""></center></p>

<p>This post covers further integration of the AAD configurations we created in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a> with the Nancy web applciation we created and <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part3">part II</a> . We will be leveraging Nancy's support for stateless authentication to secure our web application's content. This affords a simplistic, low-overhead implementation to allow only trusted users access.</p>

<h3 id="handlingaadsreturnedauthorizationcode">Handling AAD's Returned Authorization code</h3>

<p>We ended <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part2">part II</a> with AAD invoking a callback to the configured <strong>RETURN_URL</strong> "/Authenticated" along with a query parameter representing an authorization code. Let's add functionality to the WebApp.csproj to use this authortization code to retrieve the identity of a user invoking our application.</p>

<h4 id="handlingaadsreturn_urlcallback">Handling AAD's RETURN_URL Callback</h4>

<p>In order to catch the callback redirection from AAD to "/Authenticated" create a new route within WebApp.csproj's SecureModule.cs:</p>

<pre><code>        Get["/Authenticated"] = _ =&gt;
        {
            return "Hello " + Context.CurrentUser.UserName + "!";
        };
</code></pre>

<p>If you F5'd the application you will enter into a redirect loop and never reach the inside of the "/Authenticated" route -- do you know why?</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/FryMeme.jpg" alt="redirect loop" title=""></center></p>

<p>Remember the other code at the top of our SecureModule() :</p>

<pre><code>        Before += ctx =&gt;
        {
            return ctx.CurrentUser == null ||
                   String.IsNullOrWhiteSpace(ctx.CurrentUser.UserName)
                ? new RedirectResponse("/login")
                // else allow request to continue unabated
                : null;
        };
</code></pre>

<p>Even though AAD is dialing back to our /Authenticated route with an authorization <em>means</em> that the current user was identified by AAD as being authorized for access - Nancy still hasn't associated the incoming request (from AAD) with an authorized user. Because of this AAD's callback (and authorization code) will be rebuffed and redirected back to the /login route. How ironic!  </p>

<p><center> <br>
<img src="http://blaug.azurewebsites.net/content/images/2014/Jan/LockedOut_main_Full.jpg" alt="irony">
</center></p>

<p>In order to fix this unexpected behavior we will call in some backup in the form of a Nuget package.</p>

<h3 id="integratingnancysstatelessauthentication">Integrating Nancy's Stateless Authentication</h3>

<p>We will use Nancy's stateless authentication to consume the authorization code returned by AAD to determine a user's identity. Once Nancy knows an incoming request is associated with a real user (or not) application security logic is breezy; however there's a little more work involved to before we get there.</p>

<ol>
<li>Add the "Nancy.Authentication.Stateless" Nuget package to WebApp.csproj. This package adds support for authenticating a request eachtime it is handled by Nancy without the overhead of database or session persistance.  </li>
<li>Create a new class within WebApp.csproj called Bootstrapper.cs containing the following:</li>
</ol>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/bootstrapper-1.jpg" alt="bootstrapper" title=""></center></p>

<p><em>I apologize for the image in place of code - ghost blogging hates my code formatting -- but there is a link to all the source code at the end</em></p>

<p>The function of this code is to override Nancy's default behavior in order to inject stateless authentication into every request that the application handles. The <code>RequestStartup</code> method is invoked prior to every request that Nancy handles. </p>

<p>The interesting part comes here:</p>

<pre><code>var authorizationCode = (string)nancyContext.Request.Query.code;
return AADHelper.GetAuthenticatedUserIDentity(authorizationCode);
</code></pre>

<p>We are grasping the authentication code (remember -- that AAD returned to us) and using it to retrieve a user identity from AAD. Unfortunately the magic method we call here to do that doesn't yet exist. Let's write it.</p>

<h3 id="retrievingidentityfromaad">Retrieving Identity from AAD</h3>

<p>I already let the cat out of the bag - that mysterious authentication code that AAD sent us back in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part2">part II</a> provides the ability to retrieve a user's identification. That's its secret. Mystery solved. Let's use the token (and AAD) to do just that.</p>

<ol>
<li>Add the Nuget package Microsoft.IdentityModel.Clients.ActiveDirectory to WebApp.csproj. This is the Active Directory Authentication Library (<a href="http://www.cloudidentity.com/blog/2013/09/12/active-directory-authentication-library-adal-v1-for-net-general-availability/">ADAL</a>) -- the .Net library for consuming AAD's SaaS offerings. You can conceptualize ADAL as a telephone for requesting AAD information from within a consuming application. <br>
<ul><li>You might say "wait a second we already used AAD to show our user a login screen without ADAL!" Well we sort of did; if you look back to <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part2">part II</a> what we actually did was hack an oauth2 URI containing our AAD tenant.</li></ul></li>
<li>Open the AADHelper.cs class and add a using reference to Microsoft.IdentityModel.Clients.ActiveDirectory.  </li>
<li>Add a new method at the bottom of the class: <br>
<center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/GetAuthenticatedUserIdentity-1.jpg" alt="GetAuthenticatedUserIdentity" title=""></center></li>
</ol>

<p>Before proceeding let's resolve the missing reference to this method's <code>UserIdentity</code> dependency. Add a new class to WebApp.csproj named UserIdentity.cs:</p>

<pre><code>using Nancy.Security;
using System.Collections.Generic;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace WebApp
{
    public class UserIdentity : IUserIdentity
    {
        public UserIdentity(UserInfo userInfo)
        {
            UserName = userInfo.UserId;
        }

        public string UserName { get; set; }
        public IEnumerable&lt;string&gt; Claims { get; set; }
    }
}
</code></pre>

<p>This class is just an <a href="http://en.wikipedia.org/wiki/Adapter_pattern">adapter</a> which converts ADAL's UserInfo object into an implementation of IUserIdentity -- an interface which Nancy works off of for authentication. </p>

<p>Now we're all hooked up to retrieve a user's identity from AAD using the authorization token provided by AAD and then integrate it into Nancy's stateless authentication. Let's watch it in action. </p>

<h3 id="letitrip">Let it Rip</h3>

<ul>
<li>Within the WebApp.csproj add a Visual Studio breakpoint to the following line of Bootstrapper.cs:
<center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/breakpoint.png" alt="breakpoint" title=""></center>  </li>
<li>F5 the application and navigate to <a href="http://localhost:1234/Private">http://localhost:1234/Private</a>. Your previous login credentials should be cached within your browser (if not login with the test user we configured back in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a>). You will hit the above breakpoint after AAD has authorized you and passed back an authorization code thusly:
<center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/breakpoint2.png" alt="breakpoint2" title=""></center>  </li>
<li><p>F11 to step into the <code>GetAuthenticatedUserIDentity</code> method:
<center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/breakpoint3.png" alt="breakpoint3" title=""></center> <br>
As you continue to the end of the method you'll see that we have <code>UserInfo</code> returned from AAD. We convert this into a <code>UserIdentity</code> object (ala our <a href="http://en.wikipedia.org/wiki/Adapter_pattern">adapter</a>) and return it from the method.</p></li>
<li><p>Press <code>Shift</code>+F11 to return to Bootstrapper.cs
<center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/breakpoint4.png" alt="breakpoint4" title=""></center> <br>
From the context of Nancy's stateless authentication we are consuming the returned <code>UserIdentity</code> and associating it with the current HTTP request (remember we are in the <code>RequestStartup</code> method that is invoked prior to each handled request).</p></li>
<li><p>Press F10 to continue along the request's path through Nancy. Since the destination is /Authenticated (the <strong>RETURN URL</strong> configured within AAD back in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a>) - the request will next be handled within SecureModule.cs.</p></li>
</ul>

<p>Remember the <code>Before += ctx =&gt;</code> code that is invoked within SecureModule before a request is handled in order to redirect unauthenticated requests (see <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part2">part II</a>)? </p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/breakpoint5.png" alt="breakpoint5" title=""></center></p>

<p>This time around Nancy has a user associated with the incoming request. This is the user we configured within our AAD Tenant back in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part1</a>. </p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/th.jpg" alt="have we met before?" title=""></center></p>

<p>Because Nancy has an authenticated user associated with the request it continues unabated through <code>Before += ctx =&gt;</code> and on to its destination (as we configured within AAD as the RETURN URL back in <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a>).</p>

<ul>
<li>The request ends up here:</li>
</ul>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/breakpoint6.png" alt="breakpoint6" title=""></center></p>

<p>And outputs the user's name to the browser window:</p>

<p><center><img src="http://blaug.azurewebsites.net/content/images/2014/Jan/output.png" alt="output" title=""></center></p>

<p>Congratulations you've just setup a Nancy web application with stateless authentication to leverage Azure Active Directory's authentication service!</p>

<h2 id="extracredit">Extra Credit</h2>

<h3 id="handlingerrorsfromaad">Handling Errors From AAD</h3>

<p>Add the following code to the top of SecureModule's <code>Before += ctx =&gt;</code> to handle errors returned from ADAL's <code>AcquireTokenByAuthorizationCode</code> method to aid debugging:</p>

<pre><code>            if (ctx.Request.Query.error.HasValue)
            {
                string errorDesc = 
                    string.Format("{0}\n\n{1}\n\n{2}",
                    ctx.Request.Query.error,
                    ctx.Request.Query.error_description);

                Context.Response            = Response.AsText(errorDesc);
                Context.Response.StatusCode = HttpStatusCode.Forbidden;
                return Context.Response;
            }                
</code></pre>

<h2 id="conclusion">Conclusion</h2>

<p>In this post we integrated the work from <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part I</a> and <a href="http://blaug.azurewebsites.net/aad-security-with-nancyfx-part1">part</a> II to support stateless authentication within Nancy using AAD and Microsoft's <a href="http://www.cloudidentity.com/blog/2013/09/12/active-directory-authentication-library-adal-v1-for-net-general-availability/">ADAL</a> library. You can obtain the source code we created in this series from <a href="https://github.com/TheFastCat/AzureActiveDirectoryWithNancyFxStatelessAuthentication">this git repo</a>. Where possible obfuscated complexity (and confusion) that being said there is a lot going on; hoprfully this series of posts will give you a good introductory context to dive deeper and learn more about authorization, authentication, AAD and NancyFx.</p>]]></description><link>http://Blaug.azurewebsites.net/aad-security-with-nancyfx-part3/</link><guid isPermaLink="false">bb29e70f-790c-46e7-bd06-864cc026ee3c</guid><dc:creator><![CDATA[Reid Peryam]]></dc:creator><pubDate>Thu, 16 Jan 2014 22:27:20 GMT</pubDate></item></channel></rss>