GithubHelp home page GithubHelp logo

isabella232 / active-directory-dotnet-native-uwp-v2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from azure-samples/active-directory-dotnet-native-uwp-v2

0.0 0.0 0.0 296 KB

A Windows Universal Platform client application using msal.net, accessing the Microsoft Graph for a user authenticating with Azure AD V2 endpoint

Home Page: https://aka.ms/aadv2

License: MIT License

C# 49.65% PowerShell 50.35%

active-directory-dotnet-native-uwp-v2's Introduction

services platforms author level client service endpoint page_type languages products description urlFragment
active-directory
dotnet
Shama-K
200
UWP
Microsoft Graph
Microsoft identity platform
sample
csharp
azure
azure-active-directory
windows
windows-uwp
office-ms-graph
This sample demonstrates how to use the Microsoft Authentication Library for .NET to get an access token and call the Microsoft Graph from a UWP app.
uwp-signing-in-graph-aad

Universal Windows Platform application signing in users with Microsoft and calling the Microsoft Graph

Build badge

Getting Started Library Docs Support

About this sample

Table of contents

Overview

This sample demonstrates how to use the Microsoft Authentication Library (MSAL) for .NET to get an access token and call the Microsoft Graph using the MS Graph SDK from a Universal Windows Platform (UWP) application.

  1. The .NET client UWP application uses the Microsoft Authentication Library (MSAL) to sign-in a user and obtain a JWT access token from Azure Active Directory (Azure AD).
  2. The access token is then used as a bearer token to call Microsoft Graph and fetch the signed-in user's details.

Looking for previous versions of this code sample? Check out the tags on the releases GitHub page.

Topology

Steps to run

You can get full explanation about this sample, and build it from scratch by going to Call the Microsoft Graph API from a Universal Windows Platform (UWP) application. You would have to change a few things (see below, build from scratch)

How to run this sample

To run this sample, you'll need:

  • Visual Studio 2019
  • An Internet connection
  • An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, 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 (formerly Windows Live account). Therefore, 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.
  • AzureAD Powershell Module if opting to use the automatic set up in Step 2 (available at the Powershell Gallery)

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/active-directory-dotnet-native-uwp-v2.git

or download and extract the repository .zip file.

Given that the names of the referenced NuGet packages are quite long, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.

Step 2: Register the sample application with your Azure Active Directory tenant

There is one project in this sample. To register it, you can:

Expand this section if you want to use this automation:
  1. On Windows, run PowerShell and navigate to the root of the cloned directory

  2. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  3. Run the script to create your Azure AD application and configure the code of the sample application accordingly.

  4. In PowerShell run:

    cd .\AppCreationScripts\
    .\Configure.ps1

    Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.

  5. Open the Visual Studio solution and click start to run the code.

Follow the steps below to manually walk through the steps to register and configure the applications.

Choose the Azure AD tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
  2. If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Azure AD tenant.

Register the UWP App (UWP-App-calling-MSGraph)

  1. Navigate to the Microsoft identity platform for developers App registrations page.

  2. Select New registration.

  3. In the Register an application page that appears, enter your application's registration information:

    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example UWP-App-calling-MSGraph.
    • Under Supported account types, select Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
  4. Select Register to create the application.

  5. In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.

  6. In the app's registration screen, select Authentication in the menu.

  7. Select Save to save your changes.

  8. In the app's registration screen, click on the API permissions blade in the left to open the page where we add access to the APIs that your application needs.

    • Click the Add a permission button and then,
    • Ensure that the Microsoft APIs tab is selected.
    • In the Commonly used Microsoft APIs section, click on Microsoft Graph
    • In the Delegated permissions section, select User.Read in the list. Use the search box if necessary.
    • Click on the Add permissions button at the bottom.

Step 3: Configure the UWP App (UWP-App-calling-MSGraph) to use your app registration

Open the project in your IDE (like Visual Studio) to configure the code.

In the steps below, "ClientID" is the same as "Application ID" or "AppId".

  1. Open the Native_UWP_V2\MainPage.xaml.cs file

  2. Find the below line

    private const string ClientId = "[Application Id pasted from the application registration portal]"

    and replace the existing value with the application ID (clientId) of the UWP-App-calling-MSGraph application copied from the Azure portal.

  3. (Optionally): Enable Windows Integrated Authentication when using a federated Azure AD tenant

    Out of the box, this sample is not configured to work with Integrated Windows Authentication (IWA) when used with a federated Azure Active Directory domain. To work with IWA the application manifest must enable additional capabilities. These capabilities are not configured by default for this sample because applications requesting the Enterprise Authentication or Shared User Certificates capabilities require a higher level of verification to be accepted into the Windows Store, and not all developers may wish to perform the higher level of verification. To enable Windows-Integrated Authentication, in Package.appxmanifest, in the Capabilities tab, enable:

     - Enterprise Authentication
     - Private Networks (Client & Server)
     - Shared User Certificates
    

    Also, MainPage.xaml.cs, when building the application, ensure that the following line of code: .WithUseCorporateNetwork(true)

Step 4: Run the sample

  1. Run the application from Visual Studio (Debug | Start without Debugging), directly on the local machine, or after deploying to a device or an emulator.

Consider taking a moment to share your experience with us.

Known limitation: on Windows 10, you cannot sign in with your windows hello PIN

If sign-in with your work or school account and your organization requires conditional access, you are asked to provide a certificate:

  • If you have not enabled UWP-specific considerations above, you will get this error:

    No valid client certificate found in the request.
    No valid certificates found in the user's certificate store.
    Please try again choosing a different authentication method.
    
  • On Windows 10 desktop UWP application, if you enabled the settings described above, the list of certificates is presented, however if you choose to use your PIN, the PIN window is never presented. This is a known limitation with Web authentication broker in UWP applications running on Windows 10 (this works fine on Windows Phone 10). As a work-around, you will need to click on the sign-in with other options link and then choose Sign-in with a username and password instead, provide your password and go through the phone authentication.

  • we plan to remove this limitation in the future by integrating the Web Account Manager (WAM)

Alternate approach to use WithDefaultRedirectURI()

In the current sample, WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient") method is used. To use WithDefaultRedirectURI(), please follow below steps:

  1. In MainPage.XAML.cs, Update WithRedirectUri with WithDefaultRedirectUri as shown in below lines of code:

Current Code

PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
    .WithAuthority(Authority)
    .WithUseCorporateNetwork(false)
    .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
    .WithLogging((level, message, containsPii) =>
     {
         Debug.WriteLine($"MSAL: {level} {message} ");
     }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)
    .Build();

Updated Code

PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
    .WithAuthority("https://login.microsoftonline.com/common")
    .WithUseCorporateNetwork(false)
    .WithDefaultRedirectUri()
    .WithLogging((level, message, containsPii) =>
     {
         Debug.WriteLine($"MSAL: {level} {message} ");
     }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)
    .Build();
  1. Discover the callback URI for your app by adding redirectURI field in MainPage.xaml.cs and setting a breakpoint on it:
public sealed partial class MainPage : Page
{
        ...

        string redirectURI = Windows.Security.Authentication.Web.WebAuthenticationBroker
                            .GetCurrentApplicationCallbackUri().ToString();
        public MainPage()
        {
            ...
        }
       ...
}
  

Run the app, and copy the value of redirectUri when the breakpoint is hit. The value should look something similar to the following:
ms-app://s-1-15-2-1352796503-54529114-405753024-3540103335-3203256200-511895534-1429095407/

You can remove the mentioned line of code as it is required only once to fetch the value.

  1. Add the returned value in RedirectUri under Authentication blade in the Application Registration Portal.

Steps to build from scratch

Follow the instructions given in Windows desktop .NET guided walkthrough, but:

  • Instead of creating a WPF project, you will need to create a UWP project
  • Instead of using a Label in the MainWindow.xaml, you will need to use a TextBock (as Labels are not supported in the UWP platform). Instead of the Label Content property, use the TextBlock's Text property
  • With UWP applications, you don't need to add a cache as it's already managed by MSAL.Net

Community help and support

We use Stack Overflow with the community to provide support. We highly recommend you ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [msal.dotnet].

If you find and bug in the sample please raise the issue on GitHub Issues.

If you find a bug in msal.Net, please raise the issue on MSAL.NET GitHub Issues.

To provide a recommendation, visit our User Voice page.

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

More information

For more information see MSAL.NET's conceptual documentation:

active-directory-dotnet-native-uwp-v2's People

Contributors

aiwangmicrosoft avatar archieag avatar bgavrilms avatar jennyf19 avatar jmprieur avatar kalyankrishna1 avatar microsoftopensource avatar msftgits avatar naihuiw avatar salmanmkc avatar shama-k avatar supernova-eng avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.