forked from microsoft/Windows-universal-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScenario3_AAD.xaml.cpp
346 lines (300 loc) · 15.7 KB
/
Scenario3_AAD.xaml.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright (c) Microsoft. All rights reserved.
#include "pch.h"
#include "Scenario3_Aad.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Security::Authentication::Web::Core;
using namespace Windows::Security::Credentials;
using namespace Windows::Storage;
using namespace Windows::UI::Popups;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::UI::ApplicationSettings;
using namespace Windows::ApplicationModel::Background;
using namespace Windows::UI::Xaml::Media::Imaging;
Scenario3_Aad::Scenario3_Aad() : rootPage(MainPage::Current)
{
InitializeComponent();
InitalizeAccountsControlDialog();
}
void Scenario3_Aad::OnNavigatedFrom(NavigationEventArgs^ e)
{
LogoffAndRemoveAccount();
CleanupAccountsControlDialog();
}
void SDKTemplate::Scenario3_Aad::Button_SignIn_Click(Object^ sender, RoutedEventArgs^ e)
{
// Inside OnAccountCommandsRequested we will determine that we need to show accounts
// and providers eligible for sign in because there is no signed in account
AccountsSettingsPane::Show();
}
void SDKTemplate::Scenario3_Aad::Button_GetTokenSilently_Click(Object^ sender, RoutedEventArgs^ e)
{
AuthenticateWithRequestTokenSilent(m_provider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID, m_account);
}
void SDKTemplate::Scenario3_Aad::Button_ManageAccounts_Click(Object^ sender, RoutedEventArgs^ e)
{
// Inside OnAccountCommandsRequested we will determine that we need to show the
// active account since are signed into an account right now
AccountsSettingsPane::Show();
}
void SDKTemplate::Scenario3_Aad::Button_Reset_Click(Object^ sender, RoutedEventArgs^ e)
{
rootPage->NotifyUser("Resetting", NotifyType::StatusMessage);
LogoffAndRemoveAccount();
rootPage->NotifyUser("Done Resetting", NotifyType::StatusMessage);
}
void SDKTemplate::Scenario3_Aad::InitalizeAccountsControlDialog()
{
// Add to the event AccountCommandsRequested to load our list of providers into the AccountSettingsPane
m_accountCommandsRequestedRegistrationToken = AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::add(
ref new TypedEventHandler<AccountsSettingsPane^, AccountsSettingsPaneCommandsRequestedEventArgs^>(
this,
&SDKTemplate::Scenario3_Aad::OnAccountCommandsRequested)
);
// Populate our list of providers with the AAD provider, and attempt to find any accounts saved.
GetProvidersAndAccounts();
}
void SDKTemplate::Scenario3_Aad::CleanupAccountsControlDialog()
{
// Remove the event handler from the AccountCommandsRequested
AccountsSettingsPane::GetForCurrentView()->AccountCommandsRequested::remove(m_accountCommandsRequestedRegistrationToken);
}
void SDKTemplate::Scenario3_Aad::OnAccountCommandsRequested(
AccountsSettingsPane^ sender,
AccountsSettingsPaneCommandsRequestedEventArgs^ e)
{
// This scenario only supports a single account at one time.
// If there already is an account, we do not include a provider in the list
if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
{
AddWebAccount(e);
}
else
{
AddWebAccountProvider(e);
}
AddLinks(e);
}
void SDKTemplate::Scenario3_Aad::GetProvidersAndAccounts()
{
// Make a task to get the AAD Provider by it's ID
// When that task completes, save the AAD provider found
concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(MICROSOFT_PROVIDER_ID, ORGANIZATION_AUTHORITY))
.then([this](WebAccountProvider^ foundAadProvider)
{
if (foundAadProvider)
{
m_provider = foundAadProvider;
}
else
{
rootPage->NotifyUser("Provider not found for id: " + MICROSOFT_PROVIDER_ID + " and authority: " + ORGANIZATION_AUTHORITY, NotifyType::StatusMessage);
}
}).then([this]()
{
// Then check to see if there is a stored account id in local settings,
// if so then get that account and save that as well
if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
{
auto accountID = safe_cast<String^>(ApplicationData::Current->LocalSettings->Values->Lookup(STORED_ACCOUNT_ID_KEY));
concurrency::create_task(WebAuthenticationCoreManager::FindAccountAsync(m_provider, accountID)).then([this](WebAccount^ foundAadAccount)
{
if (foundAadAccount)
{
SaveAccount(foundAadAccount);
}
});
}
});
}
//Creates a provider command object for our provider and adds it to the AccountsControl list of provider commands
void SDKTemplate::Scenario3_Aad::AddWebAccountProvider(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
{
e->HeaderText = "Describe what adding an account to your application will do for the user.";
// Create a new WebAccountProviderCommandInvokedHandler for the event fired when a user clicks on a provider in the AccountSettingsPane
WebAccountProviderCommandInvokedHandler^ handler = ref new WebAccountProviderCommandInvokedHandler(this, &SDKTemplate::Scenario3_Aad::WebAccountProviderCommandInvoked);
// Make a new command based on the AAD provider and the click handler we just created
WebAccountProviderCommand^ aadProviderCommand = ref new WebAccountProviderCommand(SDKTemplate::Scenario3_Aad::m_provider, handler);
// Append that command to the WebAccountProviderCommands list for the AccountSettingsPane
e->WebAccountProviderCommands->Append(aadProviderCommand);
}
//Creates a web account command object for our account, if we have one saved, and adds it to the AccountsControl list of web account commands
void SDKTemplate::Scenario3_Aad::AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
{
e->HeaderText = "Describe what removing an account to your application will do.";
// Create a new WebAccountCommandInvokedHandler for the event fired when a user clicks on an account in the AccountSettingsPane
WebAccountCommandInvokedHandler^ handler = ref new WebAccountCommandInvokedHandler(this, &SDKTemplate::Scenario3_Aad::WebAccountCommandInvoked);
// Make a new command based on the AAD account and the click handler we just created
WebAccountCommand^ aadAccountCommand = ref new WebAccountCommand(m_account, handler, SupportedWebAccountActions::Remove);
// Append that command to the WebAccountProviderCommands list for the AccountSettingsPane
e->WebAccountCommands->Append(aadAccountCommand);
}
// Add optional descriptive text and buttons/commands to the AccountControl
void SDKTemplate::Scenario3_Aad::AddLinks(AccountsSettingsPaneCommandsRequestedEventArgs^ e)
{
// You can add links such as privacy policy, help, general account settings
e->Commands->Append(ref new SettingsCommand("privacypolicy", "Privacy Policy", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario3_Aad::PrivacyPolicyInvoked)));
e->Commands->Append(ref new SettingsCommand("otherlink", "Other Link", ref new UICommandInvokedHandler(this, &SDKTemplate::Scenario3_Aad::OtherLinkInvoked)));
}
// The function that will be called from AccountSettingsPane with the WebAccountProvider
// that was clicked by the user
void SDKTemplate::Scenario3_Aad::WebAccountProviderCommandInvoked(WebAccountProviderCommand^ command)
{
AuthenticateWithRequestToken(command->WebAccountProvider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID);
}
// The function that will be called from AccountSettingsPane with the WebAccount
// that was selected by the user.
void SDKTemplate::Scenario3_Aad::WebAccountCommandInvoked(WebAccountCommand^ command, WebAccountInvokedArgs^ args)
{
if (args->Action == WebAccountAction::Remove)
{
LogoffAndRemoveAccount();
}
}
// Displays privacy policy message on clicking it in the AccountsControl
void SDKTemplate::Scenario3_Aad::PrivacyPolicyInvoked(IUICommand^ command)
{
rootPage->NotifyUser("Privacy policy clicked by user", NotifyType::StatusMessage);
}
// Displays other link message on clicking it in the AccountsControl
void SDKTemplate::Scenario3_Aad::OtherLinkInvoked(IUICommand^ command)
{
rootPage->NotifyUser("Other link pressed by user", NotifyType::StatusMessage);
}
// Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send
// that request asynchronously to WebAccountManager's RequestTokenAsync API
//
// WebAccountManager will then try three steps, in order:
// (1): Check it's local cache to see if it has a valid token
// (2): Try to silently request a new token from the AAD service
// (3): Show the AAD UI for user interaction required (user credentials) before it may return a token.
//
// Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token
// based requests and not require the ability to store a cached token within your app.
void SDKTemplate::Scenario3_Aad::AuthenticateWithRequestToken(WebAccountProvider^ passedProvider, String^ scope, String^ clientID)
{
rootPage->NotifyUser("Requested " + passedProvider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage);
auto wtr = ref new WebTokenRequest(passedProvider, scope, clientID);
// When our task finishes it will return result of the operation, and if successful it will contain a token
// and WebAccount. We save the WebAccount as the "active" account.
concurrency::create_task(WebAuthenticationCoreManager::RequestTokenAsync(wtr)).then([this](WebTokenRequestResult^ webTokenRequestResult)
{
if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success)
{
if (webTokenRequestResult->ResponseData->GetAt(0)->WebAccount)
{
if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
{
ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
}
WebAccount^ account = webTokenRequestResult->ResponseData->GetAt(0)->WebAccount;
SaveAccount(account);
}
}
OutputTokenResult(webTokenRequestResult);
});
}
// Create a new WebAccountManager WebTokenRequest based on the Provider, Scope, ClientID and then create a task to send
// that request and the account to get the token for asynchronously to WebAccountManager's GetTokenSilentlyAsync API
//
// WebAccountManager's GetTokenSilentlyAsync will then try :
// (1): Check it's local cache to see if it has a valid token
// (2): Try to silently request a new token from the AAD service
// (3): Return a status of UserInteractionRequired if we need the user credentials
//
// Because of WebAccountManager's ability to cache tokens, you should only need to call WebAccountManager when making token
// based requests and not require the ability to store a cached token within your app.
void SDKTemplate::Scenario3_Aad::AuthenticateWithRequestTokenSilent(WebAccountProvider^ provider, String^ scope, String^ clientID, WebAccount^ account)
{
rootPage->NotifyUser("Requested " + provider->DisplayName + " from AccountsManager dialog.", NotifyType::StatusMessage);
auto wtr = ref new WebTokenRequest(provider, scope, clientID);
// When our task finishes it will return result of the operation, and if successful it will contain a token
// and WebAccount. We save the WebAccount as the "active" account.
concurrency::create_task(WebAuthenticationCoreManager::GetTokenSilentlyAsync(wtr, account)).then([this](WebTokenRequestResult^ webTokenRequestResult)
{
if (webTokenRequestResult->ResponseStatus == WebTokenRequestStatus::Success)
{
// Perform an operation with the token you just got
}
OutputTokenResult(webTokenRequestResult);
});
}
// Displays the result of requesting a token asynchronously to the main page
void SDKTemplate::Scenario3_Aad::OutputTokenResult(WebTokenRequestResult^ result)
{
if (result->ResponseStatus == WebTokenRequestStatus::Success)
{
rootPage->NotifyUser(result->ResponseStatus.ToString() + "!\nUser: " + result->ResponseData->GetAt(0)->WebAccount->Id + "\n Token returned was: " + result->ResponseData->GetAt(0)->Token, NotifyType::StatusMessage);
}
else if (result->ResponseStatus == WebTokenRequestStatus::ProviderError)
{
// The account provider has passed us an error and we should handle it.
rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage);
}
else if (result->ResponseStatus == WebTokenRequestStatus::AccountProviderNotAvailable)
{
// The account provider is unavailable, this is a temporary error.
rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::ErrorMessage);
}
else if (result->ResponseStatus == WebTokenRequestStatus::UserInteractionRequired)
{
// The account provider needs to display a UI, since we called request token silently we should call it
// with RequestTokenAsync.
rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage);
}
else if (result->ResponseStatus == WebTokenRequestStatus::UserCancel)
{
// The user cancelled the sign in process for the account provider, handle
// that how you need to.
rootPage->NotifyUser(result->ResponseStatus.ToString(), NotifyType::StatusMessage);
}
else
{
// An unexpected error was encountered
rootPage->NotifyUser(result->ResponseStatus.ToString() + " " + result->ResponseError->ErrorCode + ": " + result->ResponseError->ErrorMessage, NotifyType::ErrorMessage);
}
}
// Saves the AccountId in LocalSettings and keeps an instance
// of the WebAccount saved
void SDKTemplate::Scenario3_Aad::SaveAccount(WebAccount^ account)
{
ApplicationData::Current->LocalSettings->Values->Insert(STORED_ACCOUNT_ID_KEY, account->Id);
m_account = account;
// Update the UI
button_SignIn->IsEnabled = false;
button_GetTokenSilently->IsEnabled = true;
button_ManageAccounts->IsEnabled = true;
textblock_SignedInStatus->Text = "Signed in with:";
textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Green);
listview_SignedInAccounts->Items->Append(account->Id);
}
// Signs out the account using the SignOutAsync Token Broker API
// and removes our saved AccountId as it won't be valid when SignOutAsync finishes.
void SDKTemplate::Scenario3_Aad::LogoffAndRemoveAccount()
{
if (m_account)
{
//concurrency::create_task(m_account->SignOutAsync(AAD_SCOPE_REQUESTED));
m_account = nullptr;
}
if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
{
rootPage->NotifyUser("Signed out account id: " + ApplicationData::Current->LocalSettings->Values->Lookup(STORED_ACCOUNT_ID_KEY), NotifyType::StatusMessage);
ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
// Update UI
button_SignIn->IsEnabled = true;
button_GetTokenSilently->IsEnabled = false;
button_ManageAccounts->IsEnabled = false;
textblock_SignedInStatus->Text = "Not signed in.";
textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Red);
listview_SignedInAccounts->Items->Clear();
}
}