Brampage
Brampage

Reputation: 6974

How to do authentication onedrive for Business and upload a file (WinForms)

Im trying to make a app which uploads the files with the C# code I write to Microsoft Office 365 OneDrive for Business.
I tried several things to get the refresh token and access token.
But I could not find the way how to implement this on the web.

I tried to use this blog explenation on how to authenticate with REST.
This is what I have got so far:

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

In the method GetTokenInformation the response is always empty 0 bytes.
**First question: How do I correctly authenticate with OAuth to onedrive pro?**
**Second question: When I got the accesstoken how do I upload a file?**

Upvotes: 0

Views: 4198

Answers (1)

Matt
Matt

Reputation: 6050

As I know, you can not use OAuth authentication for SharePoint online in Windows client applications(including Windows Form applications). This MSDN article shows the OAuth flow for SharePoint online: you need a server URL as the app’s registered redirect URI, but Windows Forms application doesn't have that.

Another way to do it is to use SharePoint client object model, the code below shows how to access the OneDrive:

        string username = "[email protected]";
        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"]);
        } 

Also, you can use REST Apis, this article Access OneDrive for Business using the SharePoint 2013 APIs explains how to use REST to do it.

Upvotes: 1

Related Questions