如何对onedrive for Business进行身份验证并上传文件(WinForms)

本文关键字:文件 WinForms 身份验证 onedrive for Business | 更新日期: 2023-09-27 18:10:17

我正在尝试制作一个应用程序,将我写的带有C#代码的文件上传到Microsoft Office 365 OneDrive for Business
我尝试了几种方法来获得刷新令牌和访问令牌
但我找不到如何在网络上实现这一点的方法。

我试着用这个博客解释如何使用REST进行身份验证。
这就是我到目前为止得到的:

private void btnAuthenticate_Click(object sender, EventArgs e)
{
    webBrowser1.Navigate(GetAuthorizationUrl());
}
private string GetAuthorizationUrl()
{
    // Create a request for an authorization code.
    string url = string.Format("    {0}common/oauth2/authorize?&response_type=code&client_id={1}&resource={2}&redirect_uri={3}&state={4}",
        _authorizationEndpoint,
        _clientId,
        _resource,
        _redirectURI,
        _state);
    return url;
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
    if (e.Url.AbsoluteUri.Contains("code="))
    {
        var splited = e.Url.AbsoluteUri.Split(new char[] { '=', '&' });
        _authorizationInformation.Code = splited[1];
        _authorizationInformation.SessionState = splited[3];
        if (_authorizationInformation.SessionState.Equals(_state))
        {
            GetTokenInformation(_authorizationInformation);
        }
    }
}
    
private TokenInformation GetTokenInformation(AuthorizationInformation authInformation)
{
    try
    {
        var response = Post(HttpUtility.UrlEncode(_tokenEndpoint), new NameValueCollection(){ 
            { "grant_type", "authorization_code" },
            { "code", authInformation.Code },
            { "redirect_uri", _redirectURI },
            { "client_id", _clientId },
            { "client_secret", _clientSecret },
        });
        Stream responseStream = new MemoryStream(response);
        using (var reader = new StreamReader(responseStream))
        {
            var json = reader.ReadToEnd();
            _tokenInformation = JsonConvert.DeserializeObject<TokenInformation>(json);
        }
    }
    catch (Exception exception)
    {
        MessageBox.Show(exception.Message, "Error" + exception.HResult.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    return null;
}

在方法GetTokenInformation中,响应始终为空0字节
**第一个问题:如何使用OAuth向onedrive pro进行正确身份验证**
**第二个问题:当我得到accesstoken时,我如何上传文件**

如何对onedrive for Business进行身份验证并上传文件(WinForms)

正如我所知,您不能在Windows客户端应用程序(包括Windows窗体应用程序(中对SharePoint在线使用OAuth身份验证。这篇MSDN文章在线展示了SharePoint的OAuth流:您需要一个服务器URL作为应用程序的注册重定向URI,但Windows窗体应用程序没有。

另一种方法是使用SharePoint客户端对象模型,下面的代码显示了如何访问OneDrive:

        string username = "xxx@xxx.onmicrosoft.com";
        String pwd = "xxx#";
        ClientContext context = new ClientContext("https://xxx-my.sharepoint.com/personal/xxx_xxxinc_onmicrosoft_com/");
        SecureString password = new SecureString();
        foreach (char c in pwd.ToCharArray())
        {
            password.AppendChar(c);            }
        context.Credentials = new SharePointOnlineCredentials(username, password);
        //login in to SharePoint online
        context.ExecuteQuery();   
        //OneDrive is acctually a Document list
        List docs = context.Web.Lists.GetByTitle("Documents");
        context.ExecuteQuery();
        CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
        ListItemCollection items = docs.GetItems(query);
        // Retrieve all items the document list
        context.Load(items);
        context.ExecuteQuery();
        foreach (ListItem listItem in items)
        {
            Console.WriteLine(listItem["Title"]);
        } 

此外,您还可以使用RESTApis,这篇文章使用SharePoint2013API访问OneDrive for Business解释了如何使用REST来实现这一点。