在c#控制台项目中使用OneDrive SDK进行身份验证

时间:2017-04-05 11:08:34

标签: c# console-application onedrive

我正在尝试创建一个可以从OneDrive下载所有OneNote文件的程序。但是当我尝试使用params = ActionController::Parameters.new({ person: { name: 'Francesco', age: 22, pets: [{ name: 'Purplish', category: 'dogs' }] } }) permitted = params.permit(person: [ :name, { pets: :name } ]) permitted.permitted? # => true permitted[:person][:name] # => "Francesco" permitted[:person][:age] # => nil permitted[:person][:pets][0][:name] # => "Purplish" permitted[:person][:pets][0][:category] # => nil 进行身份验证时,会出现一个白色窗口,然后没有任何反应。我认为该窗口应该是Microsoft登录,但它中没有任何内容。

这是我的代码:

msaAuthenticationProvider

它进入AuthenticateUserAsync方法,然后是窗口上传,之后没有任何反应。 我也不确定returnURL应该是什么,因为所有的例子都是针对app版本或者只是说返回URL而没有提供任何示例。

1 个答案:

答案 0 :(得分:1)

很抱歉延迟。您是否尝试过这种方法:

msaAuthenticationProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync();

编辑:如果最后一个已知的连接令牌可用,则可以使用此方法对用户进行身份验证而无需提示。因此,如果可以或提示用户输入登录名和密码,此操作将还原最后一个身份验证缓存。这可以代替已经使用的AuthenticateUserAsync方法。我遇到了同样的问题,这种方法解决了它。

编辑2:OneDrive SDK文档非常差,我发现自己很辛苦,因为我发现您可以获取连接令牌(例如保存它)并在异步任务中需要时将其注入:< / p>

        if (_OneDriveCacheBlob == null)
        {
            bool needtosaveblob = true;
            _OneDriveCacheBlob = null;
            CredentialCache cc = new CredentialCache();
            _OneDriveCacheBlob = GetUser(CurrentUserName).OneDriveAuthProviderBlob;

            if (_OneDriveCacheBlob != null)
            {
                cc.InitializeCacheFromBlob(_OneDriveCacheBlob);
                needtosaveblob = false;
            }
            MsaAuthenticationProvider msaAuthProvider = new MsaAuthenticationProvider(OneDriveClass.clientId, OneDriveClass.returnUrl, scopes, cc);

            int timeout = 15;
            _ = Task.Run(() => WaitForODConnection(msaAuthProvider));                
            while (!WaitForODConnectionExecuted)
            {
                if (timeout <= 0)
                    break;

                await Task.Delay(TimeSpan.FromSeconds(1));
                timeout -= 1;
            }
            WaitForODConnectionExecuted = false;

            if (timeout <= 0)
            {
                // Request for reconnection to OneDrive because of invalid Blob                    
                await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                {
                    //This method requests a new login by a simple msaAuthProvider.AuthenticateUserAsync() call from a new instance of MsaAuthenticationProvider and a new instance of CredentialCache.
                    //ChangeOneDriveAccount(); 
                });
            }
            else
            {
                _OneDriveClient = new OneDriveClient(OneDriveClass.basUrl, msaAuthProvider);
            }

            string accessToken = msaAuthProvider.CurrentAccountSession.AccessToken;
            JObject json = await GetUserInfos(msaAuthProvider.CurrentAccountSession.AccessToken);
            if (json != null)
            {
                // If you need
                oneDriveUserName = json["name"].ToString();
                oneDriveEmail = json["emails"]["account"].ToString();
            }
            else
            {
                //Unable to get OneDrive user informations;                    
            }

            if (needtosaveblob)
            {
                _OneDriveCacheBlob = cc.GetCacheBlob();
                //You can save _OneDriveCacheBlob to reuse it later;
            }
        }

要获取用户信息:

/// <summary>
    /// Return User informations as a JObject. To get username and email, if return isn't null :
    /// username = json["name"].ToString();
    /// email = json["emails"]["account"].ToString();
    /// </summary>
    /// <param name="accessToken">accesstoken of Onedrive account</param>
    /// <returns>JObject value</returns>
    public static async Task<JObject> GetUserInfos(string accessToken)
    {
        JObject json = null;
        Uri uri = new Uri($"https://apis.live.net/v5.0/me?access_token={accessToken}");

        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
        System.Net.Http.HttpResponseMessage result = await httpClient.GetAsync(uri);
        //user info returnd as JSON
        string jsonUserInfo = await result.Content.ReadAsStringAsync();
        if (jsonUserInfo != null)
        {
            json = JObject.Parse(jsonUserInfo);
            //username = json["name"].ToString();
            //email = json["emails"]["account"].ToString();
        }
        return json;
    }

并且因为如果令牌不再可用,OneDrive方法将永不过期:

    bool WaitForODConnectionExecuted = false;
    private async Task WaitForODConnection(MsaAuthenticationProvider msaAuthProvider)
    {
        await msaAuthProvider.RestoreMostRecentFromCacheOrAuthenticateUserAsync();
        WaitForODConnectionExecuted = true;
    }

这不好笑,我认为我的代码不干净,因此请不要使用它而无需进行任何操作。