forked from microsoft/Windows-universal-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScenario1_DefaultAccount.xaml.cpp
283 lines (252 loc) · 12.3 KB
/
Scenario1_DefaultAccount.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
// Copyright (c) Microsoft. All rights reserved.
#include "pch.h"
#include "Scenario1_DefaultAccount.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;
// Important Note for running this sample:
// The sample as-is will not be able to get tokens without having it's app manifest being
// modified to use the App Identity of a registered Microsoft Store/registered AAD app.
//
// See 'Related Topics' in the README.md for instructions on how to register an app.
// The first scenario covers getting the default account.
//
// First you must get the default account provider by passing the id "https://login.windows.local"
// into WebAuthenticationCoreManager::FindAccountProviderAsync.
//
// It's important to note whether this account is MSA or AAD depending on the authority that the
// provider has.
// MSA: authority == "consumers"
// AAD: authority == "organizations"
// These will determine what strings you pass into the token request.
//
// Then you can call WebAuthenticationCoreManager::RequestTokenSilentlyAsync or
// WebAuthenticationCoreManager::RequestTokenAsync to get a token for the user.
//
// The main difference between these APIs is that if the user needs to enter login
// credentials before a token can be returned, RequestTokenAsync will result in
// a UI popping up while RequestTokenSilentlyAsync will just return a result of
// UserInteractionRequired.
//
// If you hit UserInteractionRequired, then you will need to call the regular
// RequestTokenAsync.
Scenario1_DefaultAccount::Scenario1_DefaultAccount() : rootPage(MainPage::Current)
{
InitializeComponent();
GetDefaultProvidersAndAccounts();
}
void Scenario1_DefaultAccount::OnNavigatedFrom(NavigationEventArgs^ e)
{
// Clean up any account that may still be logged in
LogoffAndRemoveAccount();
}
void SDKTemplate::Scenario1_DefaultAccount::Button_DefaultSignIn_Click(Platform::Object ^ sender, Windows::UI::Xaml::RoutedEventArgs ^ e)
{
if (m_provider == nullptr)
{
rootPage->NotifyUser("There are no connected accounts to be used for default sign in.", NotifyType::ErrorMessage);
return;
}
// Since we only asked for the default provider, we need to make sure we pass the right
// scope and client ids based on whether this is AAD or MSA
if (m_provider->Authority == CONSUMER_AUTHORITY)
{
AuthenticateWithRequestToken(m_provider, MSA_SCOPE_REQUESTED, MSA_CLIENT_ID);
}
else
{
AuthenticateWithRequestToken(m_provider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID);
}
}
void SDKTemplate::Scenario1_DefaultAccount::Button_GetTokenSilently_Click(Object^ sender, RoutedEventArgs^ e)
{
// Since we only asked for the default provider, we need to make sure we pass the right
// scope and client ids based on whether this is AAD or MSA
if (m_provider->Authority == CONSUMER_AUTHORITY)
{
AuthenticateWithRequestTokenSilent(m_account->WebAccountProvider, MSA_SCOPE_REQUESTED, MSA_CLIENT_ID, m_account);
}
else
{
AuthenticateWithRequestTokenSilent(m_account->WebAccountProvider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID, m_account);
}
}
void SDKTemplate::Scenario1_DefaultAccount::Button_Reset_Click(Object^ sender, RoutedEventArgs^ e)
{
rootPage->NotifyUser("Resetting", NotifyType::StatusMessage);
LogoffAndRemoveAccount();
rootPage->NotifyUser("Done Resetting", NotifyType::StatusMessage);
}
void SDKTemplate::Scenario1_DefaultAccount::GetDefaultProvidersAndAccounts()
{
// Make a task to get the Default Provider by it's ID
// When that task completes, save the default provider found along with it's authority to know if it's MSA or AAD
concurrency::create_task(WebAuthenticationCoreManager::FindAccountProviderAsync(DEFAULT_ACCOUNT_PROVIDER_ID)).then(
[this](WebAccountProvider^ foundDefaultProvider)
{
if (foundDefaultProvider)
{
m_provider = foundDefaultProvider;
ApplicationData::Current->LocalSettings->Values->Insert(STORED_ACCOUNT_AUTHORITY, m_provider->Authority);
}
else
{
rootPage->NotifyUser("Warning: Default provider not found for id: " + DEFAULT_ACCOUNT_PROVIDER_ID, 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^ foundDefaultAccount)
{
if (foundDefaultAccount)
{
SaveAccount(foundDefaultAccount);
}
});
}
});
}
// 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.
//
// We've gotten the default provider which will
//
void SDKTemplate::Scenario1_DefaultAccount::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) &&
(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 MSA 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::Scenario1_DefaultAccount::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::Scenario1_DefaultAccount::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);
if (m_provider->Authority == CONSUMER_AUTHORITY)
{
AuthenticateWithRequestToken(m_account->WebAccountProvider, MSA_SCOPE_REQUESTED, MSA_CLIENT_ID);
}
else
{
AuthenticateWithRequestToken(m_account->WebAccountProvider, AAD_SCOPE_REQUESTED, AAD_CLIENT_ID);
}
}
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::Scenario1_DefaultAccount::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;
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::Scenario1_DefaultAccount::LogoffAndRemoveAccount()
{
if (m_account)
{
//concurrency::create_task(account->SignOutAsync(MSA_SCOPE_REQUESTED));
}
if (ApplicationData::Current->LocalSettings->Values->HasKey(STORED_ACCOUNT_ID_KEY))
{
ApplicationData::Current->LocalSettings->Values->Remove(STORED_ACCOUNT_ID_KEY);
}
// Update the UI
button_SignIn->IsEnabled = true;
button_GetTokenSilently->IsEnabled = false;
textblock_SignedInStatus->Text = "Not signed in.";
textblock_SignedInStatus->Foreground = ref new SolidColorBrush(Windows::UI::Colors::Red);
listview_SignedInAccounts->Items->Clear();
}