void InitializeWebAccountProviders() { facebookProvider = new WebAccountProvider( FACEBOOK_ID, FACEBOOK_DISPLAY_NAME, new Uri("ms-appx:///icons/Facebook.png")); twitterProvider = new WebAccountProvider( TWITTER_ID, TWITTER_DISPLAY_NAME, new Uri("ms-appx:///icons/Twitter.png")); }
private async Task ProcessResponse(WebTokenRequestResult response, WebAccountProvider provider) { switch (response.ResponseStatus) { case WebTokenRequestStatus.Success: try { var tokenResponse = response.ResponseData[0]; var accessToken = tokenResponse?.Token; var username = tokenResponse?.WebAccount?.UserName; // SAVE this response, it has all your authentication info } catch (Exception) { } break; case WebTokenRequestStatus.UserCancel: // Handle user cancel by resuming pre-login screen break; case WebTokenRequestStatus.AccountProviderNotAvailable: // Fall back to WebAuthenticationBroker Fallbacks(); break; case WebTokenRequestStatus.ProviderError: break; case WebTokenRequestStatus.UserInteractionRequired: response = await GetToken(provider, false); if (response != null) { await ProcessResponse(response, provider); } break; } }
public async Task AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID) { try { WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID); // If the user selected a specific account, RequestTokenAsync will return a token for that account. // The user may be prompted for credentials or to authorize using that account with your app // If the user selected a provider, the user will be prompted for credentials to login to a new account WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { StoreNewAccountDataLocally(webTokenRequestResult.ResponseData[0].WebAccount); } OutputTokenResult(webTokenRequestResult); } catch (Exception ex) { rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage); } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority); appSettings = ApplicationData.Current.RoamingSettings; WebTokenRequest wtr = new WebTokenRequest(wap, String.Empty, clientId); wtr.Properties.Add("resource", resource); var userID = appSettings.Values["userID"]; if(userID != null) { userAccount = await WebAuthenticationCoreManager.FindAccountAsync(wap, (string)userID); if(userAccount != null) { //Use saved account to get token WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, userAccount); if (wtrResult.ResponseStatus == WebTokenRequestStatus.Success) { userAccount = wtrResult.ResponseData[0].WebAccount; } else { MessageDialog messageDialog = new MessageDialog("We tried to sign you in with the last account you used with this app," + "but it didn't work out. Please sign in as a different user."); await messageDialog.ShowAsync(); UpdateUXonSignOut(); } } else { // the WebAccount Object is no longer available wtr.Properties.Add("LoginHint", appSettings.Values["login_hint"].ToString()); WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if (wtrResult.ResponseStatus == WebTokenRequestStatus.Success) { userAccount = wtrResult.ResponseData[0].WebAccount; } } } else { //there is no recorded user so start sign-flow from start WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if(wtrResult.ResponseStatus == WebTokenRequestStatus.Success) { userAccount = wtrResult.ResponseData[0].WebAccount; } } if(userAccount != null) { UpdateUXonSignIn(); } else { //it totally failed UpdateUXonSignOut(); MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again."); await messageDialog.ShowAsync(); } }
// Get an access token for the given context and resourceId. An attempt is first made to // acquire the token silently. If that fails, then we try to acquire the token by prompting the user. public static async Task<string> GetTokenHelperAsync(WebAccountProvider accountProvider, string resourceId) { string token = null; WebAccountProvider aadAccountProvider; if (accountProvider != null) { aadAccountProvider = accountProvider; } else { aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync( AccountProviderId, Authority); } // Check if there's a record of the last account used with the app. var userID = settings.Values["userID"]; WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId); webTokenRequest.Properties.Add("resource", resourceId); WebTokenRequestResult webTokenRequestResult; if (userID != null) { // Get an account object for the user. userAccount = await WebAuthenticationCoreManager.FindAccountAsync(aadAccountProvider, (string)userID); // Ensure that the saved account works for getting the token we need. webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, userAccount); } else { webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); } if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; userAccount = webTokenResponse.WebAccount; token = webTokenResponse.Token; // We succeeded in getting a valid user. if (userAccount != null) { // Save user ID in local storage. settings.Values["userID"] = userAccount.Id; settings.Values["userEmail"] = userAccount.UserName; settings.Values["userName"] = userAccount.Properties["DisplayName"]; } return token; } else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired) { webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication); webTokenRequest.Properties.Add("resource", resourceId); //get token through prompt if (userID != null) { // Ensure that the saved account works for getting the token we need. webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount); } else { webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); } if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; userAccount = webTokenResponse.WebAccount; currentToken = webTokenResponse.Token; if (userAccount != null) { // Save user ID in local storage. settings.Values["userID"] = userAccount.Id; settings.Values["userEmail"] = userAccount.UserName; settings.Values["userName"] = userAccount.Properties["DisplayName"]; } return token; } else { // The saved account could not be used for getting a token. // Make sure that the UX is ready for a new sign in. await SignOutAsync(); return null; } } else { // The saved account could not be used for getting a token. // Make sure that the UX is ready for a new sign in. await SignOutAsync(); return null; } }
public static async Task<Dictionary<string, CapabilityDiscoveryResult>> GetCapabilities(WebAccountProvider webAccountProvider = null) { if (capabilities != null) return capabilities; if (webAccountProvider == null) webAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(AccountProviderId, Authority); DiscoveryClient discoveryClient = new DiscoveryClient( async () => await GetTokenHelperAsync(null, DiscoveryResourceId)); // Get capabilities capabilities = await discoveryClient.DiscoverCapabilitiesAsync() as Dictionary<string, CapabilityDiscoveryResult>; return capabilities; }
private async void Button_DefaultSignIn_Click(object sender, RoutedEventArgs e) { defaultProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(DefaultProviderId); if(defaultProvider == null) { rootPage.NotifyUser("This user does not have a primary account", NotifyType.StatusMessage); } else { // Set the clientID and scope based on the authority. The authority tells us if the account is a Microsoft account or an Azure AD. String scope = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountScopeRequested : AzureActiveDirectoryScopeRequested; String clientID = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountClientId : AzureActiveDirectoryClientId; AuthenticateWithRequestToken(defaultProvider, scope, clientID); } }
public async Task FetchTransferTokenAsync() { // Arrange using (MockHttpAndServiceBundle harness = CreateTestHarness()) { var msaProvider = new WebAccountProvider("id", "*****@*****.**", null); Client.Internal.Requests.AuthenticationRequestParameters requestParams = harness.CreateAuthenticationRequestParameters( TestConstants.AuthorityHomeTenant, validateAuthority: true); requestParams.AppConfig.WindowsBrokerOptions = new WindowsBrokerOptions() { MsaPassthrough = true }; var msaRequest = new WebTokenRequest(msaProvider); // step 1 - msa request _msaPlugin.CreateWebTokenRequestAsync(msaProvider, requestParams, false, true, false) .Returns(Task.FromResult(msaRequest)); var webTokenResponseWrapper = Substitute.For <IWebTokenRequestResultWrapper>(); webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success); WebAccount accountFromMsaProvider = new WebAccount(msaProvider, "*****@*****.**", WebAccountState.Connected); var webTokenResponse = new WebTokenResponse("v1_token", accountFromMsaProvider); webTokenResponseWrapper.ResponseData.Returns(new List <WebTokenResponse>() { webTokenResponse }); _wamProxy.RequestTokenForWindowAsync(IntPtr.Zero, msaRequest).Returns(webTokenResponseWrapper); // step 2 - we have v1 token and a WebAccount, now get a transfer token var transferTokenRequest = new WebTokenRequest(msaProvider); _msaPlugin .CreateWebTokenRequestAsync( msaProvider, TestConstants.ClientId, MsaPassthroughHandler.TransferTokenScopes) .Returns(Task.FromResult(transferTokenRequest)); var webTokenResponseWrapper2 = Substitute.For <IWebTokenRequestResultWrapper>(); var transferTokenRequestResult = Substitute.For <IWebTokenRequestResultWrapper>(); transferTokenRequestResult.ResponseStatus.Returns(WebTokenRequestStatus.Success); //WebAccount accountFromMsaProvider = new WebAccount(msaProvider, "*****@*****.**", WebAccountState.Connected); var transferTokenResponse = new WebTokenResponse("transfer_token"); webTokenResponseWrapper2.ResponseData.Returns(new List <WebTokenResponse>() { transferTokenResponse }); _msaPlugin.ParseSuccessfullWamResponse(Arg.Any <WebTokenResponse>(), out Arg.Any <Dictionary <string, string> >()) .Returns(x => { x[1] = new Dictionary <string, string>(); (x[1] as Dictionary <string, string>).Add("code", "actual_transfer_token"); return(new MsalTokenResponse()); }); _wamProxy.RequestTokenForWindowAsync(IntPtr.Zero, transferTokenRequest).Returns(webTokenResponseWrapper2); // Act var transferToken = await _msaPassthroughHandler.TryFetchTransferTokenAsync(requestParams, msaProvider) .ConfigureAwait(false); // Assert Assert.AreEqual("actual_transfer_token", transferToken); } }
public async void AccountCommandsRequested(AccountsSettingsPane accountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs eventArgs) { AccountsSettingsPaneEventDeferral deferral = eventArgs.GetDeferral(); HttpResult<ManageInfo> result; using (AccountClient accountClient = ClientFactory.CreateAccountClient()) { result = await accountClient.GetManageInfoAsync(); } if (!result.Succeeded) { await ErrorDialog.ShowErrorsAsync(result.Errors); // The log off command is not available on the account settings page if there are no accounts, so log off now LogOff(); deferral.Complete(); return; } ManageInfo manageInfo = result.Content; this.username = manageInfo.UserName; this.localProvider = manageInfo.LocalLoginProvider; eventArgs.HeaderText = "Manage your account logins"; ////Add WebAccountProviders Dictionary<string, WebAccountProvider> webProviders = new Dictionary<string, WebAccountProvider>(); WebAccountProviderCommandInvokedHandler providerCommandHandler = new WebAccountProviderCommandInvokedHandler(WebAccountProviderInvokedHandler); foreach (ExternalLogin externalLogin in manageInfo.ExternalLoginProviders) { WebAccountProvider provider = new WebAccountProvider(externalLogin.Url, externalLogin.Name, App.LoginIcons[externalLogin.Name]); WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, providerCommandHandler); eventArgs.WebAccountProviderCommands.Add(providerCommand); webProviders[provider.DisplayName] = provider; } WebAccountProvider localLoginProvider = new WebAccountProvider(manageInfo.LocalLoginProvider, manageInfo.LocalLoginProvider, null); webProviders[manageInfo.LocalLoginProvider] = localLoginProvider; ////Add WebAccounts and local accounts if available. bool hasLocalLogin = false; foreach (UserLoginInfo userLoginInfo in manageInfo.Logins) { WebAccountCommandInvokedHandler accountCommandHandler; SupportedWebAccountActions supportedActions = SupportedWebAccountActions.None; if (manageInfo.Logins.Length > 1) { supportedActions |= SupportedWebAccountActions.Remove; } if (userLoginInfo.LoginProvider == manageInfo.LocalLoginProvider) { hasLocalLogin = true; supportedActions |= SupportedWebAccountActions.Manage; accountCommandHandler = new WebAccountCommandInvokedHandler(LocalWebAccountInvokedHandler); } else { accountCommandHandler = new WebAccountCommandInvokedHandler(WebAccountInvokedHandler); } WebAccount webAccount = new WebAccount(webProviders[userLoginInfo.LoginProvider], userLoginInfo.ProviderKey, WebAccountState.Connected); WebAccountCommand webAccountCommand = new WebAccountCommand(webAccount, accountCommandHandler, supportedActions); eventArgs.WebAccountCommands.Add(webAccountCommand); } if (!hasLocalLogin) { WebAccountProviderCommandInvokedHandler localProviderCmdHandler = new WebAccountProviderCommandInvokedHandler(LocalProviderInvokedHandler); WebAccountProviderCommand localProviderCommand = new WebAccountProviderCommand(localLoginProvider, localProviderCmdHandler); eventArgs.WebAccountProviderCommands.Add(localProviderCommand); } SettingsCommand logOffCommand = new SettingsCommand("Logoff", "Log off", new UICommandInvokedHandler(LogOffHandler)); eventArgs.Commands.Add(logOffCommand); deferral.Complete(); }
private void Button_Reset_Click(object sender, RoutedEventArgs e) { defaultAccount = null; defaultProvider = null; button_GetTokenSilently.IsEnabled = false; textblock_SignedInStatus.Text = "Not signed in"; textblock_SignedInStatus.Foreground = new SolidColorBrush(Windows.UI.Colors.Red); listview_SignedInAccounts.Items.Clear(); }
public async void AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID) { try { WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID); // Azure Active Directory requires a resource to return a token if(Provider.Id == "https://login.microsoft.com" && Provider.Authority == "organizations") { webTokenRequest.Properties.Add("resource", "https://graph.windows.net"); } // If the user selected a specific account, RequestTokenAsync will return a token for that account. // The user may be prompted for credentials or to authorize using that account with your app // If the user selected a provider, the user will be prompted for credentials to login to a new account WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { StoreNewAccountDataLocally(webTokenRequestResult.ResponseData[0].WebAccount); } OutputTokenResult(webTokenRequestResult); } catch (Exception ex) { rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage); } }
private async Task<WebTokenRequestResult> GetToken(WebAccountProvider provider, bool isSilent) { WebTokenRequestResult result = null; try { var request = new WebTokenRequest(provider, "public_profile", "1043253362376121"); // We need to add the redirect uri so that the facebook app knows it's actually us. // This will use the store id you assigned in your facebook developer portal request.Properties.Add("redirect_uri", "msft-2f5fb048-0fd0-43e4-ad74-a9fc71e4b53d:/Authorise"); if (isSilent) { result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request); } else { result = await WebAuthenticationCoreManager.RequestTokenAsync(request); } } catch (Exception ex) { var i = 1; } return result; }
protected async override void OnNavigatedTo(NavigationEventArgs e) { wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority); appSettings = ApplicationData.Current.RoamingSettings; WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, clientId); wtr.Properties.Add("resource", resource); // Check if there's a record of the last account used with the app var userID = appSettings.Values["userID"]; if (userID != null) { // Get an account object for the user userAccount = await WebAuthenticationCoreManager.FindAccountAsync(wap, (string)userID); if (userAccount != null) { // Ensure that the saved account works for getting the token we need WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, userAccount); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { userAccount = wtrr.ResponseData[0].WebAccount; } else { // The saved account could not be used for getitng a token MessageDialog messageDialog = new MessageDialog("We tried to sign you in with the last account you used with this app, but it didn't work out. Please sign in as a different user."); await messageDialog.ShowAsync(); // Make sure that the UX is ready for a new sign in UpdateUXonSignOut(); } } else { // The WebAccount object is no longer available. Let's attempt a sign in with the saved username wtr.Properties.Add("LoginHint", appSettings.Values["login_hint"].ToString()); WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { userAccount = wtrr.ResponseData[0].WebAccount; } } } else { // There is no recorded user. Let's start a sign in flow without imposing a specific account. WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { userAccount = wtrr.ResponseData[0].WebAccount; } } if (userAccount != null) // we succeeded in obtaining a valid user { // save user ID in local storage UpdateUXonSignIn(); } else { // nothing we tried worked. Ensure that the UX reflects that there is no user currently signed in. UpdateUXonSignOut(); MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again."); await messageDialog.ShowAsync(); } }
// Get an access token for the given context and resourceId. An attempt is first made to // acquire the token silently. If that fails, then we try to acquire the token by prompting the user. public static async Task<string> GetTokenHelperAsync() { string token = null; aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority); // Check if there's a record of the last account used with the app. var userID = _settings.Values["userID"]; if (userID != null) { WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId); webTokenRequest.Properties.Add("resource", ResourceUrl); // Get an account object for the user. userAccount = await WebAuthenticationCoreManager.FindAccountAsync(aadAccountProvider, (string)userID); // Ensure that the saved account works for getting the token we need. WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; userAccount = webTokenResponse.WebAccount; token = webTokenResponse.Token; } else { // The saved account could not be used for getting a token. // Make sure that the UX is ready for a new sign in. SignOut(); } } else { // There is no recorded user. Start a sign-in flow without imposing a specific account. WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication); webTokenRequest.Properties.Add("resource", ResourceUrl); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; userAccount = webTokenResponse.WebAccount; token = webTokenResponse.Token; } } // We succeeded in getting a valid user. if (userAccount != null) { // Save user ID in local storage. _settings.Values["userID"] = userAccount.Id; _settings.Values["userEmail"] = userAccount.UserName; _settings.Values["userName"] = userAccount.Properties["DisplayName"]; return token; } // We didn't succeed in getting a valid user. Clear the app settings so that another user can sign in. else { SignOut(); return null; } }
public async Task <string> FetchTransferTokenAsync(AuthenticationRequestParameters authenticationRequestParameters, WebAccountProvider accountProvider) { if (!authenticationRequestParameters.AppConfig.IsMsaPassthrough) { throw new InvalidOperationException("Not configured for msa-pt"); } _logger.Verbose("WAM MSA-PT - fetching transfer token"); string transferToken = await FetchMsaPassthroughTransferTokenAsync( authenticationRequestParameters, accountProvider) .ConfigureAwait(false); return(transferToken); }
private async void AccountCommandsRequested(AccountsSettingsPane accountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs eventArgs) { AccountsSettingsPaneEventDeferral deferral = eventArgs.GetDeferral(); HttpResult<ExternalLogin[]> result; using (AccountClient accountClient = ClientFactory.CreateAccountClient()) { result = await accountClient.GetExternalLoginsAsync(); } if (result.Succeeded) { eventArgs.HeaderText = "Please select a login provider."; WebAccountProviderCommandInvokedHandler providerCmdHandler = new WebAccountProviderCommandInvokedHandler(WebAccountProviderInvokedHandler); foreach (ExternalLogin externalLogin in result.Content) { WebAccountProvider provider = new WebAccountProvider(externalLogin.Url, externalLogin.Name, App.LoginIcons[externalLogin.Name]); WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, providerCmdHandler); eventArgs.WebAccountProviderCommands.Add(providerCommand); } } else { await ErrorDialog.ShowErrorsAsync("Error connecting to external accounts.", result.Errors); } deferral.Complete(); }
public async void AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID) { try { WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID); // Azure Active Directory requires a resource to return a token if(Provider.Id == "https://login.microsoft.com" && Provider.Authority == "organizations") { webTokenRequest.Properties.Add("resource", "https://graph.windows.net"); } // If the user selected a specific account, RequestTokenAsync will return a token for that account. // The user may be prompted for credentials or to authorize using that account with your app // If the user selected a provider, the user will be prompted for credentials to login to a new account WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { defaultAccount = webTokenRequestResult.ResponseData[0].WebAccount; button_GetTokenSilently.IsEnabled = true; textblock_SignedInStatus.Text = "Signed in with:"; textblock_SignedInStatus.Foreground = new SolidColorBrush(Windows.UI.Colors.Green); listview_SignedInAccounts.Items.Clear(); listview_SignedInAccounts.Items.Add(defaultAccount.Id); } OutputTokenResult(webTokenRequestResult); } catch (Exception ex) { rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage); } }
private async Task GetTokenSilent(WebAccountProvider Provider, WebAccount Account) { // Set the clientID and scope based on the authority. The authority tells us if the account is a Microsoft account or an Azure AD. String scope = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountScopeRequested : AzureActiveDirectoryScopeRequested; String clientID = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountClientId : AzureActiveDirectoryClientId; WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, scope, clientID); // Azure Active Directory requires a resource to return a token if (Provider.Authority == "organizations") { webTokenRequest.Properties.Add("resource", "https://graph.windows.net"); } WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, Account); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { rootPage.NotifyUser("Silent request successful for user:"******"Cannot retrieve token silently because user interaction is required to complete this request.", NotifyType.ErrorMessage); } else { rootPage.NotifyUser("Web Token request error: " + webTokenRequestResult.ResponseStatus + " Code: " + webTokenRequestResult.ResponseError.ErrorMessage, NotifyType.StatusMessage); } }
private async Task RequestTokenAndSaveAccount(WebAccountProvider Provider, String Scope, String ClientID) { try { WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID); rootPage.NotifyUser("Requesting Web Token", NotifyType.StatusMessage); // If the user selected a specific account, RequestTokenAsync will return a token for that account. // The user may be prompted for credentials or to authorize using that account with your app // If the user selected a provider, the user will be prompted for credentials to login to a new account WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); // If a token was successfully returned, then store the WebAccount Id into local app data // This Id can be used to retrieve the account whenever needed. To later get a token with that account // First retrieve the account with FindAccountAsync, and include that webaccount // as a parameter to RequestTokenAsync or RequestTokenSilentlyAsync if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); ApplicationData.Current.LocalSettings.Values[StoredAccountKey] = webTokenRequestResult.ResponseData[0].WebAccount.Id; } OutputTokenResult(webTokenRequestResult); } catch (Exception ex) { rootPage.NotifyUser("Web Token request failed: " + ex.Message, NotifyType.ErrorMessage); } }
public async Task <string> TryFetchTransferTokenAsync(AuthenticationRequestParameters authenticationRequestParameters, WebAccountProvider accountProvider) { // Apps can have MSA-PT enabled and can configured to allow MSA users // However, some older apps have 2 incarnations, one in AAD tenant and one in MSA tenant // For this second case, we can't fetch the transfer token from the client_ID in AAD and this will fail _logger.Verbose("WAM MSA-PT - fetching transfer token"); string transferToken = await FetchMsaPassthroughTransferTokenAsync( authenticationRequestParameters, accountProvider) .ConfigureAwait(false); return(transferToken); }