protected async override void OnNavigatedTo(NavigationEventArgs e) { try { var wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "organizations"); WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, "ba789272-8d97-425c-9cdf-e43c6e76d73c"); const string resource = "https://graph.windows.net"; //wtr.Properties.Add("resource", resource); WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { var userAccount = wtrr.ResponseData[0].WebAccount; } else { var x = wtrr.ResponseError; } } catch (Exception ex) { var s = ex.Message; } }
private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command) { string token = string.Empty; // AccountClientID is ignored by MSA WebTokenRequest webTokenRequest = new WebTokenRequest(command.WebAccountProvider, AccountScopeRequested, AccountClientId); // 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) { 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; } AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested; OnAuthenticated?.Invoke(this, new AuthenticatedEventArgs(token)); }
public AuthViewModel(IAuth auth) { _auth = auth; Button = "Sign in/out"; SignInOrOutCommand = new RelayCommand(async o => { // prepare a request with 'WebTokenRequestPromptType.ForceAuthentication', // which guarantees that the user will be able to enter an account of their choosing // regardless of what accounts are already present on the system var wtr = new WebTokenRequest(_auth.AccountProvider, string.Empty, _auth.ClientId, WebTokenRequestPromptType.ForceAuthentication); wtr.Properties.Add("resource", _auth.Resource); var wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { _auth.Account = wtrr.ResponseData[0].WebAccount; SignedIn(); } else { SignedOut(); MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again."); await messageDialog.ShowAsync(); } }); }
public static async Task <bool> LogOut() { WebAccountProvider wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority); //Getting redirect url //string URI = string.Format("ms-appx-web://Microsoft.AAD.BrokerPlugIn/{0}", WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); //resource = URI; WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, clientId); wtr.Properties.Add("resource", resource); WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { var account = wtrr.ResponseData[0].WebAccount; await account.SignOutAsync(); return(true); } else { return(false); } }
public static async Task <string> GetTokenForUserAsync() { //for most Enteprise apps, we only care about AAD version of MSGraph string authority = "organizations"; // string resource = "https://graph.windows.net"; // This is the Azure AD Graph not MS Graph... string resource = "https://graph.microsoft.com"; //Microsoft Graph string TokenForUser = null; var wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority); // craft the token request for the Graph api //What is the correct scope? WebTokenRequest wtr = new WebTokenRequest(wap, _scopes, _clientId); wtr.Properties.Add("resource", resource); WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { TokenForUser = wtrr.ResponseData[0].Token; } else { System.Diagnostics.Debug.WriteLine(wtrr.ResponseError); } return(TokenForUser); }
protected override async Task <WebTokenResponse> GetToken(string resource, string authority = null) { if (authority == null) { authority = Authority; } else { authority = $"{LoginBase}/{authority}"; } WebAccountProvider wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority); var tokenRequest = new WebTokenRequest(wap, string.Empty, AppClientId); tokenRequest.Properties.Add("resource", resource); try { var tokenResponse = await WebAuthenticationCoreManager.RequestTokenAsync(tokenRequest); if (tokenResponse.ResponseStatus != WebTokenRequestStatus.Success) { throw new Exception(tokenResponse.ResponseError.ErrorMessage); } return(tokenResponse.ResponseData.Single()); } catch { throw; } }
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); } }
/// <summary> /// Get token and save account /// </summary> /// <param name="Provider">Provider</param> /// <param name="Scope">Scope</param> /// <param name="ClientID">Client ID</param> /// <returns></returns> private async Task RequestTokenAndSaveAccount(WebAccountProvider Provider, String Scope, String ClientID) { try { WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID); WebTokenRequestResult tokenResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (tokenResult.ResponseStatus == WebTokenRequestStatus.Success) { ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountProviderKey); ApplicationData.Current.LocalSettings.Values[StoredAccountKey] = tokenResult.ResponseData[0].WebAccount.Id; ApplicationData.Current.LocalSettings.Values[StoredAccountProviderKey] = tokenResult.ResponseData[0].WebAccount.WebAccountProvider.Id; } else { CustomSettings.IsUserLogged = false; } OutputTokenResult(tokenResult); } catch (Exception e) { Debug.WriteLine(e.Message); } }
public static async Task <ImageMenuItem> SignIn() { provider = await GetProvider(); String accountID = (String)ApplicationData.Current.LocalSettings.Values[StoredAccountKey]; WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID); WebTokenRequest webTokenRequest = new WebTokenRequest(provider, GraphScope, AccountClientId); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, account); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); ApplicationData.Current.LocalSettings.Values[StoredAccountKey] = webTokenRequestResult.ResponseData[0].WebAccount.Id; ImageMenuItem userDetails = await GetUser(webTokenRequestResult.ResponseData[0].Token, FullName); ApplicationData.Current.LocalSettings.Values[StoredNameKey] = userDetails.AccountName; ImageMenuItem userDetail = await GetUser(webTokenRequestResult.ResponseData[0].Token, Email); ApplicationData.Current.LocalSettings.Values[StoredEmailKey] = userDetail.AccountName; userDetails.Arguments = userDetail.AccountName; return(userDetails); } return(null); }
public async System.Threading.Tasks.Task <string> GetAzureADUserInteractiveTokenUWP(string ApplicationID, string tenantDomain) { string token = string.Empty; string authority = "https://login.microsoftonline.com/" + tenantDomain; try { // WebAccountProvider wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority); WebAccountProvider wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoftonline.com/", authority); string resource = "https://rest.media.azure.net"; WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, ApplicationID); if (wtr != null) { wtr.Properties.Add("resource", resource); WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { token = wtrr.ResponseData[0].Token; var account = wtrr.ResponseData[0].WebAccount; var properties = wtrr.ResponseData[0].Properties; } } } catch (Exception e) { LogMessage("Exception " + e.Message); token = string.Empty; } return(token); }
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 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 <IWebTokenRequestResultWrapper> RequestTokenForWindowAsync( IntPtr _parentHandle, WebTokenRequest webTokenRequest, WebAccount wamAccount) { using (_logger.LogBlockDuration("WAM:RequestTokenForWindowAsync:")) { if (_logger.IsLoggingEnabled(LogLevel.Verbose)) { _logger.VerbosePii(webTokenRequest.ToLogString(true), webTokenRequest.ToLogString(false)); _logger.VerbosePii(wamAccount.ToLogString(true), wamAccount.ToLogString(false)); } #if WINDOWS_APP // UWP requires being on the UI thread await _synchronizationContext; WebTokenRequestResult wamResult = await WebAuthenticationCoreManager.RequestTokenAsync( webTokenRequest, wamAccount); #else var wamResult = await WebAuthenticationCoreManagerInterop.RequestTokenWithWebAccountForWindowAsync( _parentHandle, webTokenRequest, wamAccount); #endif return(new WebTokenRequestResultWrapper(wamResult)); } }
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); }
private async void GetMsaToken(WebAccountProviderCommand command) { WebTokenRequest request = new WebTokenRequest(command.WebAccountProvider, "wl.basic"); WebTokenRequestResult result = await WebAuthenticationCoreManager.RequestTokenAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { WebAccount account = result.ResponseData[0].WebAccount; StoreWebAccount(account); //var restApi = new Uri(@"https://apis.live.net/v5.0/me?access_token=" + token); //var webAccount = await WebAuthenticationCoreManager.FindAccountAsync(command.WebAccountProvider, token); //using (var client = new HttpClient()) //{ // var infoResult = await client.GetAsync(restApi); // string content = await infoResult.Content.ReadAsStringAsync(); // var jsonObject = JsonObject.Parse(content); // string id = jsonObject["id"].GetString(); // string username = jsonObject["name"].GetString(); // UserIdTextBlock.Text = id; // UserNameTextBlock.Text = username; // var asdf = new WebAccount(command.WebAccountProvider, username, WebAccountState.Connected); } }
public async Task <string> GetAccessTokenForResource(string resource) { 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, App.Current.Resources["ida:ClientID"].ToString(), WebTokenRequestPromptType.Default); webTokenRequest.Properties.Add("authority", "https://login.windows.net"); webTokenRequest.Properties.Add("resource", resource); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; token = webTokenResponse.Token; } else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired) { //get token through prompt webTokenRequest = new WebTokenRequest(aadAccountProvider, String.Empty, App.Current.Resources["ida:ClientID"].ToString(), WebTokenRequestPromptType.ForceAuthentication); webTokenRequest.Properties.Add("authority", "https://login.windows.net"); webTokenRequest.Properties.Add("resource", resource); webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; token = webTokenResponse.Token; } } return(token); }
private static async Task <WebTokenResponse> RequestTokenAsync(bool forceLogin) { // [SCENARIO] OAuth 2.0 Authorization Code Grant, Public Client // Get a token to authenticate against the Web API. var promptType = forceLogin ? WebTokenRequestPromptType.ForceAuthentication : WebTokenRequestPromptType.Default; var provider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com/", AppConfiguration.AccountProviderAuthority); var request = new WebTokenRequest(provider, string.Empty, AppConfiguration.TodoListWindows10ClientId, promptType); request.Properties.Add("resource", AppConfiguration.TodoListWebApiResourceId); request.Properties.Add("authority", AppConfiguration.StsAuthority); // Skip authority validation for AD FS, otherwise you get the following error: // ERROR: The value specified for 'authority' is invalid. It is not in the valid authority list or not discovered. (3399548934) request.Properties.Add("validateAuthority", AppConfiguration.CanValidateAuthority.ToString()); var result = await WebAuthenticationCoreManager.RequestTokenAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { // [NOTE] At this point we have the authentication result, including the user information. // From this point on we can use the regular OAuth 2.0 Bearer Token to call the Web API. return(result.ResponseData.Single()); } else if (result.ResponseStatus != WebTokenRequestStatus.UserCancel) { var errorMessage = result.ResponseError == null ? "Unknown error" : result.ResponseError.ErrorMessage; throw new Exception(errorMessage); } else { return(null); } }
private async Task RequestTokenAndSaveAccount(WebAccountProvider Provider, String Scope, String ClientID) { try { WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); ApplicationData.Current.LocalSettings.Values[StoredAccountKey] = webTokenRequestResult.ResponseData[0].WebAccount.Id; TokenOne = webTokenRequestResult.ResponseData[0].Token; webTokenRequest = new WebTokenRequest(Provider, AccountScopeTwo, ClientID); webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { TokenTwo = webTokenRequestResult.ResponseData[0].Token; } SignIntoAppService(); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
public async void AuthenticateWithRequestToken( String WebAccountProviderID, String Authority, String Scope, String ClientID, String TokenBindingTarget, String RequestProperties) { try { // //create webTokenRequest with ProviderID, Scope, ClientId // DebugPrint("creating the webAccountProviderID"); WebAccountProvider provider = null; if (String.IsNullOrEmpty(Authority)) { DebugPrint("calling FindAccountProviderAsync..."); provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(WebAccountProviderID); } else { DebugPrint("calling FindAccountProviderWithAuthorityAsync..."); provider = await WebAuthenticationCoreManager.FindAccountProviderAsync( WebAccountProviderID, Authority); } DebugPrint("Provider Id: " + provider.Id); DebugPrint("Provider DisplayName: " + provider.DisplayName); WebTokenRequestPromptType prompt = ForceUiCheckBox.IsChecked.Value ? WebTokenRequestPromptType.ForceAuthentication : WebTokenRequestPromptType.Default; WebTokenRequest webTokenRequest = new WebTokenRequest( provider, Scope, ClientID, prompt); // // add properties to the tokenrequest if the IDP plugin requires // AddRequestProperties(RequestProperties, webTokenRequest); DebugPrint("Call RequestTokenAsync"); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); HandleResult(webTokenRequestResult); } catch (Exception ex) { DebugPrint("RequestToken failed: " + ex.Message); } }
private static async Task AuthenticateWithRequestToken(WebAccountProvider provider, string scope, string clientId) { var tokenRequest = new WebTokenRequest(provider, scope, clientId, WebTokenRequestPromptType.ForceAuthentication); var result = await WebAuthenticationCoreManager.RequestTokenAsync(tokenRequest); if (result.ResponseStatus == WebTokenRequestStatus.Success) { DumpResponse(result.ResponseData[0]); } }
private async void GetMsaTokenAsync(WebAccountProviderCommand command) { WebTokenRequest request = new WebTokenRequest(command.WebAccountProvider, "wl.basic"); WebTokenRequestResult result = await WebAuthenticationCoreManager.RequestTokenAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { string token = result.ResponseData[0].Token; } }
private static async Task <string> GetXTokenAsync() { string token = string.Empty; // Get an XToken // Find the account provider using the signed in user. // We always use the 1st signed in user, because we just need a valid token. It doesn't // matter who's it is. Windows.System.User currentUser; WebTokenRequest request; var users = await Windows.System.User.FindAllAsync(); currentUser = users[0]; WebAccountProvider xboxProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://xsts.auth.xboxlive.com", "", currentUser); // Build the web token request using the account provider. // Url = URL of the service we are getting a token for - for example https://apis.mycompany.com/something. // As this is a sample just use xboxlive.com // Target & Policy should always be set to "xboxlive.signin" and "DELEGATION" // For this call to succeed your console needs to be in the XDKS.1 sandbox request = new Windows.Security.Authentication.Web.Core.WebTokenRequest(xboxProvider); request.Properties.Add("Url", "https://xboxlive.com"); request.Properties.Add("Target", "xboxlive.signin"); request.Properties.Add("Policy", "DELEGATION"); // Request a token - correct pattern is to call getTokenSilentlyAsync and if that // fails with WebTokenRequestStatus.userInteractionRequired then call requestTokenAsync // to get the token and prompt the user if required. // getTokenSilentlyAsync can be called on a background thread. WebTokenRequestResult tokenResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request); //If we got back a token call our service with that token if (tokenResult.ResponseStatus == WebTokenRequestStatus.Success) { token = tokenResult.ResponseData[0].Token; } else if (tokenResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired) { // WebTokenRequestStatus.userInteractionRequired = 3 // If user interaction is required then call requestTokenAsync instead - this will prompt for user permission if required // Note: RequestTokenAsync cannot be called on a background thread. WebTokenRequestResult tokenResult2 = await WebAuthenticationCoreManager.RequestTokenAsync(request); //If we got back a token call our service with that token if (tokenResult2.ResponseStatus == WebTokenRequestStatus.Success) { token = tokenResult.ResponseData[0].Token; } else if (tokenResult2.ResponseStatus == WebTokenRequestStatus.UserCancel) { // No-op } } return(token); }
async public void acquireTokenAsync( string authority, bool validateAuthority, string resourceUrl, string clientId, string redirectUrl, string userId, string extraQueryParams, IPromise promise) { WebAccountProvider authContext; try { authContext = await getOrCreateContext(authority); } catch (Exception ex) { promise.Reject(ex); return; } RunOnDispatcher(async() => { try { WebTokenRequest wtr = new WebTokenRequest(authContext, "", clientId, WebTokenRequestPromptType.Default); wtr.Properties.Add("resource", resourceUrl); WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr); // WebAccount userAccount; if (wtrr.ResponseStatus == WebTokenRequestStatus.Success) { WebTokenResponse response = wtrr.ResponseData[0]; var props = new Dictionary <string, string>(response.Properties); AuthenticationResult result = new AuthenticationResult(response.Token, props); promise.Resolve(result); } else { promise.Reject($"{wtrr.ResponseError.ErrorCode}", new Exception(wtrr.ResponseError.ErrorMessage)); } } catch (Exception ex) { promise.Reject(ex); return; } }); }
public async Task <IWebTokenRequestResultWrapper> RequestTokenForWindowAsync( IntPtr _parentHandle, WebTokenRequest webTokenRequest) { #if WINDOWS_APP WebTokenRequestResult wamResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); #else var wamResult = await WebAuthenticationCoreManagerInterop.RequestTokenForWindowAsync( _parentHandle, webTokenRequest); #endif return(new WebTokenRequestResultWrapper(wamResult)); }
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 DocumentManager.SetAccountAsync(result.ResponseData[0].WebAccount); await DocumentManager.LoadItemsAsync(); } }
/// <summary> /// /// </summary> /// <param></param> /// <returns></returns> public static async Task <string> GetToken() { token = null; result = await WebAuthenticationCoreManager.RequestTokenAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountKey); ApplicationData.Current.LocalSettings.Values[StoredAccountKey] = result.ResponseData[0].WebAccount.Id; token = result.ResponseData[0].Token; } return(""); }
private WebTokenRequestResult RequestTokenFromIDP(CoreDispatcher coreDispatcher, bool promptForCredentialsIfNeeded, WebTokenRequest request) { WebTokenRequestResult tokenResult = null; if (coreDispatcher != null && promptForCredentialsIfNeeded) { TaskCompletionSource <object> completionSource = new TaskCompletionSource <object>(); var requestTokenTask = coreDispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { WebAuthenticationCoreManager.RequestTokenAsync(request).Completed = (info, status) => { try { tokenResult = info.GetResults(); completionSource.SetResult(null); } catch (Exception e) { completionSource.SetException(e); } }; }); completionSource.Task.Wait(); if (completionSource.Task.Exception != null) { throw completionSource.Task.Exception; } } else { IAsyncOperation <WebTokenRequestResult> getTokenTask; TaskCompletionSource <WebTokenRequestResult> webTokenRequestSource = new TaskCompletionSource <WebTokenRequestResult>(); if (promptForCredentialsIfNeeded) { getTokenTask = WebAuthenticationCoreManager.RequestTokenAsync(request); } else { getTokenTask = WebAuthenticationCoreManager.GetTokenSilentlyAsync(request); } getTokenTask.Completed += (tokenTask, status) => webTokenRequestSource.SetResult(tokenTask.GetResults()); tokenResult = webTokenRequestSource.Task.Result; } return(tokenResult); }
private async Task <WebTokenRequestResult> RequestTokenWithTimeout(WebTokenRequest request) { // The WebTokenRequest will time out if the user does not complete in time. // This is because there is currently no 'close' button on IoT Core, so it // will prevent users from getting stuck on the sign-in page forever. var requestOperation = WebAuthenticationCoreManager.RequestTokenAsync(request); var delay = Task.Delay(TimeSpan.FromSeconds(DialogTimeoutSeconds)); ServiceUtil.LogService.Write("Calling WebAuthenticationCoreManager.RequestTokenAsync()..."); var taskResult = await Task.WhenAny(delay, requestOperation.AsTask()); if (requestOperation.Status == AsyncStatus.Started) { requestOperation.Cancel(); } ServiceUtil.LogService.Write("WebTokenRequestAsync.Status: " + Enum.GetName(typeof(AsyncStatus), requestOperation.Status)); if (taskResult == delay) { ServiceUtil.LogService.Write("MSA dialog timeout"); return(null); } var tokenResult = requestOperation.GetResults(); ServiceUtil.LogService.Write("WebTokenRequestResult: " + Enum.GetName(typeof(WebTokenRequestStatus), tokenResult.ResponseStatus)); if (tokenResult != null) { switch (tokenResult.ResponseStatus) { case WebTokenRequestStatus.Success: ServiceUtil.LogService.Write("Successfully signed in! " + tokenResult.ResponseData[0].WebAccount.UserName); _appSettings.Values[_userIdKey] = tokenResult.ResponseData[0].WebAccount.Id; break; default: ServiceUtil.LogService.Write("ResponseStatus: " + Enum.GetName(typeof(WebTokenRequestStatus), tokenResult.ResponseStatus), LoggingLevel.Error); if (tokenResult.ResponseError != null) { ServiceUtil.LogService.Write("Error code: " + tokenResult.ResponseError.ErrorCode, LoggingLevel.Error); ServiceUtil.LogService.Write("Error message: " + tokenResult.ResponseError.ErrorMessage, LoggingLevel.Error); } break; } } return(tokenResult); }
/// <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); }
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); } }