Beispiel #1
0
        private 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, App.Current.Resources["ida:ClientID"].ToString(), WebTokenRequestPromptType.Default);
            webTokenRequest.Properties.Add("authority", "https://login.windows.net");
            webTokenRequest.Properties.Add("resource", "https://outlook.office365.com/");
            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", "https://outlook.office365.com/");
                webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    token = webTokenResponse.Token;
                }
            }

            return token;
        }
Beispiel #2
0
        public async Task ATI_WithPicker_MsaPt_NoTransferToken_Async()
        {
            string homeAccId = $"{TestConstants.Uid}.{TestConstants.Utid}";

            // Arrange
            using (var harness = CreateTestHarness())
            {
                var requestParams = harness.CreateAuthenticationRequestParameters(
                    TestConstants.AuthorityHomeTenant);

                // msa-pt scenario
                requestParams.AppConfig.IsMsaPassthrough = true;
                var accountPicker = Substitute.For <IAccountPicker>();
                _accountPickerFactory.Create(Arg.Any <IntPtr>(), null, null, null, false).ReturnsForAnyArgs(accountPicker);
                var msaProvider = new WebAccountProvider("msa", "*****@*****.**", null);
                accountPicker.DetermineAccountInteractivelyAsync().Returns(Task.FromResult(msaProvider));
                // AAD plugin + consumer provider = Guest MSA-PT scenario
                _webAccountProviderFactory.IsConsumerProvider(msaProvider).Returns(true);
                _msaPassthroughHandler.TryFetchTransferTokenAsync(requestParams, msaProvider)
                .Returns(Task.FromResult <string>(null));

                var aadProvider = new WebAccountProvider("aad", "*****@*****.**", null);
                _webAccountProviderFactory.GetAccountProviderAsync("home").Returns(aadProvider);

                // make sure the final request is done with the AAD provider
                var webTokenRequest = new WebTokenRequest(aadProvider);
                _aadPlugin.CreateWebTokenRequestAsync(
                    aadProvider,
                    requestParams,
                    isForceLoginPrompt: true, // it is important to force prompt if a transfer token was not obtained
                    isInteractive: true,
                    isAccountInWam: false)
                .Returns(Task.FromResult(webTokenRequest));

                var webTokenResponseWrapper = Substitute.For <IWebTokenRequestResultWrapper>();
                webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success);
                var webTokenResponse = new WebTokenResponse();
                webTokenResponseWrapper.ResponseData.Returns(new List <WebTokenResponse>()
                {
                    webTokenResponse
                });

                _wamProxy.RequestTokenForWindowAsync(Arg.Any <IntPtr>(), webTokenRequest).
                Returns(Task.FromResult(webTokenResponseWrapper));
                _aadPlugin.ParseSuccessfullWamResponse(webTokenResponse, out _).Returns(_msalTokenResponse);

                var atiParams = new AcquireTokenInteractiveParameters();
                atiParams.Prompt = Prompt.SelectAccount;

                // Act
                var result = await _wamBroker.AcquireTokenInteractiveAsync(requestParams, atiParams)
                             .ConfigureAwait(false);

                // Assert
                Assert.AreSame(_msalTokenResponse, result);
                Assert.AreEqual("select_account", webTokenRequest.Properties["prompt"]);
                _msaPassthroughHandler.Received(1).AddTransferTokenToRequest(webTokenRequest, 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;
            }
        }
 internal static void AddMsalParamsToRequest(
     AuthenticationRequestParameters authenticationRequestParameters,
     WebTokenRequest webTokenRequest)
 {
     AddExtraParamsToRequest(webTokenRequest, authenticationRequestParameters.ExtraQueryParameters);
     AddAuthorityParamToRequest(authenticationRequestParameters, webTokenRequest);
     AddPOPParamsToRequest(webTokenRequest);
 }
Beispiel #5
0
        public async Task <WebTokenRequest> CreateWebTokenRequestAsync(
            WebAccountProvider provider,
            AuthenticationRequestParameters authenticationRequestParameters,
            bool isForceLoginPrompt,
            bool isInteractive,
            bool isAccountInWam)
        {
            bool setLoginHint  = false;
            bool addNewAccount = false;

            string loginHint = authenticationRequestParameters.LoginHint ?? authenticationRequestParameters.Account?.Username;

            if (isInteractive && !isAccountInWam)
            {
                if (!string.IsNullOrEmpty(loginHint))
                {
                    setLoginHint = true;
                }
                else
                {
                    addNewAccount = !(await _webAccountProviderFactory.IsDefaultAccountMsaAsync().ConfigureAwait(false));
                }
            }

            var promptType = (setLoginHint || addNewAccount || (isForceLoginPrompt && isInteractive)) ?
                             WebTokenRequestPromptType.ForceAuthentication :
                             WebTokenRequestPromptType.Default;

            string          scopes  = ScopeHelper.GetMsalScopes(authenticationRequestParameters.Scope).AsSingleString();
            WebTokenRequest request = new WebTokenRequest(
                provider,
                scopes,
                authenticationRequestParameters.AppConfig.ClientId,
                promptType);

            if (addNewAccount || setLoginHint)
            {
                request.Properties.Add("Client_uiflow", "new_account"); // launch add account flow

                if (setLoginHint)
                {
                    request.Properties.Add("LoginHint", loginHint); // prefill username
                }
            }

            AddV2Properties(request);

            if (ApiInformation.IsPropertyPresent("Windows.Security.Authentication.Web.Core.WebTokenRequest", "CorrelationId"))
            {
                request.CorrelationId = authenticationRequestParameters.CorrelationId.ToString();
            }
            else
            {
                _logger.Warning("[WAM MSA Plugin] Could not add the correlation ID to the request.");
            }

            return(request);
        }
Beispiel #6
0
        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);
            }
        }
Beispiel #7
0
        private async Task <IWebTokenRequestResultWrapper> AcquireInteractiveWithoutPickerAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            Prompt prompt,
            IWamPlugin wamPlugin,
            WebAccountProvider provider,
            WebAccount wamAccount)
        {
            bool isForceLoginPrompt = IsForceLoginPrompt(prompt);

            WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                provider,
                authenticationRequestParameters,
                isForceLoginPrompt : isForceLoginPrompt,
                isInteractive : true,
                isAccountInWam : true)
                                              .ConfigureAwait(false);

            if (isForceLoginPrompt &&
                ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 6))
            {
                // this feature works correctly since windows RS4, aka 1803 with the AAD plugin only!
                webTokenRequest.Properties["prompt"] = prompt.PromptValue;
            }

            AddCommonParamsToRequest(authenticationRequestParameters, webTokenRequest);

            try
            {
#if WINDOWS_APP
                // UWP requires being on the UI thread
                await _synchronizationContext;
#endif
                IWebTokenRequestResultWrapper wamResult;
                if (wamAccount != null)
                {
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest,
                        wamAccount).ConfigureAwait(false);
                }
                else
                {
                    // default user
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest).ConfigureAwait(false);
                }
                return(wamResult);
            }
            catch (Exception ex)
            {
                _logger.ErrorPii(ex);
                throw new MsalServiceException(
                          MsalError.WamInteractiveError,
                          "AcquireTokenInteractive without picker failed. See inner exception for details. ", ex);
            }
        }
Beispiel #8
0
        public async Task <MsalTokenResponse> AcquireTokenSilentAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            AcquireTokenSilentParameters acquireTokenSilentParameters)
        {
            using (_logger.LogMethodDuration())
            {
                // Important: MSAL will have already resolved the authority by now,
                // so we are not expecting "common" or "organizations" but a tenanted authority
                bool isMsa = IsMsaRequest(
                    authenticationRequestParameters.Authority,
                    null,
                    IsMsaPassthrough(authenticationRequestParameters));

                IWamPlugin wamPlugin = isMsa ? _msaPlugin : _aadPlugin;

                WebAccountProvider provider;
                if (isMsa)
                {
                    provider = await _webAccountProviderFactory.GetAccountProviderAsync("consumers").ConfigureAwait(false);
                }
                else
                {
                    provider = await _webAccountProviderFactory.GetAccountProviderAsync(authenticationRequestParameters.Authority.AuthorityInfo.CanonicalAuthority)
                               .ConfigureAwait(false);
                }

                WebAccount webAccount = await FindWamAccountForMsalAccountAsync(
                    provider,
                    wamPlugin,
                    authenticationRequestParameters.Account,
                    null, // ATS requires an account object, login_hint is not supported on its own
                    authenticationRequestParameters.ClientId).ConfigureAwait(false);

                if (webAccount == null)
                {
                    throw new MsalUiRequiredException(
                              MsalError.InteractionRequired,
                              "Could not find a WAM account for the silent request.");
                }

                WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                    provider,
                    authenticationRequestParameters,
                    isForceLoginPrompt : false,
                    isAccountInWam : true,
                    isInteractive : false)
                                                  .ConfigureAwait(false);

                AddCommonParamsToRequest(authenticationRequestParameters, webTokenRequest);

                var wamResult =
                    await _wamProxy.GetTokenSilentlyAsync(webAccount, webTokenRequest).ConfigureAwait(false);

                return(CreateMsalTokenResponse(wamResult, wamPlugin, isInteractive: false));
            }
        }
        public async Task ATS_AccountMatchingInWAM_MatchingHomeAccId_Async()
        {
            string homeAccId = $"{TestConstants.Uid}.{TestConstants.Utid}";

            // Arrange
            using (var harness = CreateTestHarness())
            {
                var wamAccountProvider = new WebAccountProvider("id", "*****@*****.**", null);
                var requestParams      = harness.CreateAuthenticationRequestParameters(TestConstants.AuthorityConsumerTidTenant); // MSA
                var webAccount         = new WebAccount(wamAccountProvider, "*****@*****.**", WebAccountState.Connected);
                IReadOnlyList <WebAccount> webAccounts = new List <WebAccount>()
                {
                    webAccount
                };
                var webTokenRequest         = new WebTokenRequest(wamAccountProvider);
                var webTokenResponseWrapper = Substitute.For <IWebTokenRequestResultWrapper>();
                webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success);
                var webTokenResponse = new WebTokenResponse();
                webTokenResponseWrapper.ResponseData.Returns(new List <WebTokenResponse>()
                {
                    webTokenResponse
                });

                _wamProxy.FindAllWebAccountsAsync(wamAccountProvider, TestConstants.ClientId).Returns(Task.FromResult(webAccounts));

                // WAM can give MSAL the home account ID of a Wam account, which MSAL matches to a WAM account
                _msaPlugin.GetHomeAccountIdOrNull(webAccount).Returns(homeAccId);

                _msaPlugin.CreateWebTokenRequestAsync(
                    wamAccountProvider,
                    requestParams,
                    isForceLoginPrompt: false,
                    isAccountInWam: true,
                    isInteractive: false)
                .Returns(Task.FromResult(webTokenRequest));

                requestParams.Account = new Account(
                    homeAccId,                   // matching in on home acc id
                    "*****@*****.**", // matching is not on UPN
                    null);                       // account does not have wam_id, might be coming directly from WAM

                var atsParams = new AcquireTokenSilentParameters();
                _webAccountProviderFactory.GetAccountProviderAsync(null).ReturnsForAnyArgs(Task.FromResult(wamAccountProvider));

                _wamProxy.GetTokenSilentlyAsync(webAccount, webTokenRequest).
                Returns(Task.FromResult(webTokenResponseWrapper));
                _msaPlugin.ParseSuccesfullWamResponse(webTokenResponse).Returns(_msalTokenResponse);


                // Act
                var result = await _wamBroker.AcquireTokenSilentAsync(requestParams, atsParams).ConfigureAwait(false);

                // Assert
                Assert.AreSame(_msalTokenResponse, result);
            }
        }
Beispiel #10
0
        public void TestWebAuthenticationCoreManager()
        {
            WebAccountProvider provider        = new WebAccountProvider("id", "name", null);
            WebTokenRequest    webTokenRequest = new WebTokenRequest(provider);

            Assert.Throws <ArgumentException>(() => WebAuthenticationCoreManagerInterop.RequestTokenForWindowAsync(new IntPtr(0), webTokenRequest));
            var webAccount = new WebAccount(provider, "user name", 0);

            Assert.Throws <ArgumentException>(() => WebAuthenticationCoreManagerInterop.RequestTokenWithWebAccountForWindowAsync(new IntPtr(0), webTokenRequest, webAccount));
        }
Beispiel #11
0
        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]);
            }
        }
Beispiel #12
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;
            }
        }
        public async Task ATI_WithPicker_Async()
        {
            string homeAccId = $"{TestConstants.Uid}.{TestConstants.Utid}";

            // Arrange
            using (var harness = CreateTestHarness())
            {
                var requestParams = harness.CreateAuthenticationRequestParameters(TestConstants.AuthorityHomeTenant); // AAD
                requestParams.Account = new Account(
                    $"{TestConstants.Uid}.{TestConstants.Utid}",
                    TestConstants.DisplayableId,
                    null,
                    new Dictionary <string, string>()
                {
                    { TestConstants.ClientId, "wam_id_1" }
                });                                                                              // account has wam_id!

                var accountPicker = Substitute.For <IAccountPicker>();

                _accountPickerFactory.Create(Arg.Any <IntPtr>(), null, null, null, false).ReturnsForAnyArgs(accountPicker);

                var wamAccountProvider = new WebAccountProvider("id", "*****@*****.**", null);
                accountPicker.DetermineAccountInteractivelyAsync().Returns(Task.FromResult(wamAccountProvider));

                var webTokenRequest = new WebTokenRequest(wamAccountProvider);
                _aadPlugin.CreateWebTokenRequestAsync(
                    wamAccountProvider,
                    requestParams,
                    isForceLoginPrompt: true,
                    isInteractive: true,
                    isAccountInWam: false)
                .Returns(Task.FromResult(webTokenRequest));

                var webTokenResponseWrapper = Substitute.For <IWebTokenRequestResultWrapper>();
                webTokenResponseWrapper.ResponseStatus.Returns(WebTokenRequestStatus.Success);
                var webTokenResponse = new WebTokenResponse();
                webTokenResponseWrapper.ResponseData.Returns(new List <WebTokenResponse>()
                {
                    webTokenResponse
                });

                _wamProxy.RequestTokenForWindowAsync(Arg.Any <IntPtr>(), webTokenRequest).
                Returns(Task.FromResult(webTokenResponseWrapper));
                _aadPlugin.ParseSuccesfullWamResponse(webTokenResponse).Returns(_msalTokenResponse);

                var atiParams = new AcquireTokenInteractiveParameters();

                // Act
                var result = await _wamBroker.AcquireTokenInteractiveAsync(requestParams, atiParams)
                             .ConfigureAwait(false);

                // Assert
                Assert.AreSame(_msalTokenResponse, result);
            }
        }
Beispiel #14
0
        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;
                }
            });
        }
Beispiel #15
0
        public Task <WebTokenRequest> CreateWebTokenRequestAsync(WebAccountProvider provider, string clientId, string scopes)
        {
            WebTokenRequest request = new WebTokenRequest(
                provider,
                scopes,
                clientId);

            request.Properties.Add("wam_compat", "2.0");

            return(Task.FromResult(request));
        }
        internal static void AddMsalParamsToRequest(
            AuthenticationRequestParameters authenticationRequestParameters,
            WebTokenRequest webTokenRequest,
            string overridentAuthority = null)
        {
            AddExtraParamsToRequest(webTokenRequest, authenticationRequestParameters.ExtraQueryParameters);
            string authority = overridentAuthority ??
                               authenticationRequestParameters.UserConfiguredAuthority.AuthorityInfo.CanonicalAuthority;
            bool validate = authenticationRequestParameters.AuthorityInfo.ValidateAuthority;

            AddAuthorityParamToRequest(authority, validate, webTokenRequest);;
        }
Beispiel #17
0
        private async Task <IWebTokenRequestResultWrapper> AcquireInteractiveWithWamAccountAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            Prompt msalPrompt,
            IWamPlugin wamPlugin,
            WebAccountProvider provider,
            WebAccount wamAccount)
        {
            WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                provider,
                authenticationRequestParameters,
                isForceLoginPrompt : false,
                isInteractive : true,
                isAccountInWam : true)
                                              .ConfigureAwait(false);

            // because of https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/2476
            string differentAuthority = null;

            if (string.Equals(wamAccount?.WebAccountProvider?.Authority, Constants.OrganizationsTenant) &&
                string.Equals(authenticationRequestParameters.Authority.TenantId, Constants.OrganizationsTenant))
            {
                differentAuthority = authenticationRequestParameters.Authority.GetTenantedAuthority("common");
            }

            WamAdapters.AddMsalParamsToRequest(authenticationRequestParameters, webTokenRequest, differentAuthority);

            try
            {
                IWebTokenRequestResultWrapper wamResult;
                if (wamAccount != null)
                {
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest,
                        wamAccount).ConfigureAwait(false);
                }
                else
                {
                    // default user
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest).ConfigureAwait(false);
                }
                return(wamResult);
            }
            catch (Exception ex)
            {
                _logger.ErrorPii(ex);
                throw new MsalServiceException(
                          MsalError.WamInteractiveError,
                          "AcquireTokenInteractive without picker failed. See inner exception for details. ", ex);
            }
        }
Beispiel #18
0
        public Task <WebTokenRequest> CreateWebTokenRequestAsync(WebAccountProvider provider, string clientId, string scopes)
        {
            WebTokenRequest request = new WebTokenRequest(
                provider,
                scopes,
                clientId,
                WebTokenRequestPromptType.Default);

            AddV2Properties(request);

            return(Task.FromResult(request));
        }
Beispiel #19
0
        private static void AddTelemetryPropertiesToRequest(WebTokenRequest request, ICoreLogger logger)
        {
            if (s_telemetryHeaders == null)
            {
                s_telemetryHeaders = MsalIdHelper.GetMsalIdParameters(logger);
            }

            foreach (var kvp in s_telemetryHeaders)
            {
                request.Properties.Add(kvp);
            }
        }
        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));
        }
Beispiel #21
0
        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();
            }
        }
Beispiel #22
0
        private async Task <TokenAndSignatureResult> InternalGetTokenAndSignatureHelperAsync(string httpMethod, string url, string headers, byte[] body, bool promptForCredentialsIfNeeded, bool forceRefresh)
        {
            if (this.provider == null)
            {
                throw new Exception("Xbox Live identity provider is not initialized");
            }

            var request = new WebTokenRequest(this.provider);

            request.Properties.Add("HttpMethod", httpMethod);
            request.Properties.Add("Url", url);
            if (!string.IsNullOrEmpty(headers))
            {
                request.Properties.Add("RequestHeaders", headers);
            }
            if (forceRefresh)
            {
                request.Properties.Add("ForceRefresh", "true");
            }

            if (body != null && body.Length > 0)
            {
                request.Properties.Add("RequestBody", Encoding.UTF8.GetString(body));
            }

            request.Properties.Add("Target", this.AuthConfig.RPSTicketService);
            request.Properties.Add("Policy", this.AuthConfig.RPSTicketPolicy);
            if (promptForCredentialsIfNeeded)
            {
                string pfn = Windows.ApplicationModel.Package.Current.Id.FamilyName;
                request.Properties.Add("PackageFamilyName", pfn);
            }

            TokenAndSignatureResult tokenAndSignatureReturnResult = null;
            var tokenResult = await RequestTokenFromIdpAsync(promptForCredentialsIfNeeded, request);

            try
            {
                tokenAndSignatureReturnResult = this.ConvertWebTokenRequestResult(tokenResult);
                if (tokenAndSignatureReturnResult != null && this.IsSignedIn && tokenAndSignatureReturnResult.XboxUserId != this.XboxUserId)
                {
                    this.UserSignedOut();
                    throw new Exception("User has switched"); // todo: auth_user_switched
                }
            }
            catch (Exception)
            {
                // log
            }

            return(tokenAndSignatureReturnResult);
        }
Beispiel #23
0
        public async Task <MsalTokenResponse> AcquireTokenSilentDefaultUserAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            AcquireTokenSilentParameters acquireTokenSilentParameters)
        {
            using (_logger.LogMethodDuration())
            {
                var defaultAccountProvider = await _webAccountProviderFactory.GetDefaultProviderAsync().ConfigureAwait(false);

                if (defaultAccountProvider == null)
                {
                    throw new MsalUiRequiredException(
                              MsalError.InteractionRequired,
                              "A default account was not found");
                }
                // special case: passthrough + default MSA account. Need to use the transfer token protocol.
                if (_wamOptions.MsaPassthrough &&
                    _webAccountProviderFactory.IsConsumerProvider(defaultAccountProvider))
                {
                    return(await AcquireTokenSilentDefaultUserPassthroughAsync(authenticationRequestParameters, defaultAccountProvider).ConfigureAwait(false));
                }

                bool isMsa = await IsMsaRequestAsync(
                    authenticationRequestParameters.Authority,
                    null,
                    _wamOptions.MsaPassthrough).ConfigureAwait(false);

                IWamPlugin         wamPlugin = isMsa ? _msaPlugin : _aadPlugin;
                WebAccountProvider provider  = await GetProviderAsync(
                    authenticationRequestParameters.Authority.AuthorityInfo.CanonicalAuthority,
                    isMsa).ConfigureAwait(false);

                WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                    provider,
                    authenticationRequestParameters,
                    isForceLoginPrompt : false,
                    isAccountInWam : false,
                    isInteractive : false)
                                                  .ConfigureAwait(false);

                WamAdapters.AddMsalParamsToRequest(authenticationRequestParameters, webTokenRequest, _logger);

                var wamResult =
                    await _wamProxy.GetTokenSilentlyForDefaultAccountAsync(webTokenRequest).ConfigureAwait(false);

                return(WamAdapters.CreateMsalResponseFromWamResponse(
                           wamResult,
                           wamPlugin,
                           authenticationRequestParameters.AppConfig.ClientId,
                           _logger,
                           isInteractive: false));
            }
        }
Beispiel #24
0
        private async Task <WebTokenRequestResult> SignInAsync(string resource)
        {
            var taskCompletionSource = new TaskCompletionSource <WebTokenRequestResult>();

            TypedEventHandler <AccountsSettingsPane, AccountsSettingsPaneCommandsRequestedEventArgs> AccountCommandsRequestedHandler = null;

            AccountCommandsRequestedHandler = async(s, e) =>
            {
                Debug.WriteLine("AccountCommandsRequestedHandler");

                AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= AccountCommandsRequestedHandler;

                // In order to make async calls within this callback, the deferral object is needed
                AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();
                if (deferral != null)
                {
                    // The Microsoft account provider is always present in Windows 10 devices, even IoT Core, as is the Azure AD plugin.
                    var providerCommand = new WebAccountProviderCommand(await GetProvider(), async(command) =>
                    {
                        Debug.WriteLine("WebAccountProviderCommandInvokedHandler");

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

                            var wtrr = await RequestTokenWithTimeout(wtr);
                            SaveToken(wtrr, resource);

                            taskCompletionSource.SetResult(wtrr);
                        }
                        catch (Exception ex)
                        {
                            ServiceUtil.LogService.Write("Web Token Request Error: " + ex.Message, LoggingLevel.Error);
                            taskCompletionSource.SetResult(null);
                        }
                    });

                    e.WebAccountProviderCommands.Add(providerCommand);

                    deferral.Complete();
                }
            };

            AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += AccountCommandsRequestedHandler;
            await AccountsSettingsPane.ShowAddAccountAsync();

            return(await taskCompletionSource.Task);
        }
Beispiel #25
0
        public void AddTransferTokenToRequest()
        {
            // Arrange
            const string    TransferToken = "transfer_token";
            var             provider      = new WebAccountProvider("id", "*****@*****.**", null);
            WebTokenRequest request       = new WebTokenRequest(provider, "scope", "client_id");

            // Act
            _msaPassthroughHandler.AddTransferTokenToRequest(request, TransferToken);

            // Assert
            Assert.AreEqual(TransferToken, request.Properties["SamlAssertion"]);
            Assert.AreEqual("SAMLV1", request.Properties["SamlAssertionType"]);
        }
Beispiel #26
0
        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);
        }
        public Task <WebTokenRequest> CreateWebTokenRequestAsync(
            WebAccountProvider provider,
            AuthenticationRequestParameters authenticationRequestParameters,
            bool isForceLoginPrompt,
            bool isInteractive,
            bool isAccountInWam,
            string scopeOverride = null)
        {
            string loginHint = !string.IsNullOrEmpty(authenticationRequestParameters.LoginHint) ?
                               authenticationRequestParameters.LoginHint :
                               authenticationRequestParameters.Account?.Username;

            bool setLoginHint =
                isInteractive &&
                !isAccountInWam &&
                !string.IsNullOrEmpty(loginHint);

            var wamPrompt = setLoginHint || (isInteractive && isForceLoginPrompt) ?
                            WebTokenRequestPromptType.ForceAuthentication :
                            WebTokenRequestPromptType.Default;

            WebTokenRequest request = new WebTokenRequest(
                provider,
                scopeOverride ?? ScopeHelper.GetMsalScopes(authenticationRequestParameters.Scope).AsSingleString(),
                authenticationRequestParameters.AppConfig.ClientId,
                wamPrompt);

            if (setLoginHint)
            {
                request.Properties.Add("LoginHint", authenticationRequestParameters.LoginHint);
            }

            request.Properties.Add("wam_compat", "2.0");
            if (ApiInformation.IsPropertyPresent("Windows.Security.Authentication.Web.Core.WebTokenRequest", "CorrelationId"))
            {
                LegacyOsWamProxy.SetCorrelationId(request, authenticationRequestParameters.CorrelationId.ToString());
            }
            else
            {
                request.Properties.Add("correlationId", authenticationRequestParameters.CorrelationId.ToString());
            }

            if (!string.IsNullOrEmpty(authenticationRequestParameters.ClaimsAndClientCapabilities))
            {
                request.Properties.Add("claims", authenticationRequestParameters.ClaimsAndClientCapabilities);
            }

            return(Task.FromResult(request));
        }
        /// <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 #29
0
        internal static void AddMsalParamsToRequest(
            AuthenticationRequestParameters authenticationRequestParameters,
            WebTokenRequest webTokenRequest,
            ICoreLogger logger,
            string overridenAuthority = null)
        {
            AddExtraParamsToRequest(webTokenRequest, authenticationRequestParameters.ExtraQueryParameters);
            string authority = overridenAuthority ??
                               authenticationRequestParameters.AuthorityManager.OriginalAuthority.AuthorityInfo.CanonicalAuthority;
            bool validate = authenticationRequestParameters.AuthorityInfo.ValidateAuthority;

            AddAuthorityParamToRequest(authority, validate, webTokenRequest);

            AddTelemetryPropertiesToRequest(webTokenRequest, logger);
        }
        private async Task <IWebTokenRequestResultWrapper> AcquireInteractiveWithoutPickerAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            Prompt msalPrompt,
            IWamPlugin wamPlugin,
            WebAccountProvider provider,
            WebAccount wamAccount)
        {
            bool isForceLoginPrompt = IsForceLoginPrompt(msalPrompt);

            WebTokenRequest webTokenRequest = await wamPlugin.CreateWebTokenRequestAsync(
                provider,
                authenticationRequestParameters,
                isForceLoginPrompt : isForceLoginPrompt,
                isInteractive : true,
                isAccountInWam : true)
                                              .ConfigureAwait(false);

            AddPromptToRequest(msalPrompt, isForceLoginPrompt, webTokenRequest);

            WamAdapters.AddMsalParamsToRequest(authenticationRequestParameters, webTokenRequest);

            try
            {
                IWebTokenRequestResultWrapper wamResult;
                if (wamAccount != null)
                {
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest,
                        wamAccount).ConfigureAwait(false);
                }
                else
                {
                    // default user
                    wamResult = await _wamProxy.RequestTokenForWindowAsync(
                        _parentHandle,
                        webTokenRequest).ConfigureAwait(false);
                }
                return(wamResult);
            }
            catch (Exception ex)
            {
                _logger.ErrorPii(ex);
                throw new MsalServiceException(
                          MsalError.WamInteractiveError,
                          "AcquireTokenInteractive without picker failed. See inner exception for details. ", ex);
            }
        }
Beispiel #31
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);
        }
Beispiel #32
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>
        /// 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;
        }
		private async void MainPage_OnLoaded(object sender, RoutedEventArgs e)
		{
			//var redirect = GetAppRedirectURI();

			try
			{
				WebAccountProvider wap =
						await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", _authority);

				WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, _clientId);
				wtr.Properties.Add("resource", _resource);
				WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);

				if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
					_accessToken = wtrr.ResponseData[0].Token;
			}
			catch (Exception ex)
			{
				ShowException(ex);
			}
		}
        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;
        }    
        // Get an access token for the given context and resourceId. An attempt is first made to 
        // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
        public static async Task<string> GetTokenHelperAsync(WebAccountProvider accountProvider, string resourceId)
        {
            string token = null;
            WebAccountProvider aadAccountProvider;

            if (accountProvider != null)
            {
                aadAccountProvider = accountProvider;
            }
            else
            {
                aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                    AccountProviderId, Authority);

            }

            // Check if there's a record of the last account used with the app.
            var userID = settings.Values["userID"];

            WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId);
            webTokenRequest.Properties.Add("resource", resourceId);

            WebTokenRequestResult webTokenRequestResult;
            if (userID != null)
            {
                // Get an account object for the user.
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(aadAccountProvider, (string)userID);

                // Ensure that the saved account works for getting the token we need.
                webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, userAccount);
            }
            else
            {
                webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
            }

            if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch)
            {
                WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                userAccount = webTokenResponse.WebAccount;
                token = webTokenResponse.Token;

                // We succeeded in getting a valid user.
                if (userAccount != null)
                {
                    // Save user ID in local storage.
                    settings.Values["userID"] = userAccount.Id;
                    settings.Values["userEmail"] = userAccount.UserName;
                    settings.Values["userName"] = userAccount.Properties["DisplayName"];
                }

                return token;
            }
            else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
            {
                webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
                webTokenRequest.Properties.Add("resource", resourceId);

                //get token through prompt
                if (userID != null)
                {
                    // Ensure that the saved account works for getting the token we need.
                    webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount);
                }
                else
                {
                    webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                }

                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    userAccount = webTokenResponse.WebAccount;
                    currentToken = webTokenResponse.Token;

                    if (userAccount != null)
                    {
                        // Save user ID in local storage.
                        settings.Values["userID"] = userAccount.Id;
                        settings.Values["userEmail"] = userAccount.UserName;
                        settings.Values["userName"] = userAccount.Properties["DisplayName"];
                    }
                    return token;
                }
                else
                {
                    // The saved account could not be used for getting a token.
                    // Make sure that the UX is ready for a new sign in.
                    await SignOutAsync();
                    return null;

                }
            }
            else
            {
                // The saved account could not be used for getting a token.
                // Make sure that the UX is ready for a new sign in.
                await SignOutAsync();
                return null;
            }

        }
        // Get an access token for the given context and resourceId. An attempt is first made to 
        // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
        public static async Task<string> GetTokenHelperAsync()
        {

            string token = null;

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

            // Check if there's a record of the last account used with the app.
            var userID = _settings.Values["userID"];

            if (userID != null)
            {

                WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId);
                webTokenRequest.Properties.Add("resource", ResourceUrl);

                // Get an account object for the user.
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(aadAccountProvider, (string)userID);


                // Ensure that the saved account works for getting the token we need.
                WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount);
                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    userAccount = webTokenResponse.WebAccount;
                    token = webTokenResponse.Token;

                }
                else
                {
                    // The saved account could not be used for getting a token.
                    // Make sure that the UX is ready for a new sign in.
                    SignOut();
                }

            }
            else
            {
                // There is no recorded user. Start a sign-in flow without imposing a specific account.

                WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
                webTokenRequest.Properties.Add("resource", ResourceUrl);

                WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    userAccount = webTokenResponse.WebAccount;
                    token = webTokenResponse.Token;

                }
            }

            // We succeeded in getting a valid user.
            if (userAccount != null)
            {
                // Save user ID in local storage.
                _settings.Values["userID"] = userAccount.Id;
                _settings.Values["userEmail"] = userAccount.UserName;
                _settings.Values["userName"] = userAccount.Properties["DisplayName"];

                return token;
            }

            // We didn't succeed in getting a valid user. Clear the app settings so that another user can sign in.
            else
            {

                SignOut();
                return null;
            }


        }
        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 static async Task<string> TryAuthenticateSilentlyAsync()
        {
            try
            {

                var redir = GetAppRedirectURI();

                var aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(
                     AccountProviderId, Authority);

                // Check if there's a record of the last account used with the app.
                var userID = settings.Values["userID"];

                WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId);
                webTokenRequest.Properties.Add("resource", GraphResourceId);

                WebTokenRequestResult webTokenRequestResult;
                if (userID != null)
                {
                    // Get an account object for the user.
                    userAccount = await WebAuthenticationCoreManager.FindAccountAsync(
                        aadAccountProvider, (string)userID);

                    // Ensure that the saved account works for getting the token we need.
                    webTokenRequestResult =
                            await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, userAccount);
                }
                else
                {
                    webTokenRequestResult =
                            await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);
                }


                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success
                    || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch)
                {
                    WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                    userAccount = webTokenResponse.WebAccount;
                    currentToken = webTokenResponse.Token;

                    if (userAccount != null)
                    {
                        // Save user ID in local storage.
                        settings.Values["userID"] = userAccount.Id;
                        settings.Values["userEmail"] = userAccount.UserName;
                        settings.Values["userName"] = userAccount.Properties["DisplayName"];
                    }
                    return currentToken;

                }
                else 

                // Dont want to log during launch !!
                //if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
                //{
                //    webTokenRequest = new WebTokenRequest(aadAccountProvider, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
                //    webTokenRequest.Properties.Add("resource", GraphResourceId);

                //    //get token through prompt
                //    if (userID != null)
                //    {
                //        // Ensure that the saved account works for getting the token we need.
                //        webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount);
                //    }
                //    else
                //    {
                //        webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
                //    }

                //    if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                //    {
                //        WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
                //        userAccount = webTokenResponse.WebAccount;
                //        currentToken = webTokenResponse.Token;

                //        if (userAccount != null)
                //        {
                //            // Save user ID in local storage.
                //            settings.Values["userID"] = userAccount.Id;
                //            settings.Values["userEmail"] = userAccount.UserName;
                //            settings.Values["userName"] = userAccount.Properties["DisplayName"];
                //        }
                //        return true;
                //    }
                //    else
                //    {
                //        // The saved account could not be used for getting a token.
                //        // Make sure that the UX is ready for a new sign in.
                //        await SignOutAsync();
                //        return false;

                //    }
                //}
                {
                    // The saved account could not be used for getting a token.
                    // Make sure that the UX is ready for a new sign in.
                    await SignOutAsync();
                    return null;
                }
            }
            catch (Exception)
            {
                await SignOutAsync();
                return null;
            }


        }
        private async void OnLoaded(object sender, RoutedEventArgs e)
        {
            try
            {
#if ADAL
                // Ok, to use async () here as ctor takes a Func<Task<string>>
                _client =
                    new ActiveDirectoryClient(new Uri($"{Resource}/{tenant}"),
                        async () =>
                        {
                            var auth = await GetAuthAsync();
                            return auth.AccessToken;
                        });
#else
                ViewModel.IsBusy = true;

                _client =
                    new ActiveDirectoryClient(new Uri($"{Resource}/{tenant}"),
                        () =>
                        {
                            var tcs = new TaskCompletionSource<string>();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                            Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                            {
                                try
                                {                                 // replace 'organizations' with 'consumers' to use MSA
                                    string authority = $"https://login.microsoftonline.com/{tenant}";
                                    //string authority = "organizations";
                                    var wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com",
                                        authority);

                                    WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, ClientId);
                                    wtr.Properties.Add("resource", Resource);

                                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);

                                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                                        tcs.SetResult(wtrr.ResponseData[0].Token);
                                }
                                catch (Exception ex)
                                {
                                    tcs.SetException(ex);
                                }
                                finally
                                {
                                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                        () =>
                                        {
                                            ViewModel.IsBusy = false;
                                        });
                                }
                            });

                            return tcs.Task;
                        });

#endif
                // put first page into obs collection for now...
                var users = await _client.Users.ExecuteAsync();
                ViewModel.Users = new ObservableCollection<IUser>(users.CurrentPage);
            }
            catch (Exception ex)
            {
                MessageDialog mg = new MessageDialog(ex.Message);
                await mg.ShowAsync();
            }
        }
        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);
            }
        }
        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);
            }
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority);
            appSettings = ApplicationData.Current.RoamingSettings;                               
            WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, clientId);
            wtr.Properties.Add("resource", resource);
            
            // Check if there's a record of the last account used with the app
            var userID = appSettings.Values["userID"];
            if (userID != null)
            {
                // Get an account object for the user
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(wap, (string)userID);
                if (userAccount != null)
                {
                    // Ensure that the saved account works for getting the token we need
                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, userAccount);
                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {                        
                        userAccount = wtrr.ResponseData[0].WebAccount;
                    }
                    else
                    {                        
                        // The saved account could not be used for getitng a token
                        MessageDialog messageDialog = new MessageDialog("We tried to sign you in with the last account you used with this app, but it didn't work out. Please sign in as a different user.");
                        await messageDialog.ShowAsync();
                        // Make sure that the UX is ready for a new sign in
                        UpdateUXonSignOut();
                    }
                }
                else
                {
                    // The WebAccount object is no longer available. Let's attempt a sign in with the saved username
                    wtr.Properties.Add("LoginHint", appSettings.Values["login_hint"].ToString());
                    WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                    if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                    {                        
                        userAccount = wtrr.ResponseData[0].WebAccount;
                    }
                }
            }
            else
            {  
                // There is no recorded user. Let's start a sign in flow without imposing a specific account.                             
                WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    userAccount = wtrr.ResponseData[0].WebAccount;
                }
            }

            if (userAccount != null) // we succeeded in obtaining a valid user
            {
                // save user ID in local storage
                UpdateUXonSignIn();
            }
            else
            {
                // nothing we tried worked. Ensure that the UX reflects that there is no user currently signed in.
                UpdateUXonSignOut();
                MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again.");
                await messageDialog.ShowAsync();                
            }
        }
 // Change the currently signed in user
 private async void btnSignInOut_Click(object sender, RoutedEventArgs e)
 {
     // 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
     WebTokenRequest wtr = new WebTokenRequest(wap, string.Empty, clientId, WebTokenRequestPromptType.ForceAuthentication);
     wtr.Properties.Add("resource", resource);
     WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
     if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)
     {
         userAccount = wtrr.ResponseData[0].WebAccount;
         UpdateUXonSignIn();
     }
     else
     {
         UpdateUXonSignOut();
         MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again.");
         await messageDialog.ShowAsync();
     }
 }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", authority);
            appSettings = ApplicationData.Current.RoamingSettings;
            WebTokenRequest wtr = new WebTokenRequest(wap, String.Empty, clientId);
            wtr.Properties.Add("resource", resource);

            var userID = appSettings.Values["userID"];
            if(userID != null)
            {
                userAccount = await WebAuthenticationCoreManager.FindAccountAsync(wap, (string)userID);
                if(userAccount != null)
                {
                    //Use saved account to get token
                    WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr, userAccount);
                    if (wtrResult.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        userAccount = wtrResult.ResponseData[0].WebAccount;
                    }
                    else
                    {
                        MessageDialog messageDialog =
                            new MessageDialog("We tried to sign you in with the last account you used with this app," +
                                "but it didn't work out. Please sign in as a different user.");
                        await messageDialog.ShowAsync();
                        UpdateUXonSignOut();
                    }

                }
                else
                {
                    // the WebAccount Object is no longer available
                    wtr.Properties.Add("LoginHint", appSettings.Values["login_hint"].ToString());
                    WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                    if (wtrResult.ResponseStatus == WebTokenRequestStatus.Success)
                    {
                        userAccount = wtrResult.ResponseData[0].WebAccount;
                    }

                }
               
            }
            else
            {
                //there is no recorded user so start sign-flow from start
                WebTokenRequestResult wtrResult = await WebAuthenticationCoreManager.RequestTokenAsync(wtr);
                if(wtrResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    userAccount = wtrResult.ResponseData[0].WebAccount;
                }
               
            }
            if(userAccount != null)
            {
                UpdateUXonSignIn();
            }
            else
            {
                //it totally failed
                UpdateUXonSignOut();
                MessageDialog messageDialog = new MessageDialog("We could not sign you in. Please try again.");
                await messageDialog.ShowAsync();
            }

        }
        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 #47
0
        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);
            }
        }
        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);
            }
        }
 // 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 void CallApiButton_Click(object sender, RoutedEventArgs e)
        {
            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)
            {
                this.accessToken = wtrr.ResponseData[0].Token;

               // HttpClient client = new HttpClient();
               // client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", accessToken);

               // HttpResponseMessage response = await client.GetAsync(new Uri("https://api.powerbi.com/beta/myorg/reports"));
               // response.EnsureSuccessStatusCode();
               //string data = await response.Content.ReadAsStringAsync();
               // dataTextBlock.Text = data;
               // textSignedIn.Text = accessToken;
                //List<string> args = new List<string>();
                //args.Add(@"{ action: 'loadReport', accessToken: '" + this.accessToken + "'}");
                //args.Add(@"*");

               // var test = await this.MyWebView.InvokeScriptAsync("postMessage", args.ToArray<string>());
              //  dataTextBlock.Text = test.ToString();
            }

        }
        public async Task AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID)
        {
            try
            {
                WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID);

                // If the user selected a specific account, RequestTokenAsync will return a token for that account.
                // The user may be prompted for credentials or to authorize using that account with your app
                // If the user selected a provider, the user will be prompted for credentials to login to a new account
                WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);

                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    StoreNewAccountDataLocally(webTokenRequestResult.ResponseData[0].WebAccount);
                }

                OutputTokenResult(webTokenRequestResult);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage);
            }
        }
        private async void OnWebAccountProviderRequested(WebAccountProviderCommand cmd)
        {
            // Retrieve the provider info instance for the requestd provider
            var pi = Platform.Current.WebAccountManager.GetProviderInfo(cmd.WebAccountProvider.Id);
            if (pi == null)
                throw new ArgumentNullException(nameof(pi));

            try
            {
                WebTokenRequest request = new WebTokenRequest(cmd.WebAccountProvider, pi.Scope, pi.ClientID);

                // Add any properties for this request from the provider info
                if (pi.RequestProperties != null)
                    foreach (var prop in pi.RequestProperties)
                        request.Properties.Add(prop);

                // 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 result = await WebAuthenticationCoreManager.RequestTokenAsync(request);

                if (result.ResponseStatus == WebTokenRequestStatus.Success)
                {
                    var webTokenResponse = result.ResponseData[0];
                    var webAccount = webTokenResponse.WebAccount;

                    // Wrapper the web account data
                    WebAccountInfo wi = new WebAccountInfo();
                    wi.Type = pi.WebAccountType;
                    wi.ProviderID = webAccount.WebAccountProvider.Id;
                    wi.AccountID = !string.IsNullOrEmpty(webAccount.Id) ? webAccount.Id : webAccount.UserName;
                    wi.Authority = webAccount.WebAccountProvider.Authority != null ? webAccount.WebAccountProvider.Authority : "";
                    wi.Token = webTokenResponse.Token;
                    this.SaveWebAccountInfo(wi);

                    Platform.Current.Logger.Log(LogLevels.Information, string.Format("Web Token request successful for AccountID: {0}", wi.AccountID));

                    // Success Callback
                    _successHandler(pi, wi, result);
                }
                else
                {
                    Platform.Current.Logger.Log(LogLevels.Information, "Web Token request error: " + result.ResponseStatus + " Code: " + result.ResponseError.ErrorMessage);

                    // Failed Callback
                    _failedHandler(pi, result);
                }

            }
            catch (Exception ex)
            {
                Platform.Current.Logger.LogError(ex, "Web Token request failed");
                _failedHandler(pi, null);
            }
            finally
            {
                this.Cleanup();
            }
        }
 private async void MyWebView_Loaded(object sender, RoutedEventArgs e)
 {
     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)
     {
         this.accessToken = wtrr.ResponseData[0].Token;
         List<string> args = new List<string>();
         args.Add(this.accessToken);
         var test = await MyWebView.InvokeScriptAsync("updateIframe", args.ToArray<string>());
     }
     
 }