Esempio n. 1
0
 public void OutputTokenResult(WebTokenRequestResult result)
 {
     if (result.ResponseStatus == WebTokenRequestStatus.Success)
     {
         rootPage.NotifyUser("Web Token request successful for user:"******"Web Token request error: " + result.ResponseStatus + " Code: " + result.ResponseError.ErrorMessage, NotifyType.StatusMessage);
     }
 }
Esempio n. 2
0
 public void OutputTokenResult(WebTokenRequestResult result)
 {
     if (result.ResponseStatus == WebTokenRequestStatus.Success)
     {
         DisplayInfoAsync("Web Token request successful for user:"******"Web Token request error: " + result.ResponseError);
     }
 }
 private SignInResult ConvertWebTokenRequestStatus(WebTokenRequestResult tokenResult)
 {
     if (tokenResult.ResponseStatus == WebTokenRequestStatus.UserCancel)
     {
         return(new SignInResult(SignInStatus.UserCancel));
     }
     else
     {
         return(new SignInResult(SignInStatus.UserInteractionRequired));
     }
 }
Esempio n. 4
0
    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);
    }
Esempio n. 5
0
 private async void WAM_Failed(WebAccountManager.WebAccountProviderInfo pi, WebTokenRequestResult result)
 {
     try
     {
         this.Platform.Logger.LogError(result?.ResponseError.ToException(), "WAM failed to retrieve user account token.");
         await this.ShowMessageBoxAsync(CancellationToken.None, "Could not retrieve your Microsoft Account profile to pre-fill your account registration.");
     }
     catch (Exception ex)
     {
         this.Platform.Logger.LogError(ex, "Failed to perform work during WAM failure");
     }
 }
        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 void OutputTokenResult(WebTokenRequestResult result)
 {
     if (result.ResponseStatus == WebTokenRequestStatus.Success)
     {
         rootPage.NotifyUser("Web Token request successful for user: "******"Account";
     }
     else
     {
         rootPage.NotifyUser("Web Token request error: " + result.ResponseError, NotifyType.StatusMessage);
     }
 }
Esempio n. 8
0
 /// <summary>
 /// Flow to perform on any failures from the WAM popup
 /// </summary>
 /// <param name="pi"></param>
 /// <param name="result"></param>
 private async void WAM_Failed(WebAccountManager.WebAccountProviderInfo pi, WebTokenRequestResult result)
 {
     try
     {
         // Failure with WAM
         this.Platform.Logger.LogError(result?.ResponseError.ToException(), "WAM failed to retrieve user account token.");
         await this.ShowMessageBoxAsync(CancellationToken.None, string.Format(Account.TextWebAccountManagerRegisterAccountFailure, pi.WebAccountType));
     }
     catch (Exception ex)
     {
         await this.HandleExceptionAsync(ex, "Failed to perform work during WAM failure");
     }
 }
        private void HandleTokenError(WebTokenRequestResult result)
        {
            if (result.ResponseStatus == WebTokenRequestStatus.ProviderError)
            {
                Debug.WriteLine("You most likely haven't configured the application association with the store. " +
                                "Right-click on the project in Visual Studio, then follow the steps in " +
                                "Store -> Associate App with the store...");
            }

            Debug.WriteLine("Error from the provider: " +
                            $"ResponseStatus={result.ResponseStatus.ToString("G")}, " +
                            $"ErrorCode={result.ResponseError?.ErrorCode}, " +
                            $"ErrorMessage={result.ResponseError?.ErrorMessage}");
        }
Esempio n. 10
0
        public void HandleResult(WebTokenRequestResult webTokenRequestResult, bool addAccount = false)
        {
            switch (webTokenRequestResult.ResponseStatus)
            {
            case WebTokenRequestStatus.Success:

                DebugPrint("RequestTokenAsync succeeds");
                try
                {
                    WebTokenResponse tokenResponse = webTokenRequestResult.ResponseData[0];
                    ProcessWebTokenResponse(tokenResponse, addAccount);
                }
                catch (Exception ex)
                {
                    DebugPrint("Exeption during ResponseData: " + ex.Message);
                }
                break;


            case WebTokenRequestStatus.UserCancel:

                // Handle user cancel by resuming pre-login screen
                DebugPrint("User cancelled the authentication");
                break;


            case WebTokenRequestStatus.AccountProviderNotAvailable:

                // fall back to WebAuthenticationBroker
                DebugPrint("WebTokenRequestStatus.AccountProviderNotAvailable");
                break;

            case WebTokenRequestStatus.ProviderError:
                DebugPrint(string.Format("Error: 0x{0:X08} message: {1}", webTokenRequestResult.ResponseError.ErrorCode, webTokenRequestResult.ResponseError.ErrorMessage));
                break;

            case WebTokenRequestStatus.UserInteractionRequired:
                DebugPrint("WebTokenRequestStatus.UserInteractionRequired");

                if (webTokenRequestResult.ResponseError != null)
                {
                    DebugPrint(string.Format("Error: 0x{0:X08} message: {1}", webTokenRequestResult.ResponseError.ErrorCode, webTokenRequestResult.ResponseError.ErrorMessage));
                }
                break;

            default:
                DebugPrint("Unhandled webTokenRequestResult.ResponseStatus: " + webTokenRequestResult.ResponseStatus);
                break;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param></param>
        /// <returns></returns>
        public static async Task <string> GetTokenSilently()
        {
            token = null;

            result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(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(token);
        }
        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);
        }
        /// <summary>
        /// Purges token cache. Can be useful if user revoked consent (on https://account.live.com/consent/Manage)
        /// and cached tickets get rejected by the Groove API.
        /// </summary>
        public async Task PurgeTokenCache()
        {
            WebAccount currentAccount = await GetCurrentAccountAsync();

            if (currentAccount != null)
            {
                foreach (string scope in new[] { ProfileScope, GrooveApiScope, $"{ProfileScope} {GrooveApiScope}" })
                {
                    WebTokenRequest       request = new WebTokenRequest(currentAccount.WebAccountProvider, scope);
                    WebTokenRequestResult result  = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request, currentAccount);

                    await result.InvalidateCacheAsync();
                }
            }
        }
Esempio n. 14
0
        async public void acquireTokenSilentAsync(
            String authority,
            bool validateAuthority,
            String resourceUrl,
            String clientId,
            String userId,
            IPromise promise)
        {
            WebAccountProvider authContext;

            try
            {
                authContext = await getOrCreateContext(authority);
            }
            catch (Exception ex)
            {
                promise.Reject(ex);
                return;
            }

            try
            {
                WebTokenRequest wtr = new WebTokenRequest(authContext, "", clientId, WebTokenRequestPromptType.Default);
                wtr.Properties.Add("resource", resourceUrl);

                WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(wtr);

                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;
            }
        }
        /// <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
                    });
                }
            }
        }
Esempio n. 16
0
        //<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);
            }
        }
        public TokenRequestResult(WebTokenRequestResult result)
        {
            if (result != null)
            {
                this.ResponseStatus = result.ResponseStatus;
                this.ResponseError  = result.ResponseError;

                var responseData = result.ResponseData?.FirstOrDefault();
                if (responseData != null)
                {
                    this.Properties    = responseData.Properties;
                    this.ProviderError = responseData.ProviderError;
                    this.Token         = responseData.Token;
                    this.WebAccountId  = responseData.WebAccount.Id;
                }
            }
        }
        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);
        }
        /// <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");
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Handle token result
        /// </summary>
        /// <param name="result">Token result</param>
        private async void OutputTokenResult(WebTokenRequestResult result)
        {
            if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                CustomSettings.IsUserLogged = true;

                string token = result.ResponseData[0].Token;

                var restApi = new Uri(@"https://apis.live.net/v5.0/me?access_token=" + token);

                using (var client = new HttpClient())
                {
                    var infoResult = await client.GetAsync(restApi);

                    string content = await infoResult.Content.ReadAsStringAsync();

                    var jsonObject = JsonObject.Parse(content);
                    LoggingButton.Content = jsonObject["name"].GetString();
                }


                //var photoApi = new Uri(@"https://apis.live.net/v5.0/me/picture?access_token=" + token);
                //using (var client = new HttpClient())
                //{
                //    var photoResult = await client.GetAsync(photoApi);
                //    using (var imageStream = await photoResult.Content.ReadAsStreamAsync())
                //    {
                //        BitmapImage image = new BitmapImage();
                //        using (var randomStream = imageStream.AsRandomAccessStream())
                //        {
                //            await image.SetSourceAsync(randomStream);
                //            this.image.Source = image;
                //            var wid = image.PixelWidth;
                //            var hei = image.PixelHeight;
                //        }

                //    }
                //}
            }
            else
            {
                CustomSettings.IsUserLogged = false;
            }
        }
        /// <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);
        }
Esempio n. 22
0
        private static string GetTokenFromResult(WebTokenRequestResult result)
        {
            try
            {
                foreach (var data in result.ResponseData)
                {
                    if (!string.IsNullOrWhiteSpace(data.Token))
                    {
                        return(data.Token);
                    }
                }
            }
            catch (Exception ex)
            {
                ServiceUtil.LogService.Write(ex.ToString(), LoggingLevel.Warning);
            }

            return(null);
        }
Esempio n. 23
0
        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);
        }
Esempio n. 24
0
        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);
        }
Esempio n. 25
0
        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);
            }
        }
Esempio n. 26
0
        private async Task <string> GetMsaTokenSilentlyAsync()
        {
            // Recall the provider Id and account Id from the app's storage
            string providerId = ApplicationData.Current.RoamingSettings.Values["CurrentUserProviderId"]?.ToString();
            string accountId  = ApplicationData.Current.RoamingSettings.Values["CurrentUserId"]?.ToString();

            if (null == providerId || null == accountId)
            {
                return(null);
            }

            WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(providerId);

            WebAccount account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountId);

            if (account == null)
            {
                return(null);
            }

            var request = new WebTokenRequest(provider, "wl.basic");

            // We already have the web account, so we can call GetTokenSilentlyAsync instead of RequestTokenAsync.
            WebTokenRequestResult result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request, account);

            // Unable to get a token silently - you'll need to show the UI
            if (result.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
            {
                return(null);
            }
            // Success
            else if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                return(result.ResponseData[0].Token);
            }
            // Other error
            else
            {
                return(null);
            }
        }
Esempio n. 27
0
        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;
            }
        }
Esempio n. 28
0
        private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
        {
            try {
                WebTokenRequest webTokenRequest = new WebTokenRequest(command.WebAccountProvider, AccountScopeRequested, ClientId);
                webTokenRequest.Properties.Add("resource", Resource);

                WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);

                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    OnAuthSuccess(webTokenRequestResult.ResponseData[0].ConvertToAzureADToken());
                }
                else
                {
                    OnAuthFailed($"Auth failed: {webTokenRequestResult.ResponseError.ErrorMessage}");
                }
            }
            catch (Exception ex) {
                OnAuthFailed($"Exception occurred: {ex.Message}");
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Restituisce l'access Token per le Graph APIs
        /// </summary>
        public static async Task <string> GetTokenAsync()
        {
            WebAccount userAccount = null;

            WebAccountProvider aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority);

            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;
                return(webTokenResponse.Token);
            }

            return(null);
        }
        /// <summary>
        /// You shouldn't call this method directly. It's registered to the Account Pane, so it will be used as
        /// a callback when you call AccountsSettingsPane.Show();
        /// </summary>
        private async void SignInUserAccountAsync(WebAccountProviderCommand command)
        {
            Stopwatch timer = Stopwatch.StartNew();

            try
            {
                // We want to require all scopes right from the beginning
                // This way the user gives consent only once
                WebTokenRequest       request = new WebTokenRequest(command.WebAccountProvider, $"{ProfileScope} {GrooveApiScope}");
                WebTokenRequestResult result  = await WebAuthenticationCoreManager.RequestTokenAsync(request);

                if (result.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    Debug.WriteLine("Successful sign-in");

                    WebAccount account = result.ResponseData[0].WebAccount;

                    ApplicationData.Current.LocalSettings.Values[CurrentUserProviderKey] = account.WebAccountProvider.Id;
                    ApplicationData.Current.LocalSettings.Values[CurrentUserKey]         = account.Id;

                    UserIsSignedIn = true;
                    UserSignInChange(this, true);

                    timer.Stop();
                    return;
                }

                HandleTokenError(result);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Sign-in failure:");
                Debug.WriteLine(e.ToString());
            }
            finally
            {
                timer.Stop();
                Debug.WriteLine($"Sign-in took {timer.ElapsedMilliseconds}ms");
            }
        }
        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;

            }
        }
 private async void WAM_Failed(Services.WebAccountManager.WebAccountProviderInfo pi, WebTokenRequestResult result)
 {
     try
     {
         Platform.Current.Logger.LogError(result?.ResponseError.ToException(), "WAM failed to retrieve user account token.");
         await this.ShowMessageBoxAsync("Could not retrieve your Microsoft Account profile to pre-fill your account registration.");
     }
     catch (Exception ex)
     {
         Platform.Current.Logger.LogError(ex, "Failed to perform work during WAM failure");
     }
 }
 private void OutputTokenResult(WebTokenRequestResult result)
 {
     if (result.ResponseStatus == WebTokenRequestStatus.Success)
     {
         rootPage.NotifyUser("Web Token request successful for user: "******"Account";
     }
     else
     {
         rootPage.NotifyUser("Web Token request error: " + result.ResponseError, NotifyType.StatusMessage);
     }
 }
 public void OutputTokenResult(WebTokenRequestResult result)
 {
     if (result.ResponseStatus == WebTokenRequestStatus.Success)
     {
         rootPage.NotifyUser("Web Token request successful for user:"******"Web Token request error: " + result.ResponseStatus + " Code: " + result.ResponseError.ErrorMessage, NotifyType.StatusMessage);
     }
 }
Esempio n. 35
0
 /// <summary>
 /// Flow to perform on any failures from the WAM popup
 /// </summary>
 /// <param name="pi"></param>
 /// <param name="result"></param>
 private async void WAM_Failed(Services.WebAccountManager.WebAccountProviderInfo pi, WebTokenRequestResult result)
 {
     try
     {
         // Failure with WAM
         Platform.Current.Logger.LogError(result?.ResponseError.ToException(), "WAM failed to retrieve user account token.");
         await this.ShowMessageBoxAsync(string.Format(Strings.Account.TextWebAccountManagerRegisterAccountFailure, pi.WebAccountType));
     }
     catch (Exception ex)
     {
         Platform.Current.Logger.LogError(ex, "Failed to perform work during WAM failure");
     }
 }
Esempio n. 36
0
        /// <summary>
        /// Flow to perform on successful pick of an account from the WAM popup
        /// </summary>
        /// <param name="pi">Details of the WAM provider choosen</param>
        /// <param name="info">Details of the WAM authenticated account</param>
        /// <param name="result">WebTokenRequestResult instance containing token info.</param>
        private async void WAM_Success(Services.WebAccountManager.WebAccountProviderInfo pi, Services.WebAccountManager.WebAccountInfo info, WebTokenRequestResult result)
        {
            try
            {
                this.ShowBusyStatus(Strings.Account.TextAuthenticating, true);

                // Create an account with the API
                _cts = new CancellationTokenSource();

                var response = await DataSource.Current.AuthenticateAsync(info, _cts.Token);

                // Authenticate the user into the app
                Platform.Current.AuthManager.SetUser(response);

                Platform.Current.Navigation.Home(this.ViewParameter);
            }
            catch(Exception ex)
            {
                Platform.Current.Logger.LogError(ex, "Failed to perform work during WAM success");
            }
            finally
            {
                this.Dispose();
                this.ClearStatus();
            }
        }
        private async void WAM_Success(Services.WebAccountManager.WebAccountProviderInfo pi, Services.WebAccountManager.WebAccountInfo wad, WebTokenRequestResult result)
        {
            try
            {
                this.ShowBusyStatus(string.Format(Strings.Account.TextWebAccountManagerRetrievingProfile, pi.WebAccountType), true);

                await Platform.Current.WebAccountManager.SignoutAsync();

                _cts = new CancellationTokenSource();
                using (var api = new MicrosoftApi())
                {
                    var msa = await api.GetUserProfile(wad.Token, _cts.Token);
                    this.Populate(msa);
                }
            }
            catch (Exception ex)
            {
                Platform.Current.Logger.LogError(ex, "Failed to perform work during WAM success");
            }
            finally
            {
                this.Dispose();
                this.ClearStatus();
            }
        }