|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Linq; |
| 5 | +using System.Runtime.InteropServices.WindowsRuntime; |
| 6 | +using Windows.Foundation; |
| 7 | +using Windows.Foundation.Collections; |
| 8 | +using Windows.UI.Xaml; |
| 9 | +using Windows.UI.Xaml.Controls; |
| 10 | +using Windows.UI.Xaml.Controls.Primitives; |
| 11 | +using Windows.UI.Xaml.Data; |
| 12 | +using Windows.UI.Xaml.Input; |
| 13 | +using Windows.UI.Xaml.Media; |
| 14 | +using Windows.UI.Xaml.Navigation; |
| 15 | +using Microsoft.Identity.Client; |
| 16 | +using Microsoft.Graph; |
| 17 | +using System.Diagnostics; |
| 18 | +using System.Threading.Tasks; |
| 19 | +using System.Net.Http.Headers; |
| 20 | +using Windows.Security.Authentication.Web; |
| 21 | +using System.Threading; |
| 22 | + |
| 23 | + |
| 24 | +// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 |
| 25 | + |
| 26 | +namespace UWPWAM |
| 27 | +{ |
| 28 | + /// <summary> |
| 29 | + /// An empty page that can be used on its own or navigated to within a Frame. |
| 30 | + /// </summary> |
| 31 | + public sealed partial class MainPage : Page |
| 32 | + { |
| 33 | + |
| 34 | + //Set the scope for API call to user.read |
| 35 | + private string[] scopes = new string[] { "user.read" }; |
| 36 | + |
| 37 | + // Below are the clientId (Application Id) of your app registration and the tenant information. |
| 38 | + // You have to replace: |
| 39 | + // - the content of ClientID with the Application Id for your app registration |
| 40 | + //private const string ClientId = "[Application Id pasted from the application registration portal]"; |
| 41 | + |
| 42 | + private const string ClientId = "4b0db8c2-9f26-4417-8bde-3f0e3656f8e0"; |
| 43 | + |
| 44 | + private const string Tenant = "common"; // Alternatively "[Enter your tenant, as obtained from the Azure portal, e.g. kko365.onmicrosoft.com]" |
| 45 | + private const string Authority = "https://login.microsoftonline.com/" + Tenant; |
| 46 | + |
| 47 | + // The MSAL Public client app |
| 48 | + private static IPublicClientApplication PublicClientApp; |
| 49 | + |
| 50 | + private static string MSGraphURL = "https://graph.microsoft.com/v1.0/"; |
| 51 | + private static AuthenticationResult authResult; |
| 52 | + |
| 53 | + public MainPage() |
| 54 | + { |
| 55 | + this.InitializeComponent(); |
| 56 | + |
| 57 | + // returns something like s-1-15-2-2601115387-131721061-1180486061-1362788748-631273777-3164314714-2766189824 |
| 58 | + string sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host; |
| 59 | + |
| 60 | + // use uppercase S |
| 61 | + sid = sid.Replace('s', 'S'); |
| 62 | + |
| 63 | + // the redirect URI |
| 64 | + string redirectUri = $"ms-appx-web://microsoft.aad.brokerplugin/{sid}"; |
| 65 | + } |
| 66 | + |
| 67 | + /// <summary> |
| 68 | + /// Call AcquireTokenAsync - to acquire a token requiring user to sign in |
| 69 | + /// </summary> |
| 70 | + private async void CallGraphButton_Click(object sender, RoutedEventArgs e) |
| 71 | + { |
| 72 | + try |
| 73 | + { |
| 74 | + // Sign in user using MSAL and obtain an access token for Microsoft Graph |
| 75 | + GraphServiceClient graphClient = await SignInAndInitializeGraphServiceClient(scopes); |
| 76 | + |
| 77 | + // Call the /me endpoint of Graph |
| 78 | + User graphUser = await graphClient.Me.Request().GetAsync(); |
| 79 | + |
| 80 | + // Go back to the UI thread to make changes to the UI |
| 81 | + await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => |
| 82 | + { |
| 83 | + ResultText.Text = "Display Name: " + graphUser.DisplayName + "\nBusiness Phone: " + graphUser.BusinessPhones.FirstOrDefault() |
| 84 | + + "\nGiven Name: " + graphUser.GivenName + "\nid: " + graphUser.Id |
| 85 | + + "\nUser Principal Name: " + graphUser.UserPrincipalName; |
| 86 | + DisplayBasicTokenInfo(authResult); |
| 87 | + this.SignOutButton.Visibility = Visibility.Visible; |
| 88 | + }); |
| 89 | + } |
| 90 | + catch (MsalException msalEx) |
| 91 | + { |
| 92 | + await DisplayMessageAsync($"Error Acquiring Token:{System.Environment.NewLine}{msalEx}"); |
| 93 | + } |
| 94 | + catch (Exception ex) |
| 95 | + { |
| 96 | + await DisplayMessageAsync($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}"); |
| 97 | + return; |
| 98 | + } |
| 99 | + } |
| 100 | + /// <summary> |
| 101 | + /// Signs in the user and obtains an access token for Microsoft Graph |
| 102 | + /// </summary> |
| 103 | + /// <param name="scopes"></param> |
| 104 | + /// <returns> Access Token</returns> |
| 105 | + private static async Task<string> SignInUserAndGetTokenUsingMSAL(string[] scopes) |
| 106 | + { |
| 107 | + // Initialize the MSAL library by building a public client application |
| 108 | + PublicClientApp = PublicClientApplicationBuilder.Create(ClientId) |
| 109 | + .WithAuthority(Authority) |
| 110 | + .WithBroker() |
| 111 | + .WithLogging((level, message, containsPii) => |
| 112 | + { |
| 113 | + Debug.WriteLine($"MSAL: {level} {message} "); |
| 114 | + }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true) |
| 115 | + .Build(); |
| 116 | + |
| 117 | + |
| 118 | + IEnumerable<IAccount> accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(true); |
| 119 | + IAccount firstAccount = accounts.FirstOrDefault(); |
| 120 | + |
| 121 | + try |
| 122 | + { |
| 123 | + authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount) |
| 124 | + .ExecuteAsync(); |
| 125 | + } |
| 126 | + catch (MsalUiRequiredException ex) |
| 127 | + { |
| 128 | + // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token |
| 129 | + Debug.WriteLine($"MsalUiRequiredException: {ex.Message}"); |
| 130 | + |
| 131 | + authResult = await PublicClientApp.AcquireTokenInteractive(scopes) |
| 132 | + //.WithAccount(firstAccount) |
| 133 | + .ExecuteAsync() |
| 134 | + .ConfigureAwait(true); |
| 135 | + |
| 136 | + } |
| 137 | + return authResult.AccessToken; |
| 138 | + } |
| 139 | + |
| 140 | + /// <summary> |
| 141 | + /// Sign in user using MSAL and obtain a token for Microsoft Graph |
| 142 | + /// </summary> |
| 143 | + /// <returns>GraphServiceClient</returns> |
| 144 | + private async static Task<GraphServiceClient> SignInAndInitializeGraphServiceClient(string[] scopes) |
| 145 | + { |
| 146 | + GraphServiceClient graphClient = new GraphServiceClient(MSGraphURL, |
| 147 | + new DelegateAuthenticationProvider(async (requestMessage) => |
| 148 | + { |
| 149 | + requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", await SignInUserAndGetTokenUsingMSAL(scopes)); |
| 150 | + })); |
| 151 | + |
| 152 | + return await Task.FromResult(graphClient); |
| 153 | + } |
| 154 | + |
| 155 | + /// <summary> |
| 156 | + /// Sign out the current user |
| 157 | + /// </summary> |
| 158 | + private async void SignOutButton_Click(object sender, RoutedEventArgs e) |
| 159 | + { |
| 160 | + IEnumerable<IAccount> accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false); |
| 161 | + IAccount firstAccount = accounts.FirstOrDefault(); |
| 162 | + |
| 163 | + try |
| 164 | + { |
| 165 | + await PublicClientApp.RemoveAsync(firstAccount).ConfigureAwait(false); |
| 166 | + await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => |
| 167 | + { |
| 168 | + ResultText.Text = "User has signed out"; |
| 169 | + this.CallGraphButton.Visibility = Visibility.Visible; |
| 170 | + this.SignOutButton.Visibility = Visibility.Collapsed; |
| 171 | + }); |
| 172 | + } |
| 173 | + catch (MsalException ex) |
| 174 | + { |
| 175 | + ResultText.Text = $"Error signing out user: {ex.Message}"; |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + /// <summary> |
| 180 | + /// Display basic information contained in the token. Needs to be called from the UI thread. |
| 181 | + /// </summary> |
| 182 | + private void DisplayBasicTokenInfo(AuthenticationResult authResult) |
| 183 | + { |
| 184 | + TokenInfoText.Text = ""; |
| 185 | + if (authResult != null) |
| 186 | + { |
| 187 | + TokenInfoText.Text += $"User Name: {authResult.Account.Username}" + Environment.NewLine; |
| 188 | + TokenInfoText.Text += $"Token Expires: {authResult.ExpiresOn.ToLocalTime()}" + Environment.NewLine; |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + /// <summary> |
| 193 | + /// Displays a message in the ResultText. Can be called from any thread. |
| 194 | + /// </summary> |
| 195 | + private async Task DisplayMessageAsync(string message) |
| 196 | + { |
| 197 | + await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, |
| 198 | + () => |
| 199 | + { |
| 200 | + ResultText.Text = message; |
| 201 | + }); |
| 202 | + } |
| 203 | + } |
| 204 | +} |
0 commit comments