{"id":2162,"date":"2013-04-29T01:23:27","date_gmt":"2013-04-29T08:23:27","guid":{"rendered":"http:\/\/www.cloudidentity.com\/blog\/?p=2162"},"modified":"2013-04-30T01:20:59","modified_gmt":"2013-04-30T08:20:59","slug":"fun-with-windows-azure-ad-calling-rest-services-from-a-windows-phone-8-app","status":"publish","type":"post","link":"https:\/\/www.cloudidentity.com\/blog\/2013\/04\/29\/fun-with-windows-azure-ad-calling-rest-services-from-a-windows-phone-8-app\/","title":{"rendered":"Fun With Windows Azure AD: Calling REST Services from a Windows Phone 8 App"},"content":{"rendered":"<p>[In short: I put together a quick &amp; dirty sample which shows how you can get a Windows Azure AD token from a Windows Phone 8 application. Total hack, not official guidance, this is my personal blog, yadda yadda yadda.]<\/p>\n<p>Last week we released the <a href=\"http:\/\/blogs.msdn.com\/b\/active_directory_team_blog\/archive\/2013\/04\/22\/developer-preview-of-oauth-code-grant-and-aal-for-windows-store-apps.aspx\">preview of some new interesting Windows Azure AD features<\/a>, a code grant authorization endpoint and <a href=\"https:\/\/www.cloudidentity.com\/blog\/2013\/04\/22\/windows-azure-authentication-library-aal-for-windows-store-a-deep-dive\/\">a version of AAL targeted at Windows Store applications<\/a>.<br \/>\nIn the last few days may of you guys asked me if AAL for Windows Store could also be used for Windows Phone 8 applications: and who can blame you, given the <a href=\"http:\/\/seekingalpha.com\/article\/1381841-windows-phone-continues-to-gain-market-share-thanks-to-nokia\">latest news<\/a>? <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-winkingsmile\" alt=\"Winking smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/wlEmoticon-winkingsmile5.png\" \/><\/p>\n<p>As described in the <a href=\"https:\/\/www.cloudidentity.com\/blog\/2013\/04\/22\/windows-azure-authentication-library-aal-for-windows-store-a-deep-dive\/\">deep dive post<\/a>, AAL for Windows Store really takes advantage of many of the unique features of the Windows Runtime: a number of those features are not available on the phone, hence AAL for Windows Store will only work on Windows 8 and Windows RT devices.<br \/>\nThat said: does that mean that you cannot take advantage of the great features of Windows Azure AD from your shiny Windows Phone 8 device? Nothing further from the truth.<br \/>\nA library saves you from the hassle of having to deal with protocol and token lifecycle in every app you write, but if you are willing to get your hands a bit dirty you can definitely get something going from scratch <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/wlEmoticon-smile8.png\" \/><\/p>\n<p>Here\u2019s what I did. Since my wife insisted to watch &#8220;Once Upon a Time\u201d, yesterday night I resolved to put together a quick a dirty PoC to show how easy it is to get an access token from a Windows Phone 8 app directly from the Windows Azure endpoint(s). Admittedly using horrible shortcuts (app-global properties for communicating across pages? really?) but I got the thing done in just about 1 hour and 30 mins, which I believe proves my point (especially given that I haven\u2019t touched Windows Phone development tools since <a href=\"http:\/\/www.windowsphone.com\/en-us\/store\/app\/eng-china-dictionary\/e9da80a6-dc22-e011-854c-00237de2db9e\">this guy<\/a> and <a href=\"http:\/\/www.windowsphone.com\/en-us\/store\/app\/eng-japan-dictionary\/d4c45058-fa2c-e011-854c-00237de2db9e\">his brother<\/a>). Tonight I am writing down how it went. Enjoy!<\/p>\n<h2>The General Idea<\/h2>\n<p>The first principle is that I wanted to do as little as possible. I used as starting point the AAL for Windows Store sample <a href=\"http:\/\/go.microsoft.com\/fwlink\/?LinkId=296713\">here<\/a>: I reused the exact same Web API project as my backend (though I had to do a small trick for making it accessible form the emulator), and I used the Windows Store client to create todo entries so that I did not have to implement write operations in my WP8 client. Also: I probably should not mention this, because it is REALLY bad practice, but I did not even bother to create a new serviceprincipal and permission entries for the WP8 client: I reused the settings already in place. Professional driver on a closed course, do not attempt! <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/wlEmoticon-smile8.png\" \/> Always register separate entries for your clients or you\u2019ll end up with an unmanageable mess.<\/p>\n<p>About the WP8 client itself: I decided to start with an empty WP8 app, and have the bare minimum:<\/p>\n<ul>\n<li>a home page, with buttons for triggering the \u201csign in\u201d and for calling a read operation of the Web API backend<\/li>\n<li>a page for taking care of the \u201csign in\u201d flow<\/li>\n<\/ul>\n<p>The code in this project is <em>purposefully<\/em> not very reusable. If this post serves a purpose, it should be to help you to grok how the protocol flow works: reusing this quick &amp; dirty code \u201cas is\u201d would not be a very good idea, given that working at the protocol level means you are now taking on the responsibility (normally on the library) of implementing a flow that is sound and secure.<\/p>\n<p>And now, without further ado\u2026<\/p>\n<h2>The Windows Phone 8 App Client<\/h2>\n<p>I started with an empty Windows Phone application, which I added as a new project to the existing solution and added it right away in the multi-start debug settings.<\/p>\n<h3>Global Settings<\/h3>\n<p>Now, what to do next? Let\u2019s think for a moment. I want the app to be able to obtain an access token from Windows Azure AD.\u00a0 From the work with AAL, we know that this entails providing some key coordinated describing the client itself (client ID, return URI), the resource I want to access (resource URI) and the Windows Azure AD tenant I want to work with.<\/p>\n<p>Given that I want the authentication flow to take place in its own page, I need a way to get those coordinates in that page; furthermore, I need to extract the access token (and whatever else I might want, like the refresh token) from the sign in page and make it available to the calling page.<br \/>\nI could pass those parameters in the querystring of the page on navigation events, but I\u2019ll go with the brute force approach instead: I\u2019ll shove all important settings in global properties. Below you can see the main ones, in App.xaml.cs.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> <span class=\"kwrd\">partial<\/span> <span class=\"kwrd\">class<\/span> App : Application\r\n{\r\n    <span class=\"rem\">\/\/\/ &lt;summary&gt;<\/span>\r\n    <span class=\"rem\">\/\/\/ Provides easy access to the root frame of the Phone Application.<\/span>\r\n    <span class=\"rem\">\/\/\/ &lt;\/summary&gt;<\/span>\r\n    <span class=\"rem\">\/\/\/ &lt;returns&gt;The root frame of the Phone Application.&lt;\/returns&gt;<\/span>\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">static<\/span> PhoneApplicationFrame RootFrame { get; <span class=\"kwrd\">private<\/span> set; }\r\n\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">string<\/span> RedirectUri {get; set;} \r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">string<\/span> DomainName {get; set;}\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">string<\/span> ClientID {get; set;}\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">string<\/span> Resource {get; set;}\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">string<\/span> Code {get; set;} \r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">string<\/span> AccessToken {get; set;}<\/pre>\n<style type=\"text\/css\"><!--\n.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>Given that I just want to see the flow work, I won\u2019t add any fancy configuration and initialize the scenario coordinates as hardcoded values at construction time:<\/p>\n<pre class=\"csharpcode\"><span class=\"rem\">\/\/\/ &lt;summary&gt;<\/span>\r\n<span class=\"rem\">\/\/\/ Constructor for the Application object.<\/span>\r\n<span class=\"rem\">\/\/\/ &lt;\/summary&gt;<\/span>\r\n<span class=\"kwrd\">public<\/span> App()\r\n{\r\n    <span class=\"rem\">\/\/ Global handler for uncaught exceptions.<\/span>\r\n    UnhandledException += Application_UnhandledException;\r\n\r\n        <span class=\"rem\">\/\/ ...default stuff omitted for brevity, keep everything as you find it<\/span>\r\n\r\n    RedirectUri = <span class=\"str\">\"http:\/\/whatevah\"<\/span>;\r\n    DomainName = <span class=\"str\">\"treyresearch1.onmicrosoft.com\"<\/span>;\r\n    ClientID = <span class=\"str\">\"4a491cff-73a9-4a45-b274-b5836a723b14\"<\/span>;\r\n    Resource = <span class=\"str\">\"http:\/\/localhost:8643\/\"<\/span>;\r\n    Code = AccessToken = <span class=\"kwrd\">string<\/span>.Empty;\r\n}<\/pre>\n<style type=\"text\/css\"><!--\n.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<h3>The Main Page<\/h3>\n<p>With the coordinates being taken care of, let\u2019s focus to the main page from the template. Let\u2019s add the couple of buttons I mentioned earlier and hook them up to click event handlers stubs.<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image47.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-width: 0px;\" title=\"image\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image_thumb47.png\" width=\"600\" height=\"368\" border=\"0\" \/><\/a><\/p>\n<p>Then, let\u2019s move to the C# code for the page.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> <span class=\"kwrd\">partial<\/span> <span class=\"kwrd\">class<\/span> MainPage : PhoneApplicationPage\r\n{\r\n    App app;\r\n    <span class=\"rem\">\/\/ Constructor<\/span>\r\n    <span class=\"kwrd\">public<\/span> MainPage()\r\n    {\r\n        InitializeComponent();\r\n        app = App.Current <span class=\"kwrd\">as<\/span> App;\r\n    }<\/pre>\n<pre class=\"csharpcode\">    <span class=\"kwrd\">protected<\/span> <span class=\"kwrd\">override<\/span> <span class=\"kwrd\">void<\/span> OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\r\n    {\r\n        <span class=\"kwrd\">base<\/span>.OnNavigatedTo(e);        \r\n        <span class=\"kwrd\">if<\/span> (app.AccessToken != <span class=\"kwrd\">string<\/span>.Empty)\r\n        {\r\n            signInbtn.Visibility = System.Windows.Visibility.Collapsed;\r\n            callSvcbtn.IsEnabled = <span class=\"kwrd\">true<\/span>;\r\n        }\r\n        <span class=\"kwrd\">else<\/span>\r\n        {\r\n            signInbtn.Visibility = System.Windows.Visibility.Visible;\r\n            callSvcbtn.IsEnabled = <span class=\"kwrd\">false<\/span>;\r\n        }\r\n    }<\/pre>\n<style type=\"text\/css\"><!--\n.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>Before everything, I added a shorthand for the application object to make access to coordinates and tokens handy.<\/p>\n<p>Then, I added some UI management logic in the OnNavigatedTo event. The idea is simple: when there is no token in the global property, I need to display the sign in button (and I cannot call the service just yet, hence the corresponding button must be disabled).<br \/>\nConversely, if I do have a token I should no longer display the sign in button and I should ensure that the service calling button is enabled.<br \/>\nThe above is really really coarse: the flow does provide me with expiration data and a refresh token, which I could use for a more sophisticated token lifecycle management, but I wanted to do the bare minimum.<\/p>\n<p>Done the above, let\u2019s move to the service calling logic. Below you can find the familiar OAuth2 bearer-protected REST call calling logic.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">private<\/span> <span class=\"kwrd\">void<\/span> callSvcbtn_Click(<span class=\"kwrd\">object<\/span> sender, RoutedEventArgs e)\r\n{\r\n     HttpWebRequest hwr = WebRequest.Create(<span class=\"kwrd\">new<\/span> Uri(<span class=\"str\">\"http:\/\/192.168.1.42:8643\/\"<\/span>+<span class=\"str\">\"api\/todolist\"<\/span>)) <span class=\"kwrd\">as<\/span> HttpWebRequest;\r\n     hwr.Headers[System.Net.HttpRequestHeader.Authorization] = <span class=\"str\">\"Bearer \"<\/span> + app.AccessToken;\r\n    hwr.BeginGetResponse(GetResponseCallback,hwr); \r\n}\r\n\r\n<span class=\"kwrd\">private<\/span>  <span class=\"kwrd\">void<\/span> GetResponseCallback(IAsyncResult rez)\r\n{\r\n    HttpWebRequest hwr = rez.AsyncState <span class=\"kwrd\">as<\/span> HttpWebRequest;\r\n    HttpWebResponse response = hwr.EndGetResponse(rez) <span class=\"kwrd\">as<\/span> HttpWebResponse;\r\n    <span class=\"kwrd\">string<\/span> a = (<span class=\"kwrd\">new<\/span> StreamReader(response.GetResponseStream(), Encoding.UTF8)).ReadToEnd();\r\n\r\n    Dispatcher.BeginInvoke(() =&gt;\r\n    {\r\n        MessageBox.Show(a);\r\n    }); \r\n}<\/pre>\n<style type=\"text\/css\"><!--\n.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 click handler initializes a new request for the intended API and add to it the access token as the authorization header. You might have noticed that I am using an IP address in the resource URL: the reason is that in order to make an app running in the WP8 emulator see the IIS Express on the local machine you have to go through some extra config, which ends up entailing using the IPv4 address of your dev box. <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/windowsphone\/develop\/jj684580%28v=vs.105%29.aspx#BKMK_ReconfiguringthesolutionwhenhostingtheservicewithIISExpress\">Instructions here!<\/a><br \/>\nThe GetResponseCallback method retrieves the response, and (courtesy of the dispatcher, super-handy when you want stuff to happen in the UI thread) displays it in a dialog.<br \/>\nLike the rest of the post, everything naively without any error management.<\/p>\n<p>The last thing to fill in is the handler for the sign in button:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">private<\/span> <span class=\"kwrd\">void<\/span> signInbtn_Click(<span class=\"kwrd\">object<\/span> sender, RoutedEventArgs e)\r\n{\r\n    NavigationService.Navigate(<span class=\"kwrd\">new<\/span> Uri(<span class=\"str\">\"\/SignIn.xaml\"<\/span>,UriKind.Relative));\r\n}<\/pre>\n<style type=\"text\/css\"><!--\n.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>Yep, it looks like I need to add a page called SignIn.<\/p>\n<h3>The Sign In Page<\/h3>\n<p>Below you can see the sign in page, which I added to the main project.<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image42.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;\" title=\"image\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image_thumb42.png\" width=\"600\" height=\"393\" border=\"0\" \/><\/a><\/p>\n<p>Apart from the omnipresent titles, the page contains\u2026 a WebBrowser object. As you can imagine, the job of that browser will be to render the UI required by the Authorization endpoint. Let\u2019s take a look at the code, piece by piece.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> <span class=\"kwrd\">partial<\/span> <span class=\"kwrd\">class<\/span> SignIn : PhoneApplicationPage\r\n{\r\n    App app = (App.Current <span class=\"kwrd\">as<\/span> App);\r\n\r\n    <span class=\"kwrd\">public<\/span> SignIn()\r\n    {\r\n        InitializeComponent();\r\n        myBrowser.IsScriptEnabled = <span class=\"kwrd\">true<\/span>;\r\n    }\r\n\r\n    <span class=\"kwrd\">protected<\/span> <span class=\"kwrd\">override<\/span> <span class=\"kwrd\">void<\/span> OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)\r\n    {\r\n        <span class=\"kwrd\">base<\/span>.OnNavigatedTo(e);\r\n\r\n        <span class=\"kwrd\">string<\/span> authURL = <span class=\"kwrd\">string<\/span>.Format(\r\n            <span class=\"str\">\"https:\/\/login.windows.net\/{0}\/oauth2\/authorize?response_type=code&amp;resource={1}&amp;client_id={2}&amp;redirect_uri={3}\"<\/span>,\r\n            app.DomainName,<\/pre>\n<pre class=\"csharpcode\">            app.Resource,<\/pre>\n<pre class=\"csharpcode\">            app.ClientID,<\/pre>\n<pre class=\"csharpcode\">            app.RedirectUri);\r\n        <span class=\"rem\">\/\/navigate to it<\/span>\r\n        myBrowser.Navigate(<span class=\"kwrd\">new<\/span> Uri(authURL));            \r\n    }<\/pre>\n<style type=\"text\/css\"><!--\n.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 page creates the usual shorthand for the app object.<br \/>\nThe constructor ensures that the WebBrowser will support JavaScript (off by default).<br \/>\nThe page event OnNavigatedTo kicks in the sign in flow as soon as the page is reached.<br \/>\nFirst, it creates the Windows Azure AD preview Authorization endpoint string, by instantiating in the current URL template the necessary coordinates; then it passes it to the browser control to navigate to it.<\/p>\n<p>Form this moment on, all the action will be triggered by the events raised by the browser control. Namely: the user will interact with whatever credential gathering will be presented by Windows Azure AD, and at the end of the Authorize portion of the flow the browser will be redirected to the return URI. Given that such URI might not correspond to an actual endpoint (as it is the case here) we need to detect that the flow is heading there before the browser attempts to render a non-existent page: we do that by checking for the return URI in the Navigating event.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">private<\/span> <span class=\"kwrd\">void<\/span> Navigating(<span class=\"kwrd\">object<\/span> sender, NavigatingEventArgs e)\r\n{\r\n    <span class=\"kwrd\">string<\/span> returnURL = e.Uri.ToString();    \r\n    <span class=\"kwrd\">if<\/span> (returnURL.StartsWith(app.RedirectUri))\r\n    {\r\n        app.Code = e.Uri.Query.Remove(0,6);\r\n        e.Cancel = <span class=\"kwrd\">true<\/span>;\r\n        myBrowser.Visibility = System.Windows.Visibility.Collapsed;\r\n        GetToken();                \r\n    }            \r\n}<\/pre>\n<style type=\"text\/css\"><!--\n.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 code is really easy: check if the requested URL begins with the return URI, and if it does extract the code (by clipping \u2018?code=\u2019 from the query), stop the browser navigation, hide the browser control and trigger the next stage of the token acquisition logic (in the custom method GetToken).<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">private<\/span> <span class=\"kwrd\">void<\/span> GetToken()\r\n{\r\n    HttpWebRequest hwr = \r\n        WebRequest.Create(\r\n            <span class=\"kwrd\">string<\/span>.Format(<span class=\"str\">\"https:\/\/login.windows.net\/{0}\/oauth2\/token\"<\/span>, \r\n                           app.DomainName)) <span class=\"kwrd\">as<\/span> HttpWebRequest;\r\n    hwr.Method = <span class=\"str\">\"POST\"<\/span>;\r\n    hwr.ContentType = <span class=\"str\">\"application\/x-www-form-urlencoded\"<\/span>;\r\n    hwr.BeginGetRequestStream(<span class=\"kwrd\">new<\/span> AsyncCallback(SendTokenEndpointRequest), hwr);\r\n}<\/pre>\n<style type=\"text\/css\"><!--\n.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>GetToken prepares a new POST request for the Windows Azure AD token endpoint, then leaves to SendTokenEndpointRequest the asynchronous task of pumping up the request bits.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">private<\/span> <span class=\"kwrd\">void<\/span> SendTokenEndpointRequest(IAsyncResult rez)\r\n{\r\n    HttpWebRequest hwr = rez.AsyncState <span class=\"kwrd\">as<\/span> HttpWebRequest;   \r\n    <span class=\"kwrd\">byte<\/span>[] bodyBits = Encoding.UTF8.GetBytes(\r\n        <span class=\"kwrd\">string<\/span>.Format(\r\n            <span class=\"str\">\"grant_type=authorization_code&amp;code={0}&amp;client_id={1}&amp;redirect_uri={2}\"<\/span>,\r\n            app.Code, \r\n            app.ClientID, \r\n            HttpUtility.UrlEncode(app.RedirectUri)));\r\n    Stream st = hwr.EndGetRequestStream(rez);\r\n    st.Write(bodyBits, 0, bodyBits.Length);\r\n    st.Close();\r\n    hwr.BeginGetResponse(<span class=\"kwrd\">new<\/span> AsyncCallback(RetrieveTokenEndpointResponse), hwr);\r\n}<\/pre>\n<style type=\"text\/css\"><!--\n.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>SendTokenEndpointRequest prepares the body of the request by crafting the message that the Token endpoint expects, including the client coordinates (minus the secret, given that this is not a confidential client just like an Windows Store app) and the code received form the authorization endpoint.<br \/>\nThat done, it pumps it to the Token endpoint and leaves to RetrieveTokenEndpointResponse the asynchronous task of retrieving the bits of the response.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">private<\/span> <span class=\"kwrd\">void<\/span> RetrieveTokenEndpointResponse(IAsyncResult rez)\r\n{\r\n    HttpWebRequest hwr = rez.AsyncState <span class=\"kwrd\">as<\/span> HttpWebRequest;\r\n    HttpWebResponse resp = hwr.EndGetResponse(rez) <span class=\"kwrd\">as<\/span> HttpWebResponse;\r\n\r\n    StreamReader sr = <span class=\"kwrd\">new<\/span> StreamReader(resp.GetResponseStream());\r\n    <span class=\"kwrd\">string<\/span> responseString = sr.ReadToEnd();\r\n    JObject jo = JsonConvert.DeserializeObject(responseString) <span class=\"kwrd\">as<\/span> JObject;\r\n    app.AccessToken = (<span class=\"kwrd\">string<\/span>)jo[<span class=\"str\">\"access_token\"<\/span>];\r\n\r\n    Dispatcher.BeginInvoke(() =&gt;\r\n    {\r\n        NavigationService.GoBack();\r\n    }); \r\n}<\/pre>\n<p>RetrieveTokenEndpointResponse deserializes the response in a string, then (thanks to the magical <a href=\"http:\/\/json.codeplex.com\/\">Json.NET<\/a>: I <em>love <\/em>that library!) parses it in a JSON object and extracts from it the access token. The access token is then saved in the global property, ready to be used by the service calling method in the main page.<br \/>\nThe method closes with another UI thread operation: now that the token has been obtained, the app can go back to the main page where it will be put to use, concluding the logic we need to complete the application flow.<\/p>\n<p>Note: I extract just the access token because I am lazy, but the Token endpoint response contains everything you need:<\/p>\n<pre class=\"csharpcode\">{\r\n  <span class=\"str\">\"access_token\"<\/span>: <span class=\"str\">\"eyJ0eXAiOiJKV1QiLBJhbGciOiJSUzI1NiI[\u2026]jvsuXYGT1AvwN3BLdwvEG-vxsnSFIgRc_T6gYGtQgYBQezhLkvRA\"<\/span>,\r\n  <span class=\"str\">\"token_type\"<\/span>: <span class=\"str\">\"Bearer\"<\/span>,\r\n  <span class=\"str\">\"expires_in\"<\/span>: <span class=\"str\">\"28799\"<\/span>,\r\n  <span class=\"str\">\"expires_on\"<\/span>: <span class=\"str\">\"1367336769\"<\/span>,\r\n  <span class=\"str\">\"refresh_token\"<\/span>: <span class=\"str\">\"AAAAAAAAB0muTENxe1qIJDFMMyUMiFt[\u2026]Q-Hq3WRqO3XUgAA\"<\/span>,\r\n  <span class=\"str\">\"scope\"<\/span>: <span class=\"str\">\"user_impersonation\"<\/span>\r\n}<\/pre>\n<style type=\"text\/css\"><!--\n.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>Just wanted to make sure you don\u2019t forget what\u2019s in there. That said, let\u2019s see this baby in action!<\/p>\n<h2>Running the Project<\/h2>\n<p>As mentioned above, running this solution in the emulator requires doing some extra work to make IIS Express visible: all the instructions are <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/windowsphone\/develop\/jj684580%28v=vs.105%29.aspx#BKMK_ReconfiguringthesolutionwhenhostingtheservicewithIISExpress\">here<\/a>.<\/p>\n<p>That said, let\u2019s have some fun!<br \/>\nThe idea is that on F5 the solution will start all projects: the Windows Store client, the Web API and the WP8 client. We\u2019ll use the Windows Store client for creating some todo items, then we\u2019ll use the WP8 client to read them.<\/p>\n<p>Here there\u2019s the test page of the Web API\u2026<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image43.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-width: 0px;\" title=\"image\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image_thumb43.png\" width=\"604\" height=\"331\" border=\"0\" \/><\/a><\/p>\n<p>\u2026and here there\u2019s the Windows Store client from the original sample. Let\u2019s use it to add some entries (not exactly todo\u2019s, but yesterday I had an earworm\u2026 do you have it too now? <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-winkingsmile\" alt=\"Winking smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/wlEmoticon-winkingsmile5.png\" \/>).<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image36.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; padding-top: 0px; padding-left: 0px; margin: 0px; display: inline; padding-right: 0px; border-width: 0px;\" title=\"image\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image_thumb36.png\" width=\"604\" height=\"339\" border=\"0\" \/><\/a><\/p>\n<p>Great! Let\u2019s do few ALT+TAB to get to the emulator, already loaded with our app (titled as the Spanish conversations between Caleb and Sean <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-winkingsmile\" alt=\"Winking smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/wlEmoticon-winkingsmile5.png\" \/>).<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image44.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;\" title=\"image\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image_thumb44.png\" width=\"338\" height=\"614\" border=\"0\" \/><\/a><\/p>\n<p>Hitting sign in lands us to the Windows Azure authorization endpoint page, which in turn bounces us around to gather user credentials. Note: the browser is purposefully smaller than the entire page for showing you what\u2019s going on here, otherwise you might confuse it with a full browser handover.<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image45.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;\" title=\"image\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image_thumb45.png\" width=\"342\" height=\"608\" border=\"0\" \/><\/a><\/p>\n<p>Entering the right credential makes the magic described above happen, then bounces us back to the main page. From the fact that the sign in button is gone and the call service button is active we can tell that the access token property is non-empty.<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image46.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;\" title=\"image\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image_thumb46.png\" width=\"343\" height=\"616\" border=\"0\" \/><\/a><\/p>\n<p>If we click the call service button, ta-dah! We get back the todos uploaded from the other client.<\/p>\n<p><a href=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image40.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-width: 0px;\" title=\"image\" alt=\"image\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/image_thumb40.png\" width=\"346\" height=\"617\" border=\"0\" \/><\/a><\/p>\n<p>Q.E.D.<\/p>\n<h2>Summary<\/h2>\n<p>Yes, I agree: a library would be faster &amp; easier to use, hopefully more robust and less code-invasive. However if you want to take advantage of Windows Azure AD from your Windows Phone 8 applications hitting the protocol endpoints is definitely an option!<\/p>\n<p>This would be a good time to remind you that the code I write here is <strong><span style=\"text-decoration: underline;\"><em>not<\/em><\/span><\/strong> official guidance and really does not want to be: it\u2019s just stuff I like to do when the TV is not giving me all the ROI I\u2019d expect from that fancy cable box\u2026 take inspiration if you want, but please make sure to do due diligence before doing anything more than experimentations with it.<\/p>\n<p>That said, writing apps for devices is FUN! Have a good time and keep the feedback coming <img decoding=\"async\" class=\"wlEmoticon wlEmoticon-smile\" alt=\"Smile\" src=\"https:\/\/www.cloudidentity.com\/blog\/wp-content\/uploads\/2013\/04\/wlEmoticon-smile8.png\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>[In short: I put together a quick &amp; dirty sample which shows how you can get a Windows Azure AD token from a Windows Phone 8 application. Total hack, not official guidance, this is my personal blog, yadda yadda yadda.] Last week we released the preview of some new interesting Windows Azure AD&#8230;<\/p>\n","protected":false},"author":1,"featured_media":2172,"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-2162","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\/2162","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=2162"}],"version-history":[{"count":3,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/posts\/2162\/revisions"}],"predecessor-version":[{"id":2181,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/posts\/2162\/revisions\/2181"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/media\/2172"}],"wp:attachment":[{"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/media?parent=2162"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/categories?post=2162"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.cloudidentity.com\/blog\/wp-json\/wp\/v2\/tags?post=2162"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}