This walkthrough assumes you have completed the Getting Started walkthrough and the first lift and shift walkthrough.

Similar documents
Azure Developer Immersions API Management

Azure Developer Immersion Redis Cache

Azure Developer Immersions Application Insights

Azure Developer Immersion Getting Started

Microsoft Cloud Workshops. Microservices and Serverless Architecture - Developer Edition Leader Hackathon guide

Bringing Together One ASP.NET

Developing Intelligent Apps

Using SourceTree on the Development Server

Warewolf User Guide 1: Introduction and Basic Concepts

Getting Started with the Ed-Fi ODS and Ed-Fi ODS API

Configure App Service Authentication for Your Azure Web App

EM L04 Using Workflow to Manage Your Patch Process and Follow CISSP Best Practices

Cloud Enabling.NET Client Applications ---

Hands-On Lab. Windows Azure Virtual Machine Roles. Lab version: Last updated: 12/14/2010. Page 1

Azure Archival Installation Guide

Azure Application Deployment and Management: Service Fabric Create and Manage a Local and Azure hosted Service Fabric Cluster and Application

CUSTOMER PORTAL. Connectors Guide

CHANNEL9 S WINDOWS PHONE 8.1 DEVELOPMENT FOR ABSOLUTE BEGINNERS

Installation Guide. 3CX CRM Plugin for ConnectWise. Single Tenant Version

Welcome to the CP Portal

Info Input Express Network Edition

Telerik Corp. Test Studio Standalone & Visual Studio Plug-In Quick-Start Guide

Getting Started (1.8.7) 9/2/2009

Portable Class Libraries ---

Introduction & Navigation

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

Hands-On Lab New Collaboration Experiences for Development Teams using Team Foundation Server 2013 Lab version: Last updated: 11/25/2013

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

Parish . User Manual

DBXL AZURE INSTALLATION GUIDE

If this is the first time you have run SSMS, I recommend setting up the startup options so that the environment is set up the way you want it.

ReportPlus Embedded Web SDK Guide

Using Dropbox with Node-RED

Real-Time SignalR. Overview

A Quick Tour GETTING STARTED WHAT S IN THIS CHAPTER?

Instructions for Using the Databases

Snapshot Best Practices: Continuous Integration

CAD PPE Hands-on Lab Day 1. Modern App

Contents Getting Started... 3 About Scribe Online and Connectors... 3 Scribe Online Services... 3 CDK Components... 3 Audience... 4 Prerequisites...

Configuring Anonymous Access to Analysis Files in TIBCO Spotfire 7.5

GETTING STARTED GUIDE

Oracle Big Data Cloud Service, Oracle Storage Cloud Service, Oracle Database Cloud Service

PISCES Installation and Getting Started 1

Sample Spark Web-App. Overview. Prerequisites

Partner Integration Portal (PIP) Installation Guide

Configuring GNS3 for CCNA Security Exam (for Windows) Software Requirements to Run GNS3

Kendo UI. Builder by Progress : What's New

Secure Mobile Access Module

0. Introduction On-demand. Manual Backups Full Backup Custom Backup Store Your Data Only Exclude Folders.

Network Rail Brand Hub USER GUIDE

Using Eclipse Che IDE to develop your codebase. Red Hat Developers Documentation Team :15:48 UTC

Getting Started Using HBase in Microsoft Azure HDInsight

BROWSER-BASED SUPPORT CONSOLE USER S GUIDE. 31 January 2017

Web Sites in Production

Learning vrealize Orchestrator in action V M U G L A B

Zephyr Cloud for HipChat

Lab Android Development Environment

Using Microsoft Azure Active Directory MFA as SAML IdP with Pulse Connect Secure. Deployment Guide

Red Hat JBoss Fuse 7.0-TP

Using SQL Developer. Oracle University and Egabi Solutions use only

Working with SQL SERVER EXPRESS

Set-up Server Features and Roles Once the users are created we will move on to setting up the Internet Information Services (IIS) role on the server.

Introduction to application management

Communication. Identity

Web-enable a 5250 application with the IBM WebFacing Tool

Load Balancing VMware Workspace Portal/Identity Manager

Kendo UI. Builder by Progress : Using Kendo UI Designer

ADOBE DREAMWEAVER CS4 BASICS

Learning Objectives. Description. Your AU Expert(s) Trent Earley Behlen Mfg. Co. Shane Wemhoff Behlen Mfg. Co.

Using Eclipse Che IDE to develop your codebase. Red Hat Developers Documentation Team :54:11 UTC

BlackBerry Developer Summit. A02: Rapid Development Leveraging BEMS Services and the AppKinetics Framework

Webnodes Developers Quick Guide

Roxen Content Provider

Website Management with the CMS

Processing Big Data with Hadoop in Azure HDInsight

We start by providing you with an overview of the key feature of the IBM BPM Process Portal.

3 Getting Started with Objects

Your First Windows Form

GoLive will first ask you if your new site will be for one individual or a work group; select for a Single User, and click Next.

Agent and Agent Browser. Updated Friday, January 26, Autotask Corporation

Load Balancing VMware Identity Manager

Serverless Single Page Web Apps, Part Four. CSCI 5828: Foundations of Software Engineering Lecture 24 11/10/2016

ForeScout Extended Module for MobileIron

Amazon AppStream 2.0: SOLIDWORKS Deployment Guide

Workspace Administrator Help File

Lesson 10: Exercise: Tip Calculator as a Universal App

Participant Handbook

EUSurvey OSS Installation Guide

Getting started with Convertigo Mobilizer

PowerExchange for Facebook: How to Configure Open Authentication using the OAuth Utility

EGit/Gerrit Hands-on training #1: Installation and Configuration

Index A, B. Cascading Style Sheets (CSS), 45 Columns, 325 calculations, 330 choice type, 328

SQL Server 2005: Reporting Services

Hands-On Introduction to Queens College Web Sites

InCycle InRelease User Guide

The Centrify browser extension

Lab 4: create a Facebook Messenger bot and connect it to the Watson Conversation service

Discovering Computers & Microsoft Office Office 2010 and Windows 7: Essential Concepts and Skills

Docker on Windows Server 2016

SyncStudio by HandApps Software. A Complete Mobile Database Synchronization Solution. Quick-Start Manual. Release 3.x, June 2017

Transcription:

Azure Developer Immersion In this walkthrough, you are going to put the web API presented by the rgroup app into an Azure API App. Doing this will enable the use of an authentication model which can support various third-party login providers, including Microsoft accounts, which you will be using, but also Google, Twitter, Facebook, and Azure Active Directory. In addition, you will get login mechanisms for mobile apps. The app supports Microsoft account login through the web site already, but adding mobile app support is non-trivial; it is considerably easier through an API App. The authentication system also provides a way to manage credentials for external resource such as Dropbox, Office 365, Yammer, or Salesforce. The API App platform provides a way to show the relevant consent UI, as well as obtain and store the access token for using the external service on behalf of the user. Furthermore, you can use API Apps from Azure Logic Apps, making it possible for your code to supply triggers that run workflows, or to be invoked from a workflow. This walkthrough assumes you have completed the Getting Started walkthrough and the first lift and shift walkthrough. There are three exercises in this walkthrough: 1. API App 2. Create a Test Client App 3. Configure API Access Exercise 1: API App In this first exercise, you will inspect and work with the API App for the rgroup application. 1. Your web browser should still be open to the Visual Studio Online Task Board for your Team Project. If not, open your web browser, access your Team Project and access the Task Board. 2. Drag and drop the card, Complete the 02-API App Walkthrough from the To do column to the In progress column. 3. In Visual Studio 2015, select File Close Solution to close your existing Solution if Visual Studio is running from the previous walkthrough. If not, start Visual Studio 2015. 4. Access the Team Explorer window (View Team Explorer) and activate the Home page (click the Home icon). Until now, the site s web API has been part of the main web app; it contains both MVC controllers for the web pages and Web API controllers. However, we are going to use a separate project for the API because we want to deploy the API endpoints as an API App while leaving the web user interface in a Web App. In fact, there is a project already created.

5. Under the list of Solutions on the Team Explorer home page, double-click on Rg.WebWithApiApp.sln. 6. If prompted to Connect to SQL Server, verify your credentials and click OK. 7. In the Solution Explorer window, select the Solution root node, and then click the Collapse All button on the toolbar. 8. Select Build Build Solution to compile everything and make sure all the NuGet packages are current. While the build runs, continue on reading. 9. In the Rg.Api project, expand the Controllers folder.

If you look in the Rg.Api project s Controllers folder, you will find the same set of classes as in the Rg.Web project s Controllers\Api folder. However, there are a few minor differences. The first is that, while the web app has the [Authorize] attribute on most controllers, this API project does not. That is because you are going get Azure to handle authentication and authorization for you. When you write an API App, you do not put any security handling in your own code at all. Also, as you are going to see later, the way you identify users is slightly different in this code. One feature of API Apps that you will not normally find in Web Apps is the SwaggerConfig.cs file in the App_Start folder (you can open it if you like). Swagger is a system for describing web API, and this code makes metadata describing our endpoints available. Most of this is commented out it is there to show you how you can enable various optional features but the basic functionality is enabled, as is an optional UI for browsing the API. 10. In the Solution Explorer, right-click on the Rg.Api project and choose Publish. 11. In the Publish Web dialog, select Microsoft Azure App Service. 12. In the App Service dialog, click New.

13. Use the Change Type drop-down to make the app type to API App. 14. Change the API App Name to rgroupapixxx where xxx are you initials. The name for the API App must be globally unique. In addition, it needs to be at least eight characters long. 15. The rgroup Resource Group and rgroup-plan App Service Plan should already be selected. If not select them. 16. Verify your settings and then click Create. 17. Wait for the deployment to complete. 18. Back in the Publish Web dialog, click Publish.

19. The Azure App Service Activity pane will show you the API App creation progress. Once the API App has been published, a browser should open with a message saying, This web app has been successfully created. 20. In the browser address bar where the new tab opened, add swagger to the end of the address and press the ENTER key. The browser will navigate to the test UI that enabled by the SwaggerConfig.cs file.

21. Leave this browser open; you will be coming back soon. But first, go to the Azure portal at https://portal.azure.com/ in a new browser tab. 22. Click on Resource groups from the list of actions on the left, find the rgroup resource group in there, and click on it. 23. In addition to the resources created earlier (the SQL server and database, the app plan, and the web app created by you), you should see your API app. 24. The API App is going to need the same database connection string as your web app. If you left it in the Rg.Web project s Web.config, copy it from there (remembering that you need to update the password). Otherwise, go to your web app s Settings in the Azure portal and then, in Application Settings, find the Connection Strings section, click Show connection strings, and copy the value for DefaultConnection. 25. Once you have your connection string, from the list of resources in your Resource Group, select your API App entry in the resource list. 26. In the app host s Settings select Application Settings.

27. In the Connection Strings section, add an entry with a Name of DefaultConnection, and paste in the connection string you just copied as the value. 28. Click Save. 29. Close the Application settings blade. 30. Back in the Settings blade click the API definition option. Azure reads the machine-readable version of the information that you saw a moment ago through Swagger. It provides with the ability to download the Swagger data you saw earlier in a browser UI as a JSON file. The Azure SDK can use this same information to make it easy to use API Apps from client code. You will build a very simple client app that uses this API to demonstrate this. 31. Return to Visual Studio.

Exercise 2: Create a Test Client App In this exercise, you will create a Windows Store app to be a test client of the API App. 1. Right-click on the Solution node in Solution Explorer and select Add New Project. 2. In the list on the left, expand Visual C# Windows Windows 8 Windows. 3. In the middle column of the dialog, select Blank App (Windows 8.1).

4. Make sure the Framework is set to.net Framework 4.6.1. 5. Set the Name of the app to Rg.ClientApp. 6. Click OK to add the project. 7. You will most likely be prompted to get a developer license (see below). Click I Agree if prompted.

8. Click Yes to the User Account Control dialog. 9. When prompted, log in using your Microsoft account. Click Close once your developer license has been acquired. 10. Select Build Build Solution. 11. Now you will add some NuGet references. Right click on the Rg.ClientApp and select Manage NuGet packages. 12. Right-click on the Rg.ClientApp.Windows project and select Manage NuGet Packages. 13. Click the Browse command in the NuGet Package Manager. 14. In the Search box type Bcl and press ENTER. 15. Select Microsoft.Bcl and then click Install at the right. 16. Click OK when prompted to review changes. 17. Click I Accept in the License Acceptance dialog. 18. Now repeat this process and add Microsoft.Bcl.Async and Microsoft.Net.Http. 19. You need to repeat the process one more time but before you search, you need to check the Include prerelease box. 20. Once you do that, search for Microsoft.Azure.AppService and install it. 21. Once done, close the NuGet Package Manager window.

22. Right-click on your new project Rg.ClientApp.Windows in Solution Explorer and choose Add REST API Client. The Add REST API Client dialog appears. 23. Ensure Swagger Url is selected under the Metadata File group. Click the Select Azure Asset button. 24. In the App Service dialog, expand the rgroup folder and select your API app and then click OK. In the Add REST API Client dialog, notice the URL is the same as the one you looked at earlier in the portal. 25. Click OK to complete the Add REST API Client command and wait for it to finish.

Visual Studio downloads the metadata for the API and generates a set of types to enable you to use the API. As it happens, you did not really need this because you have most of the relevant types available in a portable class library. However, this feature is very useful for APIs that do not provide that. It also adds various helper classes for using the API. 26. Look in the added folders and you will see all of these imported types (note your folder names might be slightly different from the screen shot based on your service name). You are not quite ready to use the API yet because most of the methods need to know who the caller is and you have not yet enabled authentication on this API. 27. Now is a good time to commit your changes to your local Git repo. In Solution Explorer, rightclick on the Solution node and select Commit. 28. At the Changes page, enter Add client test app as the commit message. 29. Click Add Work Item by ID and enter the Work Item ID for your current task (jump over to your open Visual Studio Online tab if you do not remember the ID) and click Add.

30. Now, click the Commit button. If prompted to save your changes, select Yes. Doing a commit will quickly save your changes to your local repo but not push them up to Visual Studio Team Services. Move on to the next Exercise.

Exercise 3: Configure API Access In this last exercise for this walkthrough, you will configure access to the API by enabling Microsoft account support. 1. In the Azure portal, go back to the list of resources in your rgroup resource group and select the API App. 2. In the Settings pane, under Features, select Authentication / Authorization. 3. In the Authentication / Authorization blade, change App Service Authentication to On. 4. In the combo-box that appears, select Log in with Microsoft Account. 5. Next, select Microsoft Account from the list of Authentication Providers. To fill this in, you will need to create another Microsoft account application. You need one for each distinct domain. It will not let you register one for the entire azurewebsites.net domain, so you will need a different one for your Web App and one for your API App.

6. Leave this page open and, in another browser tab or window, navigate to http://account.live.com/developers/applications/ and log in with your Microsoft account. 7. Click Create application. 8. Name the application rgroup API and click I accept. 9. On the left, click App Settings. 10. Copy the Client ID and Client secret (v1) from this page into the relevant boxes in the Microsoft Account pane in the Azure portal. In the Microsoft Account Authentication Settings pane in the Azure portal, you need to add two Scopes.

11. Place a check next to the wl.basic and wl.emails Scopes. 12. Click the OK button at the bottom. 13. Back on the Authentication / Authorization blade, click Save. Close the blade. 14. Back on your API App s blade, in the Essentials section, copy your app s URL.

15. Switch back to your tab where you re configuring your Microsoft account settings. Click on the API Settings link. 16. This time, you will need to set the Mobile or desktop client app radio button to Yes. 17. For the redirect URL, paste the URL you have on the clipboard. Then add /.auth/login/microsoftaccount/callback to the end and make sure it s using https. For example: https://rgroupapixxx.azurewebsites.net/.auth/login/microsoftaccount/callback 18. Click Save. 19. You also need to make a change to your API App s code. Return to Visual Studio. 20. Select View Solution Explorer. 21. Inside the Rg.Api project, open apipapp.json. 22. Near the end of this file, between the last two } characters, add a comma and after that add the line highlighted below: { } "$schema": "http://json-schema.org/schemas/2014-11-01/apiapp.json#", "id": "Rg.Api", "namespace": "microsoft.com", "gateway": "2015-01-14", "version": "1.0.0", "title": "Rg.Api", "summary": "", "author": "", "endpoints": { "apidefinition": "/swagger/docs/v1", "status": null }, "authentication": [{"type": "microsoftaccount"}]

You can now publish again to Azure. 23. Select File Save apiapp.json. 24. In the Solution Explorer, right-click on Rg.Api and select Publish. 25. In the Publish Web dialog, click the Publish button. 26. When the app has been published, you will get the Microsoft Authorization page. Authorize your app by clicking Yes. You should then see the successfully publish page like before. 27. If you now return to the Swagger UI (if you do not still have it open, find your API s URL from the Azure portal) and refresh it. 28. If you expand the Test method and GET /api/test then click Try it out, you will see something like: Because the user is now authenticated, our API App is now able to obtain the information associated with this user s Microsoft account. We have now seen that the API requires authentication and that it can get information about the logged in user. Now we can try out the API from our client app. 29. Return to Visual Studio. 30. In the Solution Explorer, in the Rg.Client app, double-click the MainPage.xaml file. Feel free to close or minimize the Output window to give yourself more room. 31. Open Visual Studio s Toolbox pane from the View menu.

32. In the toolbox, under Common XAML Controls, drag a Button onto the page. 33. In the XAML window below the design surface, replace the one line of XAML for the button with the following two lines: <Button x:name="loginbutton" Content="Log in" HorizontalAlignment="Left" Margin="50,50,0,0" VerticalAlignment="Top"/> <Button x:name="getalbumsbutton" Content="Get Albums" HorizontalAlignment="Left" Margin="50,100,0,0" VerticalAlignment="Top"/> 34. On the design surface, double-click the Log in button to add a click handler. You might have to manually switch to the new tab for MainPage.xaml.cs. 35. At the top of the MainPage.xaml.cs file, add these using directives below the existing ones: using Windows.Security.Authentication.Web; using Newtonsoft.Json; using Rg.ClientApp; using Rg.ClientApp.Models; using Windows.Storage; using Microsoft.Azure.AppService; Next you are going to add a field in the code behind. The field s data type will depend on the name you gave your API App. When you used the client code generation earlier, it created a class based on the name of the API App. For example, if your web site was called rgroupapitest, you will find a class called Rgroupapitest. But since your App will have been called something else, you will need to use whatever is the right name for your API. A quick way to find the name of your web app is to look at the folder above the App.xaml file in the Solution Explorer. In the example below the folder is rgroupapiit. Thus the type name is Rgroupapiit (note the capital R).

You ll want to name the field _apiclient. See the screen shot below where you should put your field. Remember to use the correct type name. 36. Add your field (see below where it should go in the source file; Rgroupapiit is an example type name your will be different): 37. Add a second field below the one you just created. You do not need to change the class name for this: private AppServiceClient _gatewayclient; 38. Inside the class below your two fields, add a string constant like below but using the URL for your gateway, which you can get from the Azure portal. Make sure you use https in this constant. The URL value in the portal will be http. private const string GatewayUrl = "https://yourgateway.azurewebsites.net"; It should resemble the following:

39. Add the following method to the class: private void CreateApiClientIfCredentialsAvailable() { object uv, tv; if (!ApplicationData.Current.LocalSettings.Values.TryGetValue("UserId", out uv)!applicationdata.current.localsettings.values.trygetvalue("token", out tv)) { getalbumsbutton.isenabled = false; return; } string userid = (string) uv; string usertoken = (string) tv; _gatewayclient = new AppServiceClient(GatewayUrl); _gatewayclient.setcurrentuser(userid, usertoken); _apiclient = new YOURTYPENAME(_gatewayClient.CreateHandler()); } getalbumsbutton.isenabled = true; You need to fix the highlighted line and replace YOURTYPENAME with the name of the type you used for the first field you added to this class (see step 36). 40. In the constructor, after the line of code this.initializecomponent();, add this after the call to InitializeComponent: CreateApiClientIfCredentialsAvailable(); 41. Add the async keyword before the void keyword for the loginbutton click handler. It should look like the following: private async void loginbutton_click(object sender, RoutedEventArgs e)

42. In the loginbutton click handler, add this code: string authurl = GatewayUrl + "/.auth/login/microsoftaccount"; string doneurl = GatewayUrl + "/.auth/login/done"; var wa = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(authUrl), new Uri(doneUrl)); string d = wa.responsedata; int tokenpos = d.indexof("#token="); if (tokenpos >= 0) { var encodedjson = d.substring(tokenpos + 7); var decodedjson = Uri.UnescapeDataString(encodedJson); var result = JsonConvert.DeserializeObject<dynamic>(decodedJson); string userid = result.user.userid; string usertoken = result.authenticationtoken; ApplicationData.Current.LocalSettings.Values["UserId"] = userid; ApplicationData.Current.LocalSettings.Values["Token"] = usertoken; CreateApiClientIfCredentialsAvailable(); } await _apiclient.profile.postvalidateasync(); This code when run shows the same login UI you tried a moment ago in a web browser hosted in the app, but it detects successful completion and extracts the user ID and an access token from the response. This will then be picked up by the CreateApiClientIfCredentialsAvailable method, which will then work on subsequent runs because it stores these values persistently. 43. Go back to the MainPage.xaml designer and double-click the Get Albums button to add a click handler. Again, you might have to manually switch to the new tab for MainPage.xaml.cs. 44. Add the async keyword in front of the new handler s void keyword. 45. Add this code to the handler: IList<string> testresult = await _apiclient.test.getasync(); IList<AlbumSummary> albums = await _apiclient.albums.getasync(); 46. Select Build Build Solution. 47. You will find it reports an error in a file called Test.cs. 48. Double-click on the error in the Error List window to go to the file. This seems to be a bug in the current API App SDK preview.

49. You can fix it by adding the following using directive to the top of that file: using Rg.ClientApp.Models; 50. Select Build Build Solution again. 51. In the Solution Explorer, right-click on the Rg.ClientApp project and choose Set as StartUp Project. 52. In the MainPage.xaml.cs file, set a breakpoint on the first line of the getalbumsbutton click handler by placing your cursor on the line and pressing the F9 key. 53. Press F5 to run the app. 54. Click the Log in button. 55. When a login prompt appears, sign into your Microsoft account. 56. Click the Get Albums button. 57. The debugger will stop at the click handler. 58. Step over the line that fetches test results by pressing F10. 59. Inspect the testresult variable by selecting it and then clicking the down arrow of the tool that appears. You can also view details in the Locals window which might be easier. If the testresult list contains a single item with an error message, stop debugging, go to the Azure portal, find the API App, and click its Restart button and try again. Sometimes changes to authentication settings do not percolate fully through the system until you restart. If this happens, stop debugging and try again. Once it is working you should see something like above.

This is the same information as the test endpoint reported when you tried it from the Swagger UI. This verifies that the user has been identified successfully when logging in through the client app. 60. Step over the next line by pressing F10 again. Inspect the albums variable. It should contain a list with one entry for each of your albums. If you expand one of the entries, you will see information about the album like this: 61. This verifies that your API App is able to return user-specific data. In the next part, we will see how our API App can call out to external services on behalf of the user. 62. Select Debug Stop Debugging. 63. In the Solution Explorer, right click on the Solution node for Rg.WebWithApiApp and select Commit. 64. Enter a message like Completed configuring API app and test client. 65. Under Related Work Items click Add Work Item by ID. 66. Enter the ID for your task (if necessary, go back to the Task Board to get the ID). It will most likely be 4 if you created a new account today. 67. Once you have entered it, click Add. 68. When ready, click Commit and Push. 69. Now go to the Task Board and drag and drop your task to Done. You have now completed the second walkthrough. Stand up, take a quick break, and move on to the next one.