{"id":2565,"date":"2013-12-10T09:56:06","date_gmt":"2013-12-10T16:56:06","guid":{"rendered":"http:\/\/www.cloudidentity.com\/blog\/?p=2565"},"modified":"2013-12-10T09:57:25","modified_gmt":"2013-12-10T16:57:25","slug":"protecting-a-self-hosted-api-with-microsoft-owin-security-activedirectory","status":"publish","type":"post","link":"https:\/\/www.cloudidentity.com\/blog\/2013\/12\/10\/protecting-a-self-hosted-api-with-microsoft-owin-security-activedirectory\/","title":{"rendered":"Protecting a Self-Hosted API with Microsoft.Owin.Security.ActiveDirectory"},"content":{"rendered":"<p>As you might have <a href=\"https:\/\/www.cloudidentity.com\/blog\/2013\/11\/12\/msdn-magazine-article-secure-asp-net-web-api-with-windows-azure-ad-and-microsoft-owin-components\/\" target=\"_blank\">sensed<\/a>, OWIN is slated to occupy a prominent role in our next wave of claims-based identity software (more details soon (I hope<img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-smile.png\">)).<br \/>One question I am getting with increasing frequency is \u201cjust how lightweight is this OWIN thing? Is it going to impose heavy requirements that will prevent me from doing anything with it unless I use the latest and greatest?\u201d.<\/p>\n<p>The ones among you already familiar with it are already smiling, I am sure\u2026 OWIN was designed exactly to decouple apps and frameworks from the underlying layers, and while the Microsoft OWIN Components do have some system requirements (e.g. you can\u2019t go lower that .NET 4.5) those are not more restrictive than other constraints we already have in place (the <a href=\"https:\/\/www.cloudidentity.com\/blog\/2013\/06\/06\/the-json-web-token-handler-for-net-4-5-reaches-ga\/\" target=\"_blank\">JWT handler<\/a> requires .NET 4.5 anyway).<\/p>\n<p>To give you a concrete feeling of the above, I am going to show you how you can set up a super simple Web API in a console app and how you can easily secure with with Windows Azure AD with the exact same code you use when programming against IIS Express\/full IIS. In fact, I could just reference existing tutorials (like <a href=\"http:\/\/www.asp.net\/web-api\/overview\/hosting-aspnet-web-api\/use-owin-to-self-host-web-api\" target=\"_blank\">this one<\/a> from the excellent Kanchan) and just add the authentication bits, but in my experience some denormalization often helps to understand the topic better. It will take a bit of extra work on my part, but it\u2019s all good <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-smile.png\"><\/p>\n<p>Here there\u2019s what we are going to do:<\/p>\n<ul>\n<li>We\u2019ll create a self-hosted Web API, following almost verbatim Kanchan\u2019s tutorial\n<li>We will add the middleware for validating JWT tokens from AAD\n<li>We\u2019ll create a simple client to poke our miniAPI<\/li>\n<\/ul>\n<p>To emphasize that this works also with the N-1 version of VS\/.NET, I\u2019ll use VS2012.<\/p>\n<h2>Create a Minimal Self-Hosted API<\/h2>\n<p>Let\u2019s start by creating a console application. I called mine SelfHostingFunAPI, but I am sure you\u2019ll be able to come up with something more tasteful.<br \/>Once you have the project available, head to the solution explorer, right-click on its entry and choose \u201cManage NuGet Packages\u201d. We are going to add the necessaire for hosting Web API on an arbitrary process. Select the Stable Only feed, and search for <strong>Microsoft.AspNet.WebApi.OwinSelfHost<\/strong>.<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image.png\"><img loading=\"lazy\" decoding=\"async\" title=\"image\" style=\"border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-top-width: 0px\" border=\"0\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image_thumb.png\" width=\"640\" height=\"426\"><\/a><\/p>\n<p>Pick the entry that looks like the one highlighted above, and hit install. Accept all the various licenses (if you so choose! <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-smile.png\">) and hit \u201cclose\u201d.<\/p>\n<p>Very good, we now have all the assemblies we need to self-host our API. Let\u2019s start adding some beef to the project by adding a controller for our API. Create a new class (solution explorer-&gt;right-click-&gt;Add-&gt;Class) and call it <strong>ValuesController<\/strong>. <\/p>\n<blockquote>\n<p><strong>Beware<\/strong>: <em>from this moment on names count<\/em>! MVC and OWIN are convention-driven, and if classes are not named as expected stuff simply does not happen.<\/p>\n<\/blockquote>\n<p>Implement the class with something to the effect of the code below:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">using<\/span> System.Collections.Generic;\r\n<span class=\"kwrd\">using<\/span> System.Web.Http;\r\n\r\n<span class=\"kwrd\">namespace<\/span> SelfHostingFunAPI\r\n{\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">class<\/span> ValuesController : ApiController\r\n    {\r\n        <span class=\"kwrd\">public<\/span> IEnumerable&lt;<span class=\"kwrd\">string<\/span>&gt; Get()\r\n        {\r\n            <span class=\"kwrd\">return<\/span> <span class=\"kwrd\">new<\/span> <span class=\"kwrd\">string<\/span>[] { <span class=\"str\">\"value1\"<\/span>, <span class=\"str\">\"value2\"<\/span> };\r\n        }\r\n    }\r\n}<\/pre>\n<style type=\"text\/css\">.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }\n<\/style>\n<p>Yes, that is a shortened version of the classic default controller in Web API. Make sure that the class is public.<\/p>\n<p>That done, let\u2019s add the Startup class for hosting our Web API in OWIN. Create Startup.cs as above (remember what I said about names! <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-winkingsmile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Winking smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-winkingsmile.png\">) and paste in there the following code:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">using<\/span> Owin;\r\n<span class=\"kwrd\">using<\/span> System.Web.Http;\r\n\r\n<span class=\"kwrd\">namespace<\/span> SelfHostingFunAPI\r\n{\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">class<\/span> Startup\r\n    {\r\n        <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">void<\/span> Configuration(IAppBuilder appBuilder)\r\n        {\r\n            <span class=\"rem\">\/\/ Configure Web API for self-host. <\/span>\r\n            HttpConfiguration config = <span class=\"kwrd\">new<\/span> HttpConfiguration();\r\n            config.Routes.MapHttpRoute(\r\n                name: <span class=\"str\">\"DefaultApi\"<\/span>,\r\n                routeTemplate: <span class=\"str\">\"api\/{controller}\/{id}\"<\/span>,\r\n                defaults: <span class=\"kwrd\">new<\/span> { id = RouteParameter.Optional }\r\n            );\r\n            appBuilder.UseWebApi(config);\r\n        }\r\n    }\r\n}<\/pre>\n<style type=\"text\/css\">.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }\n<\/style>\n<p>Once again, there\u2019s nothing mysterious here. The builder class sets up the default route which leads to our API controller, then adds to the middleware pipeline the Web API hoster.<\/p>\n<p>Lastly, we need to host the OWIN pipeline itself. Head to Program.cs, and write something along the lines of the following:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">using<\/span> Microsoft.Owin.Hosting;\r\n<span class=\"kwrd\">using<\/span> System;\r\n<span class=\"kwrd\">using<\/span> System.Net.Http;\r\n\r\n<span class=\"kwrd\">namespace<\/span> SelfHostingFunAPI\r\n{\r\n    <span class=\"kwrd\">class<\/span> Program\r\n    {\r\n        <span class=\"kwrd\">static<\/span> <span class=\"kwrd\">void<\/span> Main(<span class=\"kwrd\">string<\/span>[] args)\r\n        {\r\n            <span class=\"rem\">\/\/ Start OWIN host <\/span>\r\n            var server = WebApp.Start&lt;Startup&gt;(url: <span class=\"str\">\"http:\/\/localhost:9000\/\"<\/span>);\r\n            Console.ForegroundColor = ConsoleColor.Blue;\r\n            Console.WriteLine(<span class=\"str\">\"Web API listening at http:\/\/localhost:9000\/\"<\/span>);\r\n\r\n            <span class=\"rem\">\/\/ Test call<\/span>\r\n            HttpClient client = <span class=\"kwrd\">new<\/span> HttpClient();\r\n            var response = client.GetAsync(<span class=\"str\">\"http:\/\/localhost:9000\/api\/values\"<\/span>).Result;\r\n            Console.ForegroundColor = ConsoleColor.Red;\r\n            Console.WriteLine(response.Content.ReadAsStringAsync().Result); \r\n\r\n            Console.ReadLine(); \r\n        }\r\n    }\r\n}<\/pre>\n<style type=\"text\/css\">.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }\n<\/style>\n<p>The call to WebApp.Start initializes a new server, which listens at the specified address. The rest of the method calls the Web API to double check that we did everything correctly. Hit F5 and see what happens:<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image1.png\"><img loading=\"lazy\" decoding=\"async\" title=\"image\" style=\"border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-top-width: 0px\" border=\"0\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image_thumb1.png\" width=\"640\" height=\"422\"><\/a><\/p>\n<p>Perhaps that\u2019s not exactly pyrotechnics, but we do have confirmation that our self-hosted Web API is functional. Hurrah!<\/p>\n<p>Before moving on to the next task, let\u2019s eliminate the test call from Main: we\u2019ll be using an actual client moving forward. Change Main\u2019s body with the following.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">static<\/span> <span class=\"kwrd\">void<\/span> Main(<span class=\"kwrd\">string<\/span>[] args)\r\n{\r\n    <span class=\"rem\">\/\/ Start OWIN host <\/span>\r\n    var server = WebApp.Start&lt;Startup&gt;(url: <span class=\"str\">\"http:\/\/localhost:9000\/\"<\/span>);\r\n    Console.ForegroundColor = ConsoleColor.Blue;\r\n    Console.WriteLine(<span class=\"str\">\"Web API listening at http:\/\/localhost:9000\/\"<\/span>);\r\n    Console.WriteLine(<span class=\"str\">\"Press ENTER to terminate\"<\/span>);\r\n    Console.ReadLine(); \r\n}\r\n<\/pre>\n<style type=\"text\/css\">.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }\n<\/style>\n<h2>Secure the API with Windows Azure AD<\/h2>\n<p>Here comes the raison d&#8217;\u00eatre of the entire post. Say that we want to restrict access to our minimal, no-IIS API only to users from a certain Windows Azure AD tenant. The good news is \u2013 we reuse exactly the same OWIN middleware that VS2013 adds in the new Web API templates protected by organizational accounts. What\u2019s more, we reuse it using the exact same code. In fact, here I will assume that you went through the tutorial in <a href=\"https:\/\/www.cloudidentity.com\/blog\/2013\/11\/12\/msdn-magazine-article-secure-asp-net-web-api-with-windows-azure-ad-and-microsoft-owin-components\/\" target=\"_blank\">this MSDN Magazine article<\/a> (yes, denormalization has limits <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-smile.png\">) and that you can reuse in the self hosted case the API and client entries you created in the directory back then.<\/p>\n<p>That\u2019s super-easy. Let\u2019s start by adding the NuGet which wraps the JWT handler and handles token validation for WIndows Azure AD in OWIN. Open the \u201cManage NuGet Packages\u201d dialog, and search for <strong>Microsoft.Owin.Security.ActiveDirectory<\/strong>.<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image2.png\"><img loading=\"lazy\" decoding=\"async\" title=\"image\" style=\"border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-top-width: 0px\" border=\"0\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image_thumb2.png\" width=\"640\" height=\"427\"><\/a><\/p>\n<p>Install the highlighted. <\/p>\n<p>That done, we have to add the right middleware in the pipeline. Open the solution you created following the <a href=\"https:\/\/www.cloudidentity.com\/blog\/2013\/11\/12\/msdn-magazine-article-secure-asp-net-web-api-with-windows-azure-ad-and-microsoft-owin-components\/\" target=\"_blank\">MSDN magazine article<\/a>, and head to the Startup.Auth.cs file. Copy the call to UseWindowsAzureActiveDirectoryBearerAuthentication (I was in vacation in Fiji when the name was paicked up, true story <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-smile.png\">) and paste it in your Startup.cs file in the self hosted API project, as follows:<\/p>\n<pre class=\"csharpcode\"><strong><span class=\"kwrd\">using<\/span> Microsoft.Owin.Security.ActiveDirectory;<\/strong>\r\n<span class=\"kwrd\">using<\/span> Owin;\r\n<span class=\"kwrd\">using<\/span> System.Web.Http;\r\n\r\n<span class=\"kwrd\">namespace<\/span> SelfHostingFunAPI\r\n{\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">class<\/span> Startup\r\n    {\r\n        <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">void<\/span> Configuration(IAppBuilder appBuilder)\r\n        {\r\n            <span class=\"rem\">\/\/ Configure Web API for self-host. <\/span>\r\n            HttpConfiguration config = <span class=\"kwrd\">new<\/span> HttpConfiguration();\r\n            config.Routes.MapHttpRoute(\r\n                name: <span class=\"str\">\"DefaultApi\"<\/span>,\r\n                routeTemplate: <span class=\"str\">\"api\/{controller}\/{id}\"<\/span>,\r\n                defaults: <span class=\"kwrd\">new<\/span> { id = RouteParameter.Optional }\r\n            );\r\n\r\n            <strong>appBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication(\r\n                <span class=\"kwrd\">new<\/span> WindowsAzureActiveDirectoryBearerAuthenticationOptions\r\n                {\r\n                    Audience = <span class=\"str\">\"https:\/\/contoso7.onmicrosoft.com\/RichAPI\"<\/span>,\r\n                    Tenant = <span class=\"str\">\"contoso7.onmicrosoft.com\"<\/span>\r\n                });<\/strong>\r\n\r\n            appBuilder.UseWebApi(config);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<style type=\"text\/css\">.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }\n<\/style>\n<p>The new code is in bold. You\u2019ll notice that instead of relying on the config settings (as I did when targeting full ASP.NET\/IIS) here I pasted directly the values, but of course you can keep those wherever you deem most appropriate.<\/p>\n<blockquote>\n<p>Beware: the order with which you add the middleware is significant. Thanks <strong>Hongye<\/strong> for catching that!<\/p>\n<\/blockquote>\n<p>Now our pipeline includes the right middleware: if we receive a JWT, we\u2019ll validate it and if it checks out we\u2019ll pass the corresponding ClaimsPrincipal to the API body. Very good, but not good enough. Let\u2019s modify the controller class to mandate that all callers must present a valid token from the tenant of choice:<\/p>\n<pre class=\"csharpcode\"><strong><span class=\"kwrd\">using<\/span> System;<\/strong>\r\n<span class=\"kwrd\">using<\/span> System.Collections.Generic;\r\n<strong><span class=\"kwrd\">using<\/span> System.Security.Claims;<\/strong>\r\n<span class=\"kwrd\">using<\/span> System.Web.Http;\r\n\r\n<span class=\"kwrd\">namespace<\/span> SelfHostingFunAPI\r\n{\r\n   <strong> [Authorize]<\/strong>\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">class<\/span> ValuesController : ApiController\r\n    {\r\n        <span class=\"kwrd\">public<\/span> IEnumerable&lt;<span class=\"kwrd\">string<\/span>&gt; Get()\r\n        {\r\n            <strong>Console.WriteLine(<span class=\"str\">\"==&gt;I have been called by {0}\"<\/span>,\r\n                              ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn));<\/strong>\r\n            <span class=\"kwrd\">return<\/span> <span class=\"kwrd\">new<\/span> <span class=\"kwrd\">string<\/span>[] { <span class=\"str\">\"value1\"<\/span>, <span class=\"str\">\"value2\"<\/span> };\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<style type=\"text\/css\">.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }\n<\/style>\n<p>As before, the new code is in <strong>bold<\/strong>. The key element here is the [Authorize] attribute, which adds the constraint to all of the methods in the class.<br \/>I feel a bit dirty in adding a writeline in the body of&nbsp; web API, but it will be useful to show on the service console that we\u2019ve been called by the intended identity. The UPN claim is among the ones that Windows Azure AD sends in JWTs.<\/p>\n<p>Believe it or not, that\u2019s all we had to do to secure the Web API: we just had to add the code in bold <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-smile.png\"><br \/>Now, let\u2019s take care of the client.<\/p>\n<h2>Create a Client App and Test the API<\/h2>\n<p>If you want to do things quickly: you can simply take the WPF client created for the MSDN magazine tutorial, point it to the URL of the self-hosted service () and use it \u2018as in\u2019 \u2013 and you\u2019ll be seeing things in action.<br \/>That said. Given that we used a nice &amp; rugged console, I thought it would be more tough of me to show a client also implemented as a console <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-smile.png\"> if you want to try it yourself, create a console app and use something like the following as main:<\/p>\n<pre class=\"csharpcode\">[STAThread]\r\n<span class=\"kwrd\">static<\/span> <span class=\"kwrd\">void<\/span> Main(<span class=\"kwrd\">string<\/span>[] args)\r\n{\r\n    HttpClient client = <span class=\"kwrd\">new<\/span> HttpClient();\r\n    Console.ForegroundColor = ConsoleColor.Green;\r\n    Console.WriteLine(<span class=\"str\">\"Client ready.\"<\/span>);\r\n    Console.WriteLine(<span class=\"str\">\"Press any key to invoke the service\"<\/span>);\r\n    Console.WriteLine(<span class=\"str\">\"Press ESC to terminate\"<\/span>);\r\n    ConsoleKeyInfo cki;\r\n    \r\n    AuthenticationContext _ac = <\/pre>\n<pre class=\"csharpcode\">       <span class=\"kwrd\">new<\/span> AuthenticationContext(<span class=\"str\">\"https:\/\/login.windows.net\/contoso7.onmicrosoft.com\"<\/span>);\r\n    AuthenticationResult _arr = <span class=\"kwrd\">null<\/span>;\r\n\r\n    <span class=\"kwrd\">do<\/span>\r\n    {\r\n        cki = Console.ReadKey(<span class=\"kwrd\">true<\/span>);\r\n        <span class=\"rem\">\/\/ get the access token<\/span>\r\n        _arr = _ac.AcquireToken(<span class=\"str\">\"https:\/\/contoso7.onmicrosoft.com\/RichAPI\"<\/span>, \r\n                                <span class=\"str\">\"be182811-9d0b-45b2-9ffa-52ede2a12230\"<\/span>, \r\n                                <span class=\"kwrd\">new<\/span> Uri(<span class=\"str\">\"http:\/\/whatevah\"<\/span>));\r\n        <span class=\"rem\">\/\/ invoke the web API<\/span>\r\n        <span class=\"kwrd\">string<\/span> result = <span class=\"kwrd\">string<\/span>.Empty;\r\n        HttpClient httpClient = <span class=\"kwrd\">new<\/span> HttpClient();\r\n        httpClient.DefaultRequestHeaders.Authorization =\r\n            <span class=\"kwrd\">new<\/span> AuthenticationHeaderValue(<span class=\"str\">\"Bearer\"<\/span>, _arr.AccessToken);                \r\n        HttpResponseMessage response = httpClient.GetAsync(<span class=\"str\">\"http:\/\/localhost:9000\/api\/Values\"<\/span>).Result;\r\n        <span class=\"rem\">\/\/ display the result<\/span>\r\n        <span class=\"kwrd\">if<\/span> (response.IsSuccessStatusCode)\r\n        {\r\n            result = response.Content.ReadAsStringAsync().Result;                    \r\n            Console.WriteLine(<span class=\"str\">\"==&gt; Successfully invoked the service\"<\/span>);\r\n            Console.WriteLine(result);\r\n        }\r\n\r\n    } <span class=\"kwrd\">while<\/span> (cki.Key != ConsoleKey.Escape);\r\n}\r\n<\/pre>\n<style type=\"text\/css\">.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }\n<\/style>\n<p>This is a very classic ADAL client. Getting the token requires the usual 2 lines of code (the settings are straight from the client registered for calling the API in the MSDN Magazine , the rest is showing some text and performing the actual REST call. <\/p>\n<p>Want to see this moving? Start both projects and trigger a call.<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image3.png\"><img loading=\"lazy\" decoding=\"async\" title=\"image\" style=\"border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-top-width: 0px\" border=\"0\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image_thumb3.png\" width=\"640\" height=\"480\"><\/a><\/p>\n<p>Sign in as any user in your tenant, and you\u2019ll get to something like the screen below:<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image4.png\"><img loading=\"lazy\" decoding=\"async\" title=\"image\" style=\"border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-top-width: 0px\" border=\"0\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/image_thumb4.png\" width=\"640\" height=\"329\"><\/a><\/p>\n<p>Ta-dah! <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-note\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Note\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-note.png\"><\/p>\n<h2>Wrap<\/h2>\n<p>What did we see? In a nutshell:<\/p>\n<ul>\n<li>You don\u2019t need VS2013 and associated tools to use OWIN, VS2012 works just fine\n<li>OWIN can be used in absolutely minimal apps \u2013 including cases in which there\u2019s no web server\n<li>As long as the OWIN pipeline is there, the authentication middleware is happy \u2013 and does its job without requiring any special treatment<\/li>\n<\/ul>\n<p>I don\u2019t know about you, but I find this very promising \u2013 looking forward to have more and more of our claims identity goodness available in similar fashion! <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-winkingsmile\" style=\"border-top-style: none; border-left-style: none; border-bottom-style: none; border-right-style: none\" alt=\"Winking smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/12\/wlEmoticon-winkingsmile.png\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>As you might have sensed, OWIN is slated to occupy a prominent role in our next wave of claims-based identity software (more details soon (I hope)).One question I am getting with increasing frequency is \u201cjust how lightweight is this OWIN thing? Is it going to impose heavy requirements that will prevent me from&#8230;<\/p>\n","protected":false},"author":1,"featured_media":2561,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-2565","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/posts\/2565","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/comments?post=2565"}],"version-history":[{"count":1,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/posts\/2565\/revisions"}],"predecessor-version":[{"id":2566,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/posts\/2565\/revisions\/2566"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/media\/2561"}],"wp:attachment":[{"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/media?parent=2565"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/categories?post=2565"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/tags?post=2565"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}