コード例 #1
0
        public async Task <string> GetAccessToken()
        {
            _userAccount = await _msalClient.GetAccountAsync(_username);

            // If there is no saved user account, the user must sign-in
            if (_userAccount == null)
            {
                try
                {
                    // Invoke device code flow so user can sign-in with a browser
                    var result = await _msalClient.AcquireTokenByUsernamePassword(_scopes, _username, _password)
                                 .ExecuteAsync();

                    _userAccount = result.Account;
                    return(result.AccessToken);
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"Error getting access token: {exception.Message}");
                    return(result.AccessToken);
                }
            }
            else
            {
                // If there is an account, call AcquireTokenSilent
                // By doing this, MSAL will refresh the token automatically if
                // it is expired. Otherwise it returns the cached token.

                var result = await _msalClient
                             .AcquireTokenSilent(_scopes, _userAccount)
                             .ExecuteAsync();

                return(result.AccessToken);
            }
        }
コード例 #2
0
ファイル: Global.cs プロジェクト: wellbha/Office365APIEditor
        private static async Task <AuthenticationResult> InternalGetAccessTokenAsync()
        {
            // Acquire access token.

            AuthenticationResult result;

            try
            {
                var user = await pca.GetAccountAsync(currentUser.HomeAccountId.Identifier);

                result = await pca.AcquireTokenSilent(Util.MailboxViewerScopes(), user).ExecuteAsync();
            }
            catch (Exception)
            {
                try
                {
                    result = await pca.AcquireTokenInteractive(Util.MailboxViewerScopes()).WithAccount(currentUser).WithPrompt(Prompt.ForceLogin).ExecuteAsync();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return(result);
        }
コード例 #3
0
ファイル: OneDrive2FileStorage.cs プロジェクト: 77rusa/README
        private async Task <string> TryLoginSilent(string iocPath)
        {
            IAccount account = null;

            try
            {
                if (IsConnected(iocPath))
                {
                    return(iocPath);
                }
                String userId = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(iocPath).User?.Id;

                logDebug("needs acquire token");
                logDebug("trying silent login " + iocPath);

                account = Task.Run(async() => await _publicClientApp.GetAccountAsync(userId)).Result;
                logDebug("getting user ok.");
            }
            catch (Exception e)
            {
                logDebug(e.ToString());
            }
            if (account != null)
            {
                try
                {
                    logDebug("AcquireTokenSilent...");
                    AuthenticationResult authResult = await _publicClientApp.AcquireTokenSilent(Scopes, account)
                                                      .ExecuteAsync();

                    logDebug("AcquireTokenSilent ok.");
                    BuildClient(authResult);

                    /*User me = await graphClient.Me.Request().WithForceRefresh(true).GetAsync();
                     * logDebug("received name " + me.DisplayName);*/

                    return(BuildRootPathForUser(authResult));
                }
                catch (MsalUiRequiredException ex)
                {
                    GraphServiceClientWithState clientWithState = new GraphServiceClientWithState()
                    {
                        Client = null,
                        RequiresUserInteraction = true
                    };


                    mClientByUser[account.HomeAccountId.Identifier] = clientWithState;
                    logDebug("ui required");
                    return(null);
                }
                catch (Exception ex)
                {
                    logDebug("silent login failed: " + ex.ToString());
                    return(null);
                }
            }
            return(null);
        }
コード例 #4
0
    private async Task <AuthResult> AcquireTokenAsync(IPublicClientApplication app,
                                                      IEnumerable <string> scopes,
                                                      string usrId)
    {
        var acct = !string.IsNullOrEmpty(usrId) ? await app.GetAccountAsync(usrId) : null;

        var userStr = acct != null ? acct.Username : "******";

        Debug.Log($"Found User {userStr}");
        AuthResult res = new AuthResult();

        try
        {
            Debug.Log($"Calling AcquireTokenSilentAsync");
            res.res = await app.AcquireTokenSilentAsync(scopes, acct).ConfigureAwait(false);

            Debug.Log($"app.AcquireTokenSilentAsync called {res.res}");
        }
        catch (MsalUiRequiredException)
        {
            Debug.Log($"Needs UI for Login");
            try
            {
                res.res = await app.AcquireTokenAsync(scopes).ConfigureAwait(false);

                Debug.Log($"app.AcquireTokenAsync called {res.res}");
            }
            catch (MsalException msalex)
            {
                res.err = $"Error Acquiring Token:{Environment.NewLine}{msalex.Message}";
                Debug.Log($"{res.err}");
                return(res);
            }
            catch (Exception ex)
            {
                res.err = $"Error Acquiring Token Silently:{Environment.NewLine}{ex.Message}";
                Debug.Log($"{res.err}");
                return(res);
            }
        }
        catch (Exception ex)
        {
            res.err = $"Error Acquiring Token Silently:{Environment.NewLine}{ex.Message}";
            Debug.Log($"{res.err}");
            return(res);
        }

#if !UNITY_EDITOR && UNITY_WSA
        Debug.Log($"Access Token - {res.res.AccessToken}");
        ApplicationData.Current.LocalSettings.Values["UserId"] = res.res.Account.HomeAccountId.Identifier;
#endif
        return(res);
    }
コード例 #5
0
    public async Task <AuthResult> AcquireTokenAsync(IPublicClientApplication app,
                                                     IEnumerable <string> scopes,
                                                     string usrId,
                                                     Func <AuthenticationResult, Task> callback)
    {
        var usr = !string.IsNullOrEmpty(usrId) ? await app.GetAccountAsync(usrId) : null;

        var userStr = usr != null ? usr.Username : "******";
        //Debug.Log($"Found User {userStr}");
        AuthResult res = new AuthResult();

        try
        {
            //Debug.Log($"Calling AcquireTokenSilentAsync");
            res.res = await app.AcquireTokenSilentAsync(scopes, usr).ConfigureAwait(false);

            //Debug.Log($"app.AcquireTokenSilentAsync called {res.res}");
        }
        catch (MsalUiRequiredException)
        {
            //Debug.Log($"Needs UI for Login");
            try
            {
                res.res = await app.AcquireTokenAsync(scopes).ConfigureAwait(false);

                if (callback != null)
                {
                    await callback(res.res);
                }
                //Debug.Log($"app.AcquireTokenAsync called {res.res}");
            }
            catch (MsalException msalex)
            {
                res.err = $"Error Acquiring Token:{Environment.NewLine}{msalex}";
                //Debug.Log($"{res.err}");
                return(res);
            }
        }
        catch (Exception ex)
        {
            res.err = $"Error Acquiring Token Silently:{Environment.NewLine}{ex}";
            //Debug.Log($"{res.err}");
            return(res);
        }

#if !UNITY_EDITOR && UNITY_WSA
        Debug.Log($"Access Token - {res.res.AccessToken}");
        ApplicationData.Current.LocalSettings.Values["UserId"] = res.res.User.Identifier;
#endif
        return(res);
    }
        public async Task <string> GetTokenAsync()
        {
            if (!string.IsNullOrEmpty(_userId))
            {
                try
                {
                    var account = await _clientApplication.GetAccountAsync(_userId);

                    if (account != null)
                    {
                        var silentResult = await _clientApplication.AcquireTokenSilent(_scopes, account).ExecuteAsync();

                        return(silentResult.AccessToken);
                    }
                }
                catch (MsalUiRequiredException) { }
            }

            var result = await _clientApplication.AcquireTokenInteractive(_scopes).ExecuteAsync();

            _userId = result.Account.HomeAccountId.Identifier;
            return(result.AccessToken);
        }
コード例 #7
0
        public async void OnStart(IFileStorageSetupActivity activity)
        {
            if (activity.ProcessName.Equals(FileStorageSetupDefs.ProcessNameFileUsageSetup))
            {
                activity.State.PutString(FileStorageSetupDefs.ExtraPath, activity.Ioc.Path);
            }

            IAccount account = null;

            try
            {
                String userId = OneDrive2ItemLocation <OneDrive2PrefixContainerType> .FromString(activity.Ioc.Path).User?.Id;

                if (mClientByUser.ContainsKey(userId))
                {
                    finishActivityWithSuccess(activity);
                    return;
                }

                logDebug("needs acquire token");
                logDebug("trying silent login " + activity.Ioc.Path);

                account = Task.Run(async() => await _publicClientApp.GetAccountAsync(userId)).Result;
                logDebug("getting user ok.");
            }
            catch (Exception e)
            {
                logDebug(e.ToString());
            }
            if (account != null)
            {
                try
                {
                    logDebug("AcquireTokenSilent...");
                    AuthenticationResult authResult = await _publicClientApp.AcquireTokenSilent(Scopes, account)
                                                      .ExecuteAsync();

                    logDebug("AcquireTokenSilent ok.");
                    var graphClient = buildClient(authResult);

                    /*User me = await graphClient.Me.Request().WithForceRefresh(true).GetAsync();
                     * logDebug("received name " + me.DisplayName);*/

                    finishActivityWithSuccess(activity, authResult);
                    return;
                }
                catch (MsalUiRequiredException ex)
                {
                    logDebug("ui required");
                }
            }
            try
            {
                logDebug("try interactive");
                AuthenticationResult res = await _publicClientApp.AcquireTokenInteractive(Scopes)
                                           .WithParentActivityOrWindow((Activity)activity)
                                           .ExecuteAsync();

                logDebug("ok interactive");
                buildClient(res);
                finishActivityWithSuccess(activity, res);
            }
            catch (Exception e)
            {
                logDebug("authenticating not successful: " + e);
                Intent data = new Intent();
                data.PutExtra(FileStorageSetupDefs.ExtraErrorMessage, "authenticating not successful");
                ((Activity)activity).SetResult(Result.Canceled, data);
                ((Activity)activity).Finish();
            }
        }