services | platforms | author |
---|---|---|
active-directory |
dotnet |
jmprieur |
This is a sample MVC Web application that shows how to make RESTful calls to the Graph API to access Azure Active Directory data. It includes use of OWIN libraries to authenticate/authorize using Open ID connect, and a Graph API .Net library - these libraries are both available as Nuget packages.
For more information about how the protocols work in this scenario and other scenarios, see the REST API and Authentication Scenarios on http://msdn.microsoft.com/aad.
To run this sample you will need:
- Visual 2013
- An Internet connection
- An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, please see How to get an Azure AD tenant
- A user account in your Azure AD tenant. This sample will not work with a Microsoft account, so if you signed in to the Azure portal with a Microsoft account and have never created a user account in your directory before, you need to do that now.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web.git
The sample app is preconfigured to read data from a Demonstration company (GraphDir1.onMicrosoft.com) in Azure AD. Run the sample application, and from the main page, authenticate using this demo user account: demoUser@graphDir1.onMicrosoft.com graphDem0
- Sign in to the Azure portal.
- On the top right, click on your account and under the Directory list, choose an Active Directory tenant where you have admin permissions.
- Type App registrations in the search filter.
- Click on App registrations and choose Add.
- Enter a friendly name for the application, for example 'WebApp-GraphAPI' and select 'Web Application and/or Web API' as the Application Type. For the sign-on URL, enter the base URL for the sample, which is by default
https://localhost:44322/
. NOTE: It is important, due to the way Azure AD matches URLs, to ensure there is a trailing slash on the end of this URL. If you don't include the trailing slash, you will receive an error when the application attempts to redeem an authorization code. Click on Create to create the application. - While still in the Azure portal, choose your application, click on Settings and choose Properties.
- Find the Application ID value and copy it to the clipboard.
- For the App ID URI, enter
https://<your_tenant_name>/WebAppGraphAPI
, replacing<your_tenant_name>
with the domain name of your Azure AD tenant. For Example "https://contoso.com/WebAppGraphAPI". - In the Reply URL, add the reply URL address used to return the authorization code returned during Authorization code flow, eg https://localhost:44322/". NOTE: If you see TLS error messages, try changing your reply URL to use http instead of https.
- From the Settings menu, choose Keys and add a key - select a key duration of either 1 year or 2 years. When you save this page, the key value will be displayed, copy and save the value in a safe location - you will need this key later to configure the project in Visual Studio - this key value will not be displayed again, nor retrievable by any other means, so please record it as soon as it is visible from the Azure Portal.
- Configure Permissions for your application - in the Settings menu, choose the 'Required permissions' section, click on Add, then Select an API, and select 'Windows Azure Active Directory' (this is the AADGraph API). Then, click on Select Permissions and select 'Access the directory as the signed-in user' and 'Sign in and read user profile'.
NOTE: the permission "Access the directory as the signed-in user" allows the application to access your organization's directory on behalf of the signed-in user - this is a delegation permission and must be consented by the Administrator for web apps (such as this demo app). The permission "Sign in and read user profile' profiles" allows users to sign in to the application with their organizational accounts and lets the application read the profiles of signed-in users, such as their email address and contact information - this is a delegation permission, and can be consented to by the user.
- You will need to update the
web.config
file of the sample. From Visual Studio, open theweb.config
file, and under the<appSettings>
section, modify"ida:ClientId"
and"ida:AppKey"
with the values from the previous steps. Also update the"ida:Tenant"
with your Azure AD Tenant's domain name e.g.contoso.onMicrosoft.com
, (orcontoso.com
if that domain is owned by your tenant). - Find your tenantID. Your tenantId can be discovered by opening the following metadata.xml document: https://login.microsoftonline.com/GraphDir1.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml - replace "graphDir1.onMicrosoft.com", with your tenant's domain value (any domain that is owned by the tenant will work). The tenantId is a guid, that is part of the sts URL, returned in the first xml node's sts url ("EntityDescriptor"): e.g. "https://sts.windows.net/".
- In
web.config
add this line in the<system.web>
section:<sessionState timeout="525600" />
. This increases the ASP.Net session state timeout to it's maximum value so that access tokens and refresh tokens cache in session state aren't cleared after the default timeout of 20 minutes. - Build and run your application - you will need to authenticate with valid user credentials for your company when you run the application. Note: If you get "missing reference" errors, enable Nuget Package Restore and try building again.
To deploy the sample to Azure Web Sites, you will create a web site, publish the Visual Studio project to the site, and update your tenant to use the web site instead of IIS Express.
- Sign in to the Azure portal.
- Click New in the top left hand corner, select Web + Mobile --> Web App, select the hosting plan and region, and give your web site a name, e.g. webappgraphapi-contoso.azurewebsites.net. Click Create Web Site.
- Once the web site is created, click on it to manage it. For this set of steps, download the publish profile and save it. Other deployment mechanisms, such as from source control, can also be used.
- Switch to Visual Studio and go to the WebAppGraphAPI project. Right click on the project in the Solution Explorer and select Publish. Click Import, and import the publish profile that you just downloaded.
- On the Connection tab, update the Destination URL so that it is https, for example https://webappgraphapi-contoso.azurewebsites.net. Click Next.
- On the Settings tab, make sure Enable Organizational Authentication is NOT selected. Click Publish.
- Visual Studio will publish the project and automatically open a browser to the URL of the project. If you see the default web page of the project, the publication was successful.
- Navigate to the Azure portal.
- On the top bar, click on your account and under the Directory list, choose the Active Directory tenant where you wish to register your application.
- On the applications tab, select the appropriate application.
- From the Settings -> Properties and Settings -> Reply URLs menus, update the Sign-On URL and Reply URL fields to the address of your service, for example https://webappgraphapi-contoso.azurewebsites.net/. Save the configuration.
Coming soon.
First, in Visual Studio 2013 create an empty solution to host the projects. Then, follow these steps to create the sample.
- In the solution, create a new ASP.Net MVC web application called WebAppGraphAPI with Authentication set to No Authentication.
- Set SSL Enabled to be True. Note the SSL URL.
- In the project properties, Web properties, set the Project Url to be the SSL URL.
- Add the following ASP.Net OWIN middleware NuGets: Microsoft.IdentityModel.Protocol.Extensions, System.IdentityModel.Tokens.Jwt, Microsoft.Owin.Security.OpenIdConnect, Microsoft.Owin.Security.Cookies, Microsoft.Owin.Host.SystemWeb.
- Add the stable release Active Directory Authentication Library NuGet (
Microsoft.IdentityModel.Clients.ActiveDirectory
). - Add the AAD GraphAPI client library NuGet (
Microsoft.Azure.ActiveDirectory.GraphClient
) version 1.0.3 using the Package Manager Console:Install-Package Microsoft.Azure.ActiveDirectory.GraphClient -Version 1.0.3
- In the
App_Start
folder, create a classStartup.Auth.cs
. You will need to remove.App_Start
from the namespace name. Replace the code for theStartup
class with the code from the same file of the sample app. Be sure to take the whole class definition! The definition changes frompublic class Startup
topublic partial class Startup
. - Right-click on the project, select Add, select "OWIN Startup class", and name the class "Startup". If "OWIN Startup Class" doesn't appear in the menu, instead select "Class", and in the search box enter "OWIN". "OWIN Startup class" will appear as a selection; select it, and name the class
Startup.cs
. - In
Startup.cs
, replace the code for theStartup
class with the code from the same file of the sample app. Again, note the definition changes frompublic class Startup
topublic partial class Startup
. - In the
Views
-->Shared
folder, create a new partial view_LoginPartial.cshtml
. Replace the contents of the file with the contents of the file of same name from the sample. - In the
Views
-->Shared
folder, replace the contents of_Layout.cshtml
with the contents of the file of same name from the sample. Effectively, all this will do is add a single line,@Html.Partial("_LoginPartial")
, that lights up the previously added_LoginPartial
view. - If you want the user to be required to sign-in before they can see any page of the app, then in the
HomeController
, decorate theHomeController
class with the[Authorize]
attribute. If you leave this out, the user will be able to see the home page of the app without having to sign-in first, and can click the sign-in link on that page to get signed in. - In the
Models
folder add a new class calledUserProfile.cs
. Copy the implementation of UserProfile from this sample into the class. - In the project, create a new folder called
Utils
. In the folder, create three new classes calledNaiveSessionCache.cs
,GraphConfiguration.cs
andLogger.cs
. Copy their implementations from the sample. - Add a new empty MVC5 controller
AccountController
to the project. Replace the implementation with the contents of the file of same name from the sample. - Add a new empty MVC5 controller
ContactsController
to the project. Copy the implementation of the controller from the sample. Remember to include the [Authorize] attribute on the class definition. - Add three views in the
Views/Contacts
folder,Index
,Details
, andGetGroups
. Copy their implemenations from the sample. - Add a new empty MVC5 controller
GroupsController
to the project. Copy the implementation of the controller from the sample. Again, remember to include the [Authorize] attribute on the class definition. - Add seven views in the
Views/Groups
folder,Index
,Details
,GetGroups
,Delete
,GetMembers
,Edit
, andCreate
. Copy their implemenations from the sample. - Add a new empty MVC5 controller
RolesController
to the project. Copy the implementation of the controller from the sample. Again, remember to include the [Authorize] attribute on the class definition. - Add three views in the
Views/Roles
folder,Index
,Details
, andGetMembers
. Copy their implemenations from the sample. - Add a new empty MVC5 controller
UserProfileController
to the project. Copy the implementation of the controller from the sample. Again, remember to include the [Authorize] attribute on the class definition. - Add one view in the
Views/UserProfile
folder,Index
. Copy its implemenation from the sample. - Add a new empty MVC5 controller
UsersController
to the project. Copy the implementation of the controller from the sample. Again, remember to include the [Authorize] attribute on the class definition. - Add seven views in the
Views/Users
folder,Index
,Details
,GetGroups
,Delete
,GetDirectReports
,Edit
, andCreate
. Copy their implemenations from the sample. - In
web.config
, in<appSettings>
, create keys forida:ClientId
,ida:AppKey
,ida:AADInstance
,ida:Tenant
,ida:PostLogoutRedirectUri
,ida:GraphApiVersion
, andida:GraphUrl
and set the values accordingly. For the public Azure AD, the value ofida:AADInstance
ishttps://login.windows.net/{0}
the value ofida:GraphResourceId
ishttps://graph.windows.net
, and the value ofida:GraphUrl
ishttps://graph.windows.net/
. - In
web.config
add this line in the<system.web>
section:<sessionState timeout="525600" />
. This increases the ASP.Net session state timeout to it's maximum value so that access tokens and refresh tokens cache in session state aren't cleared after the default timeout of 20 minutes. - Follow the steps in the "Run the application with your own AAD tenant" above to run the newly created sample.