{"id":31918,"date":"2017-06-07T08:53:01","date_gmt":"2017-06-07T15:53:01","guid":{"rendered":"https:\/\/blog.xamarin.com\/?p=31918"},"modified":"2017-06-07T08:53:01","modified_gmt":"2017-06-07T15:53:01","slug":"enterprise-apps-made-easy-updated-libraries-apis","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/xamarin\/enterprise-apps-made-easy-updated-libraries-apis\/","title":{"rendered":"Enterprise Apps Made Easy with New Authentication &amp; Microsoft Graph Libraries"},"content":{"rendered":"<p>\t\t\t\tMany enterprise organizations are making the move to the cloud and building mobile apps for internal use. It&#8217;s increasingly common to see enterprises with entire suites of internal apps to help make employees more productive, from expense reporting to leave management, even carpooling. Rather than rolling a brand new infrastructure for these apps, organizations can take advantage of Active Directory (AD) and consume existing APIs that provide data such as contacts, email, calendar, org trees, and more. Thanks to brand new and improved libraries for authenticating users and consuming the Microsoft Graph, building such applications has become much easier.<\/p>\n<p>In this blog post, we&#8217;ll be building a sample application for managing leave (sick time, parental leave, etc.) using the Microsoft Authentication Library (MSAL) and Microsoft Graph APIs.<\/p>\n<h2>Step 1: Register the Application<\/h2>\n<p>You can register the application by visiting <a href=\"https:\/\/apps.dev.microsoft.com\">https:\/\/apps.dev.microsoft.com<\/a> and clicking on the <strong>Add an app<\/strong> button. Once you enter the app details, be sure to note the <strong>Application Id<\/strong> generated. Under the <strong>Add Platforms<\/strong> section, you can now register an application to multiple platforms. This makes life simpler by having one application ID for various implementations of the same app across mobile and web.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-31922\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/02-add-platforms.png\" alt=\"\" width=\"500\" \/><\/p>\n<p>Click <strong>Native Application<\/strong>. This will allow mobile applications to access the organization&#8217;s AD and Graph API.<\/p>\n<p>Once supported platforms are added, we can add permissions on the same screen. In this case, I&#8217;ve given the permissions\u00a0<code>\"User.Read\"<\/code>, <code>\"User.ReadBasic.All\"<\/code>, and<code>\"Mail.Send\"<\/code>. These are required to get a user&#8217;s information and send an email to his or her manager to let them know the user will be out for the day.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-31923\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/03-platforms-and-permissions.png\" alt=\"\" width=\"600\" \/><\/p>\n<p>Save the changes, and your app is now registered with the organization&#8217;s Active Directory!<\/p>\n<h2>Step 2: Building the Mobile Apps<\/h2>\n<p>Create a blank Xamarin.Forms app with the Portable Class Library (PCL) option to share code across platforms. For this library, <a href=\"https:\/\/developer.xamarin.com\/guides\/cross-platform\/application_fundamentals\/pcl\/introduction_to_portable_class_libraries\/#Editing_PCL_Settings\">ensure the profile is set to <code>Profile7<\/code><\/a>. Add the <strong>Microsoft.Client.Identity<\/strong> and <strong>Microsoft.Graph<\/strong> NuGet packages to all projects. If you don&#8217;t see them in the NuGet Package Manager, check <strong>Include Prerelease<\/strong>.<\/p>\n<p>First, we need to authenticate the user. This is done with the Microsoft Authentication Library (MSAL) <code>PublicClientApplication<\/code> class. Inside of <code>App.xaml.cs<\/code>, add the following code:<\/p>\n<pre class=\"EnlighterJSRAW\">public static PublicClientApplication IdentityClientApp = null;\npublic static UIParent UiParent = null;\n\n\/\/ AD application identifier and requested permissions, or scopes.\npublic static string ClientID = \"7214e6cd-85ad-4433-9d13-f2631e1d4142\"; \/\/ TODO: Replace this with the Application ID from Step #1.\npublic static string[] Scopes = { \"User.Read\", \"User.ReadBasic.All \", \"Mail.Send\" };\n\npublic App()\n{\n   InitializeComponent();\n   IdentityClientApp = new PublicClientApplication(ClientID);\n   MainPage = new Leaver.MainPage();\n}\n<\/pre>\n<p>Next, we need to build out a login page. Create a <code>GraphServiceClient<\/code> in <code>MainPage.xaml.cs<\/code>, which will be responsible for calling all future Graph APIs. You can see a sample implementation in the code below:<\/p>\n<pre class=\"EnlighterJSRAW\">\nprivate async Task CreateGraphClientAsync()\n{\n   try {\n     Client = new GraphServiceClient(\"https:\/\/graph.microsoft.com\/v1.0\",\n           new DelegateAuthenticationProvider(async (requestMessage) =&gt;\n           {\n              var tokenRequest = await App.IdentityClientApp.AcquireTokenAsync(App.Scopes, App.UiParent).ConfigureAwait(false);\n              requestMessage.Headers.Authorization = new AuthenticationHeaderValue(\"bearer\", tokenRequest.AccessToken);\n           }));\n           Me = await Client.Me.Request().GetAsync();\n           Username.Text = $\"Welcome {((User)Me).DisplayName}\";\n           return true;\n        }\n        catch (MsalException ex)\n        {\n           await DisplayAlert(\"Error\", ex.Message, \"OK\", \"Cancel\");\n           return false;\n        }\n}\n<\/pre>\n<p>Now that we&#8217;ve initialized our <code>GraphServiceClient<\/code>, we can use the Graph API to send an email:<\/p>\n<pre class=\"EnlighterJSRAW\">private async void SendEmail(Message message)\n{\n   if (!UserExists)\n      await CreateGraphClientAsync();\n   var req = Client.Me.SendMail(message);\n   await req.Request().PostAsync();\n   Status.Text = $\"Email sent to your manager { ((User)Manager).DisplayName }, CC: you\";\n}\n<\/pre>\n<h2>Step 3: Platform-Specific Modifications<\/h2>\n<p>Login functionality with MSAL was previously implemented in Xamarin.Forms by using <a href=\"https:\/\/developer.xamarin.com\/guides\/xamarin-forms\/application-fundamentals\/custom-renderer\/\">custom renderers<\/a>. With this new, production-ready preview of MSAL, this functionality is implemented using a URL scheme to make our lives easier. This automatically initiates the authentication flow and completes the login flow.<\/p>\n<h3>iOS<\/h3>\n<p>In Visual Studio 2017 Preview 3, we&#8217;ve added a UI editor for <code>Info.plist<\/code> where you can register your custom URL scheme:<\/p>\n<p><img decoding=\"async\" class=\"aligncenter wp-image-31928\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/04-ios-info-plist-editor.png\" alt=\"\" width=\"600\" \/><\/p>\n<p>The completed authentication process can be handled in <code>AppDelegate<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\">public override bool FinishedLaunching(UIApplication app, NSDictionary options)\n{\n   global::Xamarin.Forms.Forms.Init();\n   LoadApplication(new App());\n   App.IdentityClientApp.RedirectUri = \"msal7214e6cd-85ad-4433-9d13-f2631e1d4142:\/\/auth\";\n   return base.FinishedLaunching(app, options);\n}\n\npublic override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)\n{\n   AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs(url);\n   return true;\n}\n<\/pre>\n<h3>Android<\/h3>\n<p>Open <code>AndroidManifest.xml<\/code> and add the <code>BrowserTabActivity<\/code> with <code>intent-filter<\/code> to register the URL scheme:<\/p>\n<pre class=\"EnlighterJSRAW\">\n\n    \n      \n        \n        \n        \n        \n      \n    \n  \n<\/pre>\n<p>The completed authentication process can be handled in our app&#8217;s <code>MainActivity<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\">protected override void OnCreate(Bundle bundle)\n{\n   TabLayoutResource = Resource.Layout.Tabbar;\n   ToolbarResource = Resource.Layout.Toolbar;\n   base.OnCreate(bundle);\n   global::Xamarin.Forms.Forms.Init(this, bundle);\n   LoadApplication(new App());\n   App.IdentityClientApp.RedirectUri = \"msal7214e6cd-85ad-4433-9d13-f2631e1d4142:\/\/auth\";\n   App.UiParent = new UIParent(Xamarin.Forms.Forms.Context as Activity);\n}\nprotected override void OnActivityResult(int requestCode, Result resultCode, Intent data)\n{\n   base.OnActivityResult(requestCode, resultCode, data);\n   AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs(requestCode, resultCode, data);\n}\n<\/pre>\n<h3>Windows<\/h3>\n<p>The Microsoft Authentication Library doesn&#8217;t require any specific platform modifications to handle the login process for Universal Windows Platform (UWP) apps.<\/p>\n<h2>Step 4: Run the App<\/h2>\n<p>Once the steps are complete, run the app to see our completed leave scheduling application for iOS, Android, and Windows using Xamarin.Forms, the Microsoft Authentication Library, and the Microsoft Graph APIs.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-31929\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/05-application-running.gif\" alt=\"\" width=\"600\" \/><\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-31930\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/44\/2019\/03\/04-b-app-result.png\" alt=\"\" width=\"600\" \/><\/p>\n<h3>Conclusion<\/h3>\n<p><a href=\"https:\/\/github.com\/AzureAD\/microsoft-authentication-library-for-dotnet\">Microsoft Authentication Library<\/a> (MSAL) makes it easy to integrate apps with existing Active Directories (AD) and add authentication in just a few lines of code. The <a href=\"https:\/\/developer.microsoft.com\/en-us\/graph\/\">Microsoft Graph API<\/a> enables access various services available to our users, such as mail, calendar, people, and SharePoint, all from a single API. To try out the mobile app built in this blog post, <a href=\"https:\/\/github.com\/mayur-tendulkar\/\">download the sample from my GitHub<\/a>.\t\t<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Many enterprise organizations are making the move to the cloud and building mobile apps for internal use. It&#8217;s increasingly common to see enterprises with entire suites of internal apps to help make employees more productive, from expense reporting to leave management, even carpooling. Rather than rolling a brand new infrastructure for these apps, organizations can [&hellip;]<\/p>\n","protected":false},"author":549,"featured_media":31929,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"tags":[4],"class_list":["post-31918","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-developers","tag-xamarin-platform"],"acf":[],"blog_post_summary":"<p>Many enterprise organizations are making the move to the cloud and building mobile apps for internal use. It&#8217;s increasingly common to see enterprises with entire suites of internal apps to help make employees more productive, from expense reporting to leave management, even carpooling. Rather than rolling a brand new infrastructure for these apps, organizations can [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/31918","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/users\/549"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/comments?post=31918"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/posts\/31918\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/media?parent=31918"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/categories?post=31918"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/xamarin\/wp-json\/wp\/v2\/tags?post=31918"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}