private async void BuildPaneAsync(AccountsSettingsPane sender, AccountsSettingsPaneCommandsRequestedEventArgs e) { var deferral = e.GetDeferral(); try { var provider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers"); var command = new WebAccountProviderCommand(provider, GetMsaTokenAsync); e.WebAccountProviderCommands.Add(command); } finally { deferral.Complete(); } }
public static IAsyncOperation <WebTokenRequestResult> RequestTokenForWindowAsync(IntPtr hWnd, WebTokenRequest request) { IWebAuthenticationCoreManagerInterop webAuthenticationCoreManagerInterop = WebAuthenticationCoreManager.As <IWebAuthenticationCoreManagerInterop>(); Guid guid = WinRT.GuidGenerator.CreateIID(typeof(IAsyncOperation <WebTokenRequestResult>)); var requestPtr = MarshalInspectable <WebTokenRequest> .FromManaged(request); webAuthenticationCoreManagerInterop.RequestTokenForWindowAsync( hWnd, requestPtr, ref guid, out IntPtr result); return(MarshalInterface <IAsyncOperation <WebTokenRequestResult> > .FromAbi(result)); }
public async Task InitializeProvider(User user) { if (this.HasProvider) { return; } if (user == null) { provider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://xsts.auth.xboxlive.com"); } else { provider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://xsts.auth.xboxlive.com", string.Empty, user); } }
/// <summary> /// Gets the currently saved user account. /// </summary> private async Task <WebAccount> GetCurrentAccountAsync() { string providerId = ApplicationData.Current.LocalSettings.Values[CurrentUserProviderKey]?.ToString(); string accountId = ApplicationData.Current.LocalSettings.Values[CurrentUserKey]?.ToString(); if (providerId == null || accountId == null) { return(null); } WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(providerId); WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountId); return(account); }
/// <summary> /// Gets an auth token for the user, which can be used to call the Microsoft Graph API. /// </summary> private async Task <string> GetTokenAsync() { var provider = await GetAadProviderAsync(); var request = new WebTokenRequest(provider, "User.Read", AccountClientId); request.Properties.Add("resource", "https://graph.microsoft.com"); var result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request); if (result.ResponseStatus != WebTokenRequestStatus.Success) { result = await WebAuthenticationCoreManager.RequestTokenAsync(request); } return(result.ResponseStatus == WebTokenRequestStatus.Success ? result.ResponseData[0].Token : null); }
/// <summary> /// Checks if the user has credentials stored and tries to automatically log in with them. /// </summary> public static async Task TryLogInSilently() { if (ApplicationData.Current.RoamingSettings.Values.ContainsKey(RoamingUserKey) && ApplicationData.Current.RoamingSettings.Values.ContainsKey(RoamingProviderKey)) { string username = ApplicationData.Current.RoamingSettings.Values[RoamingUserKey].ToString(); var vault = new PasswordVault(); var credential = vault.RetrieveAll().FirstOrDefault(x => x.Resource == VaultKey && x.UserName == username); if (null == credential) { return; } // MSA tokens are short-lived, so the existing cached token is likely invalid // Silently request a new token if (ApplicationData.Current.RoamingSettings.Values[RoamingProviderKey].ToString() == "msa") { var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers"); WebTokenRequest request = new WebTokenRequest(msaProvider, "wl.basic, wl.emails"); WebTokenRequestResult result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { await LoginOrRegisterAsync(new ProviderInfo { Provider = ProviderType.Msa, Token = result.ResponseData[0].Token }); } } // Facebook and google tokens last 60 days, so we can probably re-log in with one // If not, it will fail and show the OOBE expereince else { credential.RetrievePassword(); await LoginOrRegisterAsync(new ProviderInfo { Email = username, Provider = (ProviderType)Enum.Parse(typeof(ProviderType), ApplicationData.Current.RoamingSettings.Values[RoamingProviderKey].ToString(), true), Token = credential.Password }); } } }
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 static async Task <IReadOnlyList <WebAccount> > FindAllAccountsAsync(WebAccountProvider provider, string clientID, ICoreLogger logger) { FindAllAccountsResult findResult = await WebAuthenticationCoreManager.FindAllAccountsAsync(provider, clientID); // This is expected to happen with the MSA provider, which does not allow account listing if (findResult.Status != FindAllWebAccountsStatus.Success) { var error = findResult.ProviderError; logger.Info($"[WAM Proxy] WebAuthenticationCoreManager.FindAllAccountsAsync failed " + $" with error code {error.ErrorCode} error message {error.ErrorMessage} and status {findResult.Status}"); return(Enumerable.Empty <WebAccount>().ToList()); } logger.Info($"[WAM Proxy] FindAllWebAccountsAsync returning {findResult.Accounts.Count()} WAM accounts"); return(findResult.Accounts); }
private async void GetMsaTokenAsync(WebAccountProviderCommand command) { var request = new WebTokenRequest(command.WebAccountProvider, "wl.basic"); var result = await WebAuthenticationCoreManager.RequestTokenAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { await ProcessSuccessAsync(result); RaiseLoginComplete(); } else { // If you receive an error when requesting a token, make sure you've associated your app with the Store as described in step one. Your app won't be able to get a token if you skipped this step. RaiseLoginFailed(result.ResponseStatus); } }
//<GetMSAToken> private async Task <string> GetMicrosoftAccountTokenAsync() { var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync( "https://login.microsoft.com", "consumers"); WebTokenRequest request = new WebTokenRequest(msaProvider, "devcenter_implicit.basic,wl.basic"); WebTokenRequestResult result = await WebAuthenticationCoreManager.RequestTokenAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { return(result.ResponseData[0].Token); } else { return(string.Empty); } }
private async Task <UserAccount> GetMsaTokenAsync(WebAccountProviderCommand command) { var request = new WebTokenRequest(command.WebAccountProvider, tokenScope); var result = await WebAuthenticationCoreManager.RequestTokenAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { UpdateWebAccount(result.ResponseData[0].WebAccount); CurrentAccount = await CreateUserAccount(result.ResponseData[0].Token); return(CurrentAccount); } else { throw new InvalidOperationException("WebAuthentication Response: " + result.ResponseStatus); } }
#pragma warning disable 4014 private void FindAccountCompleted(IAsyncOperation <WebAccountProvider> asyncInfo, AsyncStatus asyncStatus) { WebTokenRequest request = new WebTokenRequest(asyncInfo.GetResults()); request.Properties.Add("HttpMethod", "GET"); request.Properties.Add("Url", "https://xboxlive.com"); request.Properties.Add("RequestHeaders", ""); request.Properties.Add("ForceRefresh", "true"); request.Properties.Add("Target", "xboxlive.signin"); request.Properties.Add("Policy", "DELEGATION"); request.Properties.Add("PackageFamilyName", Windows.ApplicationModel.Package.Current.Id.FamilyName); Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { WebAuthenticationCoreManager.RequestTokenAsync(request).Completed = TokenRequestCompleted; }); }
// 将指定的 web 账号添加到账号管理界面中 private async Task ShowLogoutUI(AccountsSettingsPaneCommandsRequestedEventArgs e) { WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority); WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, _userId); if (account != null) { // 最后一个参数用于指定当用户选择了账号后,会出现哪些功能按钮(我这里测试只有 SupportedWebAccountActions.Remove 是有效的) WebAccountCommand command = new WebAccountCommand(account, WebAccountCommandInvoked, SupportedWebAccountActions.Remove); e.WebAccountCommands.Add(command); } else { _userId = null; } }
public static async Task <string> GetWUToken(string accountId) { WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers"); WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountId); WebTokenRequest request = new WebTokenRequest(provider, "service::dcat.update.microsoft.com::MBI_SSL", "{28520974-CE92-4F36-A219-3F255AF7E61E}"); WebTokenRequestResult result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request, account); string token = result.ResponseData[0].Token; var tokenBinary = CryptographicBuffer.ConvertStringToBinary(token, BinaryStringEncoding.Utf16LE); var tokenBase64 = CryptographicBuffer.EncodeToBase64String(tokenBinary); Trace.WriteLine("Token = " + token); Trace.WriteLine("TokenBase64 = " + tokenBase64); return(tokenBase64); }
private async Task AddSelectorsAsync(AccountsSettingsPaneCommandsRequestedEventArgs args, bool addOrgAccounts, bool addMsaAccounts, string tenantId = null) { if (addOrgAccounts) { args.WebAccountProviderCommands.Add( new WebAccountProviderCommand( await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", tenantId ?? "organizations"), WebAccountProviderCommandInvoked)); } if (addMsaAccounts) { args.WebAccountProviderCommands.Add( new WebAccountProviderCommand( await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers"), WebAccountProviderCommandInvoked)); } }
private void CheckUserSignedOut() { try { if (this.IsSignedIn) { var signedInAccount = WebAuthenticationCoreManager.FindAccountAsync(this.provider, this.WebAccountId); if (signedInAccount == null) { this.UserSignedOut(); } } } catch (Exception) { this.UserSignedOut(); } }
private async Task LogoffAndRemoveAccount() { if (ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey)) { WebAccountProvider providertoDelete = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority); WebAccount accountToDelete = await WebAuthenticationCoreManager.FindAccountAsync(providertoDelete, (string)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]); if (accountToDelete != null) { await accountToDelete.SignOutAsync(); } ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); SignInButton.Content = "Sign in"; } }
public async Task <string> GetTokenAsync() { var webAccount = await GetWebAccount(); if (webAccount == null) { return(null); } var request = new WebTokenRequest(webAccount.WebAccountProvider, tokenScope); var result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request, webAccount); if (result.ResponseStatus == WebTokenRequestStatus.Success) { return(result.ResponseData[0].Token); } return(null); }
/// <summary> /// Log off and remove user from stored data /// </summary> /// <returns></returns> private async Task LogoffAndRemoveAccount() { if (ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey)) { WebAccountProvider providertoDelete = await WebAuthenticationCoreManager.FindAccountProviderAsync(MSAProviderId, ConsumerAuthority); WebAccount accountToDelete = await WebAuthenticationCoreManager.FindAccountAsync(providertoDelete, (string)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]); if (accountToDelete != null) { await accountToDelete.SignOutAsync(); } ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountProviderKey); CustomSettings.IsUserLogged = false; } }
public static IAsyncAction ShowAddAccountForWindowAsync(IntPtr hWnd) { IWebAuthenticationCoreManagerInterop webAuthenticationCoreManagerInterop = WebAuthenticationCoreManager.As <IWebAuthenticationCoreManagerInterop>(); IAccountsSettingsPaneInterop accountsSettingsPaneInterop = AccountsSettingsPane.As <IAccountsSettingsPaneInterop>(); //Guid guid = typeof(IAsyncAction).GUID; Guid guid = WinRT.GuidGenerator.CreateIID(typeof(IAsyncAction)); //IAccountsSettingsPaneInterop accountsSettingsPaneInterop = // (IAccountsSettingsPaneInterop)WindowsRuntimeMarshal.GetActivationFactory(typeof(AccountsSettingsPane)); //Guid guid = typeof(IAsyncAction).GUID; accountsSettingsPaneInterop.ShowAddAccountForWindowAsync(hWnd, ref guid, out IntPtr result); return(MarshalInterface <IAsyncAction> .FromAbi(result)); }
/// <summary> /// Gets a user token for a given account. /// </summary> private async Task <string> GetUserTokenAsync(WebAccount account, string scope, bool silentlyOnly) { Stopwatch timer = Stopwatch.StartNew(); try { WebTokenRequest request = new WebTokenRequest(account.WebAccountProvider, scope); WebTokenRequestResult result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request, account); if (result.ResponseStatus == WebTokenRequestStatus.Success) { Debug.WriteLine("Successfully got user token silently"); return(result.ResponseData[0].Token); } HandleTokenError(result); if (!silentlyOnly) { // If we couldn't get the token silently, RequestTokenAsync will prompt the user for necessary action result = await WebAuthenticationCoreManager.RequestTokenAsync(request, account); if (result.ResponseStatus == WebTokenRequestStatus.Success) { Debug.WriteLine("Successfully got user token with action"); return(result.ResponseData[0].Token); } HandleTokenError(result); } return(null); } catch (Exception e) { Debug.WriteLine(e.ToString()); return(null); } finally { timer.Stop(); Debug.WriteLine($"Getting user token took {timer.ElapsedMilliseconds}ms"); } }
private async Task AddWebAccount(AccountsSettingsPaneCommandsRequestedEventArgs e) { WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority); String accountID = (String)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]; WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID); if (account == null) { // The account has most likely been deleted in Windows settings // Unless there would be significant data loss, you should just delete the account // If there would be significant data loss, prompt the user to either re-add the account, or to remove it ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); } WebAccountCommand command = new WebAccountCommand(account, WebAccountInvoked, SupportedWebAccountActions.Remove); e.WebAccountCommands.Add(command); }
public async Task <string> GetToken(WebAccountProvider provider, string scope, string clientId) { string result = string.Empty; if (null != provider) { try { // The LenovoID team said we should avoid passing emtpy strings as parameters as per Microsoft's API documentation if (String.IsNullOrEmpty(scope)) { scope = "scope"; } if (String.IsNullOrEmpty(clientId)) { clientId = "clientid"; } WebTokenRequest webTokenRequest = new WebTokenRequest(provider, scope, clientId); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest); if (webTokenRequestResult != null && webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { if (webTokenRequestResult.ResponseData != null && webTokenRequestResult.ResponseData.Count > 0 && webTokenRequestResult.ResponseData[0].Token != null) { //formats userid|token result = webTokenRequestResult.ResponseData[0].Token; } } //Logger.Log(LogSeverity.Information, "Token received", result.ToString()); } catch (Exception ex) { //Logger.Log(LogSeverity.Information, "Lenovo ID App is not installed.", ex); } } else { //Logger.Log(LogSeverity.Information, "LenovoIdAgent: GetTokenSilentlyAsync - provider was null"); } return(result); }
/// <summary> /// /// </summary> /// <param></param> /// <returns></returns> public static async Task <bool> SignIntoAppService() { provider = await GetProvider(); String accountID = (String)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]; WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID); WebTokenRequest webTokenRequest = new WebTokenRequest(provider, LiveScope, AccountClientId); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, account); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { if (await AzureAppService.SignIn(webTokenRequestResult.ResponseData[0].Token)) { return(true); } } return(false); }
private async Task ValidateProviderSelection() { if (ProvidersComboBox.SelectedItem != null) { var targetProvider = ProvidersComboBox.SelectedItem as Provider; var targetWebAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(targetProvider.Id); if (targetWebAccountProvider != null) { SetProviderUI(targetProvider); currentWebAccountProvider = targetWebAccountProvider; } else { ProvidersComboBox.SelectedIndex = -1; DebugPrint("Error: The provider was not found in this system"); } } }
public static async Task <string> GetAccessToken() { string token = null; //first try to get the token silently WebAccountProvider aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.windows.net"); WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, String.Empty, clientId, WebTokenRequestPromptType.Default); webTokenRequest.Properties.Add("authority", "https://login.windows.net"); webTokenRequest.Properties.Add("resource", ResourceUrl); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest); //if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) //{ // WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; // userAccount = webTokenResponse.WebAccount; // token = webTokenResponse.Token; //} // else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired) // { //get token through prompt webTokenRequest = new WebTokenRequest(aadAccountProvider, String.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication); webTokenRequest.Properties.Add("authority", "https://login.windows.net"); webTokenRequest.Properties.Add("resource", ResourceUrl); webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; token = webTokenResponse.Token; userAccount = webTokenResponse.WebAccount; } // } 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); }
private async Task LogoffAndRemoveAccount() { if (ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountKey)) { WebAccountProvider providertoDelete = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, ConsumerAuthority); WebAccount accountToDelete = await WebAuthenticationCoreManager.FindAccountAsync(providertoDelete, (string)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]); if (accountToDelete != null) { await accountToDelete.SignOutAsync(); } ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); ApplicationData.Current.LocalSettings.Values.Remove(StoredEmailKey); AccountListViewItem.Visibility = Visibility.Collapsed; SignInListViewItem.Visibility = Visibility.Visible; await Shared.Helpers.LocalStore.PurgeLocalStoreAsync(); App.HomesViewModel = new HomesViewModel(); App.RoomsViewModel = new RoomsViewModel(); Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { bool autoSignIn = false; AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested; rootFrame.Navigate(typeof(Views.SignIn.MainPage), autoSignIn); } Window.Current.Activate(); } }
public async Task AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID, String RequestProperties) { DebugPrint("Entering AuthenticateWithRequestToken ..."); try { WebTokenRequest webTokenRequest = new WebTokenRequest( Provider, Scope, ClientID); DebugPrint("Call RequestTokenAsync"); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); HandleResult(webTokenRequestResult, true); // store returned account locally } catch (Exception ex) { DebugPrint("RequestToken failed: " + ex.Message); } }
private async Task <WebAccountProvider> FindProvider() { WebAccountProvider accountProvider; if (this.CreationContext == null) { accountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://xsts.auth.xboxlive.com"); } else { accountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://xsts.auth.xboxlive.com", string.Empty, this.CreationContext); } if (accountProvider == null) { throw new XboxException("Unable to find Xbox Live Identity Provider"); } return(accountProvider); }
private async Task Auth() { // craft the token request for the Graph api var wtr = new WebTokenRequest(_auth.AccountProvider, string.Empty, _auth.ClientId); wtr.Properties.Add("resource", _auth.Resource); // perform the token request without showing any UX var wtrr = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(wtr, _auth.Account); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { var accessToken = wtrr.ResponseData[0].Token; _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); } else { var messageDialog = new MessageDialog("We tried to get a token for the API as the account you are currently signed in, but it didn't work out. Please sign in as a different user."); await messageDialog.ShowAsync(); } }