Beispiel #1
0
        private async Task GetTokenSilent(WebAccountProvider Provider, WebAccount Account)
        {
            // Set the clientID and scope based on the authority. The authority tells us if the account is a Microsoft account or an Azure AD.
            String scope    = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountScopeRequested : AzureActiveDirectoryScopeRequested;
            String clientID = defaultProvider.Authority == MicrosoftAccountAuthority ? MicrosoftAccountClientId : AzureActiveDirectoryClientId;

            WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, scope, clientID);

            // Azure Active Directory requires a resource to return a token
            if (Provider.Authority == "organizations")
            {
                webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
            }

            WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, Account);

            if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
            {
                rootPage.NotifyUser("Silent request successful for user:"******"Cannot retrieve token silently because user interaction is required to complete this request.", NotifyType.ErrorMessage);
            }
            else
            {
                rootPage.NotifyUser("Web Token request error: " + webTokenRequestResult.ResponseStatus + " Code: " + webTokenRequestResult.ResponseError.ErrorMessage, NotifyType.StatusMessage);
            }
        }
Beispiel #2
0
        // perform a user search by alias against the directory Graph of the currently signed in user
        private async void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            // craft the token request for the Graph api
            WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, clientId);

            wtr.Properties.Add("resource", resource);
            // perform the token request without showing any UX
            WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(wtr, userAccount);

            if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
            {
                string accessToken = wtrr.ResponseData[0].Token;
                try
                {
                    SearchResults.ItemsSource = await DirectorySearcher.SearchByAlias(SearchTermText.Text, accessToken, userAccount.Properties["TenantId"]);
                }
                catch (Exception ee)
                {
                    MessageDialog messageDialog = new MessageDialog("The Graph query didn't work. Error: " + ee.Message);
                    await messageDialog.ShowAsync();
                }
            }
            else
            {
                MessageDialog messageDialog = new MessageDialog("We tried to get a token for the Graph as the account you are currently signed in, but it didn't work out. Please sign in as a different user.");
                await messageDialog.ShowAsync();
            }
        }
        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);
        }
Beispiel #4
0
        private async Task <WebTokenRequestResult?> SilentAuthAsync()
        {
            // Ref: https://docs.microsoft.com/en-us/windows/uwp/security/web-account-manager#store-the-account-for-future-use

            string providerId = _userSettings.Get <string>(UserSettingsConstants.CurrentUserProviderId);
            string accountId  = _userSettings.Get <string>(UserSettingsConstants.CurrentUserId);

            if (string.IsNullOrWhiteSpace(providerId) || string.IsNullOrWhiteSpace(accountId))
            {
                return(null);
            }

            try
            {
                WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(providerId);

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

                WebTokenRequest       request = new WebTokenRequest(provider, Scope, _clientId);
                WebTokenRequestResult result  = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request, account);

                return(result);
            }
            catch
            {
                return(null);
            }
        }
Beispiel #5
0
        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);
        }
Beispiel #6
0
        //retrieving token from storage
        public async Task <string> GetTokenSilentlyAsync()
        {
            string providerId = ApplicationData.Current.LocalSettings.Values["CurrentUserProviderId"]?.ToString();
            string accountId  = ApplicationData.Current.LocalSettings.Values["CurrentUserId"]?.ToString();

            if (null == providerId || null == accountId)
            {
                return(null);
            }
            WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(providerId);

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

            WebTokenRequest       request = new WebTokenRequest(provider, "wl.basic");
            WebTokenRequestResult result  = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request, account);

            if (result.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
            {
                // Unable to get a token silently - you'll need to show the UI
                return(null);
            }
            else if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                // Success
                return(result.ResponseData[0].Token);
            }
            else
            {
                // Other error
                return(null);
            }
        }
        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
            {
                WebAccount account = await TryGetUserAccount(authContext);

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

                WebTokenRequestResult wtrr;
                if (account != null)
                {
                    wtrr = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(wtr, account);
                }
                else
                {
                    wtrr = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(wtr);
                }

                if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    WebTokenResponse response = wtrr.ResponseData[0];

                    // use case insensitive prop names as keys (i.e. upn = UPN)
                    var props = new Dictionary <string, string>(response.Properties, StringComparer.OrdinalIgnoreCase);

                    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> GetTokenSilentlyForDefaultAccountAsync(WebTokenRequest webTokenRequest)
        {
            using (_logger.LogBlockDuration("WAM:GetTokenSilentlyAsync:"))
            {
                var wamResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);

                return(new WebTokenRequestResultWrapper(wamResult));
            }
        }
    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);
    }
        /// <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);
        }
        public async Task <IWebTokenRequestResultWrapper> GetTokenSilentlyForDefaultAccountAsync(WebTokenRequest webTokenRequest)
        {
            using (_logger.LogBlockDuration("WAM:GetTokenSilentlyAsync:"))
            {
                if (_logger.IsLoggingEnabled(LogLevel.Verbose))
                {
                    _logger.VerbosePii(webTokenRequest.ToLogString(true), webTokenRequest.ToLogString(false));
                }

                var wamResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);

                return(new WebTokenRequestResultWrapper(wamResult));
            }
        }
        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();
                }
            }
        }
Beispiel #14
0
        /// <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
                    });
                }
            }
        }
        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);
        }
Beispiel #17
0
        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>
        /// 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");
            }
        }
Beispiel #19
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);
        }
Beispiel #20
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);
        }
Beispiel #21
0
        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();
            }
        }
Beispiel #22
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);
            }
        }
        public async Task <string> AcquireTokenSilentAsync()
        {
            var webAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(_settings.WebAccountProviderId, _settings.Authority);

            var userId      = _appSettings.Values["userId"];
            var userAccount = await WebAuthenticationCoreManager.FindAccountAsync(webAccountProvider, (string)userId);

            var webTokenRequest = new WebTokenRequest(webAccountProvider, string.Empty, _settings.ClientId);

            webTokenRequest.Properties.Add("resource", _settings.ApiResource);
            var webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, userAccount);

            if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
            {
                _appSettings.Values["userId"]     = userAccount.Id;
                _appSettings.Values["login_hint"] = userAccount.UserName;
                return(webTokenRequestResult.ResponseData[0].Token);
            }

            return(null);
        }
Beispiel #24
0
        private async void SignOutButton_Click(object sender, RoutedEventArgs e)
        {
            var msaProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                "https://login.microsoft.com", "consumers");

            var request = new WebTokenRequest(msaProvider, "consumers");
            var result  = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
            {
                // Unable to get a token silently - you'll need to show the UI
            }
            else if (result.ResponseStatus == WebTokenRequestStatus.Success)
            {
                // Success, use your token
            }

            string id = ""; // ID obtained from calling https://apis.live.net/v5.0/me?access_token=" + token

            var webAccount = await WebAuthenticationCoreManager.FindAccountAsync(msaProvider, id);
        }
Beispiel #25
0
        private static async Task <string> GetAccessTokenForResource(string resource)
        {
            string token = null;


            WebAccountProvider aadAccount = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.windows.net");

            // WebTokenRequest request = new WebTokenRequest(aadAccount, string.Empty, App.Current.Resources["ida:ClientId"].ToString(), WebTokenRequestPromptType.Default);
            WebTokenRequest request = new WebTokenRequest(aadAccount, string.Empty, "48d16164-a3b3-4ab1-b626-a5271858fdac", WebTokenRequestPromptType.Default);

            request.Properties.Add("authority", "https://login.windows.net");
            request.Properties.Add("resource", resource);

            var response = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request);

            if (response.ResponseStatus == WebTokenRequestStatus.Success)
            {
                WebTokenResponse webToken = response.ResponseData[0];
                token = webToken.Token;
            }
            else if (response.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
            {
                aadAccount = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.windows.net");

                request = new WebTokenRequest(aadAccount, string.Empty, "48d16164-a3b3-4ab1-b626-a5271858fdac", WebTokenRequestPromptType.ForceAuthentication);
                request.Properties.Add("authority", "https://login.windows.net");
                request.Properties.Add("resource", resource);

                response = await WebAuthenticationCoreManager.RequestTokenAsync(request);

                if (response.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    WebTokenResponse webToken = response.ResponseData[0];
                    token = webToken.Token;
                }
            }


            return(token);
        }
Beispiel #26
0
        public async Task <string> GetTokenSilentAsync(string resource = null)
        {
            if (resource == null)
            {
                resource = _resource;
            }

            var userID = GetSavedAccountId();

            if (userID != null)
            {
                var provider = await GetProvider();

                var userAccount = await WebAuthenticationCoreManager.FindAccountAsync(provider, (string)userID);

                if (userAccount != null)
                {
                    try
                    {
                        WebTokenRequest wtr = new WebTokenRequest(provider, _scope, _clientId);
                        if (resource != null)
                        {
                            wtr.Properties.Add("resource", resource);
                        }

                        var wtrr = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(wtr, userAccount);

                        SaveToken(wtrr, resource);

                        return(GetTokenFromResult(wtrr));
                    }
                    catch (Exception ex)
                    {
                        ServiceUtil.LogService.Write("SignInSilent: " + ex.Message, LoggingLevel.Error);
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Obtains a MSA OAuth token using WebAccountManager and tries to log the user in with it.
        /// </summary>
        private static async void MicrosoftAccountAuth(WebAccountProviderCommand command)
        {
            await ShowWait("Microsoft");

            WebTokenRequest       request = new WebTokenRequest(command.WebAccountProvider, "wl.basic,wl.emails");
            WebTokenRequestResult result  = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request);

            if (result.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
            {
                result = await WebAuthenticationCoreManager.RequestTokenAsync(request);
            }
            if (result.ResponseStatus == WebTokenRequestStatus.ProviderError)
            {
                ReportFail();
                return;
            }
            await LoginOrRegisterAsync(new ProviderInfo
            {
                Provider = ProviderType.Msa,
                Token    = result.ResponseData.FirstOrDefault()?.Token
            });
        }
        private async void button1clickAsync(object sender, RoutedEventArgs e)
        {
            string providerId = ApplicationData.Current.LocalSettings.Values["CurrentUserProviderId"]?.ToString();
            string accountId  = ApplicationData.Current.LocalSettings.Values["CurrentUserId"]?.ToString();

            if ((providerId != null) & (accountId != null))
            {
                WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(providerId);

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

                WebTokenRequest       request = new WebTokenRequest(provider, "wl.basic");
                WebTokenRequestResult result  = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request, account);

                ApplicationData.Current.LocalSettings.Values.Remove("CurrentUserProviderId");
                ApplicationData.Current.LocalSettings.Values.Remove("CurrentUserId");
                await account.SignOutAsync();

                var messageDialog = new MessageDialog("Logged out.");
                await messageDialog.ShowAsync();
            }
        }
        private async void GetAccessToken(object sender, RoutedEventArgs e)
        {
            string token    = null;
            string resource = "https://kamat777.sharepoint.com/";

            WebAccountProvider aadAccount = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.windows.net");

            // WebTokenRequest request = new WebTokenRequest(aadAccount, string.Empty, App.Current.Resources["ida:ClientId"].ToString(), WebTokenRequestPromptType.Default);
            WebTokenRequest request = new WebTokenRequest(aadAccount, string.Empty, "48d16164-a3b3-4ab1-b626-a5271858fdac", WebTokenRequestPromptType.Default);

            request.Properties.Add("authority", "https://login.windows.net");
            request.Properties.Add("resource", resource);

            var response = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request);

            if (response.ResponseStatus == WebTokenRequestStatus.Success)
            {
                WebTokenResponse webToken = response.ResponseData[0];
                token = webToken.Token;
            }
            else if (response.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
            {
                aadAccount = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.windows.net");

                request = new WebTokenRequest(aadAccount, string.Empty, "48d16164-a3b3-4ab1-b626-a5271858fdac", WebTokenRequestPromptType.ForceAuthentication);
                request.Properties.Add("authority", "https://login.windows.net");
                request.Properties.Add("resource", resource);

                response = await WebAuthenticationCoreManager.RequestTokenAsync(request);

                if (response.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    WebTokenResponse webToken = response.ResponseData[0];
                    token = webToken.Token;
                }
            }

            string tokenfound = token;
        }
Beispiel #30
0
        private async Task <bool> GetTokenSilentlyAsync(WebAccountProvider provider, String scope, String clientId)
        {
            bool result = false;

            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);

                    result = await ParseTokenResultAsync(webTokenRequestResult, false);

                    //Logger.Log(LogSeverity.Information, "Token received", result.ToString());
                }
                catch (Exception ex)
                {
                    //Logger.Log(LogSeverity.Information, "Lenovo ID App is not installed.", ex);
                    result = false;
                }
            }
            else
            {
                //await SetLIDProfileCache();
                //Logger.Log(LogSeverity.Information, "LenovoIdAgent: GetTokenSilentlyAsync - provider was null");
            }
            return(result);
        }