OneDrive / onedrive-api-docs

Official documentation for the OneDrive API
MIT License
458 stars 232 forks source link

Use a refresh_token to gain a new access token #372

Closed opicko closed 8 years ago

opicko commented 8 years ago

I am trying to understand how to get a new access token from a cached refresh_token for OneDrive for Business. The documentation does not describe what API calls need to made to accomplish this. The following instructions explain the process but not how to do this with the API.

I am having a problem mapping your 4 steps to APIcalls? It very confusing having an API but all the documentaion refers to URIs?

can you reword the following four steps to the specific API calls required?

1: Initial OAuth authorization through login.windows.net/oauth2/authorize?client_id={clientId}&scope=MyFiles.Write&response_type=code&redirect_uri={appUrl} This returns back to you an authorization code.

2: Redeem the authorization code for an access_token and refresh_token for the Office Discovery Service POST to login.windows.net/common/oauth2/token with the following form parameters: client_id, client_secret, redirect_uri, code, grant_type, and resource=https://api.office.com/discovery/

Note: You need to have the value of resource be exactly “https://api.office.com/discovery/” with the trailing /, otherwise the access token you get back won’t be valid.

3: Store the refresh_token securely for later. Even though you specify the resource for the discovery service in the request, the refresh_token value you receive is good for any service you’ve been authorized to access by the user. That means this refresh_token will get you into the OneDrive for Business, you just need to redeem it with the proper resource value later.

4: Use the access_token from #2 to make a request to the discovery service to find the OneDrive for Business URL: GET https://api.office.com/discovery/v1.0/me/services Authorization: Bearer {access_token}

rgregg commented 8 years ago

The API call is an HTTP request you need to make, which is described here: https://dev.onedrive.com/auth/aad_oauth.htm#step-4-redeem-refresh-token-for-an-access-token-to-call-onedrive-api

If you are using one of the OneDrive SDKs then this step should be taken care of for you. Are you using an SDK or using the REST API directly?

opicko commented 8 years ago

Yes, I am trying to use the OneDriveSdk.dll oneDrivesdk.windowsForms.dll

                this.oneDriveClient = BusinessClientExtensions.GetActiveDirectoryClient(FormBrowser.AadClientId, FormBrowser.AadReturnUrl);
            }
        }

        try
        {
            if (!this.oneDriveClient.IsAuthenticated)
            {
                await this.oneDriveClient.AuthenticateAsync();

This piece of code is doing the authentication when I select the “sign in to aad” option in the sample code and it works But I cannot figure out how to save the refresh token and then use it to request a new access token.

From: Ryan Gregg [mailto:notifications@github.com] Sent: Wednesday, May 25, 2016 1:22 PM To: OneDrive/onedrive-api-docs onedrive-api-docs@noreply.github.com Cc: Bill Pickowicz PICKOWICZ@omtool.com; Author author@noreply.github.com Subject: Re: [OneDrive/onedrive-api-docs] Use a refresh_token to gain a new access token (#372)

The API call is an HTTP request you need to make, which is described here: https://dev.onedrive.com/auth/aad_oauth.htm#step-4-redeem-refresh-token-for-an-access-token-to-call-onedrive-api

If you are using one of the OneDrive SDKs then this step should be taken care of for you. Are you using an SDK or using the REST API directly?

— You are receiving this because you authored the thread. Reply to this email directly or view it on GitHubhttps://github.com/OneDrive/onedrive-api-docs/issues/372#issuecomment-221643590

opicko commented 8 years ago

I have been trying to follow the instructions in your link but this does not seem to be working for me

https://login.microsoftonline.com/common/oauth2/Token?client_id=e1801d98-8aef-4d5d-b4cc-0634c828d31a&redirect_uri=https://license.omtool.com/redirect/&grant_type=refresh_token&refresh_token=AAABAAAAiL9Kn2Z27UubvWFPbm0gLczBe6UACW7fX1WypUgtWRetX7XHp9JrAq5XUFHDICbqZ2FJhMznHaOwmcq-aU6w8kGGoGLg-wGa0b2e4n5wWR3JXAx6jV6gVeFhsc-KA6N2zwBzbLXR5oz3J-GpaVK1W8ruIxcCOx2OHqwMgmiQD853ilkOKQfKezPFm8_YQnja6XOykZDEm_PsWh5xvTEtfk-_ppl9aJSwdNrCHlsuhJNuyW1hqc_-mK1Lod8HgO_Jo9BDYk2Zv6256ONvIkHvhEtqcaZVWmIMmDKME0gkKdWHGgV8yA0qqB88LvgIxIUOywDzF-_kka38gTdUdwbZOAgWCn2euDEgOjPWlYIArnXsB3Kr19iYAoJCkazfaNzzjghRFkMY5PPPiUc0aD63jdy9cpPDYUVO57bOWFUQhQ9vBr43h0VaUpwA2cnYjRKni5_AFzhGYJnwxCSxp4pH_czLMqqnZG7qaYy0kzHlR-IVQW8b6GRu2D8PE66hcY-Sw2YQGGUdMPxym3BB_tFxqebiyqYI2ZWhf699BvhqVG3XUMFLz98Tkp0D1k02oRTnbSlEkA11CV2RQfXgkfNvOOR5DFSN4kImxs1kdzx3U9sQNfqC8XwWgNUQCgpAEJiBFtGDMItZttYk0LQGb9HlhNNMFZs8PE9u6bLWij4PoEsgAA&resource=https://omtool.sharepoint.com/

From: Ryan Gregg [mailto:notifications@github.com] Sent: Wednesday, May 25, 2016 1:22 PM To: OneDrive/onedrive-api-docs onedrive-api-docs@noreply.github.com Cc: Bill Pickowicz PICKOWICZ@omtool.com; Author author@noreply.github.com Subject: Re: [OneDrive/onedrive-api-docs] Use a refresh_token to gain a new access token (#372)

The API call is an HTTP request you need to make, which is described here: https://dev.onedrive.com/auth/aad_oauth.htm#step-4-redeem-refresh-token-for-an-access-token-to-call-onedrive-api

If you are using one of the OneDrive SDKs then this step should be taken care of for you. Are you using an SDK or using the REST API directly?

— You are receiving this because you authored the thread. Reply to this email directly or view it on GitHubhttps://github.com/OneDrive/onedrive-api-docs/issues/372#issuecomment-221643590

ginach commented 8 years ago

@opicko, we've just pushed a new version of the OneDriveSDK package that supports initializing a OneDrive for Business client using a refresh token. You can do this using BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync().

As for retrieving refresh token from a previous authentication request, this should be set in client.AuthenticationProvider.CurrentAccountSession.RefreshToken, if it was returned by the first authenticate call.

opicko commented 8 years ago

Gina,

Can you provide a fragment of how this call is made? The following snippet

Complains “IOneDriveCLient” does not contain a definition for “GetAwaiter”

       await this.oneDriveClient = BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync(
                        new BusinessAppConfig
                        {
                            ActiveDirectoryAppId = AadClientId,
                            ActiveDirectoryReturnUrl = AadReturnUrl,
                        }, m_sRefreshToken);

Bill

From: Gina [mailto:notifications@github.com] Sent: Wednesday, May 25, 2016 8:51 PM To: OneDrive/onedrive-api-docs onedrive-api-docs@noreply.github.com Cc: Bill Pickowicz PICKOWICZ@omtool.com; Mention mention@noreply.github.com Subject: Re: [OneDrive/onedrive-api-docs] Use a refresh_token to gain a new access token (#372)

@opickohttps://github.com/opicko, we've just pushed a new version of the OneDriveSDK package that supports initializing a OneDrive for Business client using a refresh token. You can do this using BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync().

As for retrieving refresh token from a previous authentication request, this should be set in client.AuthenticationProvider.CurrentAccountSession.RefreshToken, if it was returned by the first authenticate call.

— You are receiving this because you were mentioned. Reply to this email directly or view it on GitHubhttps://github.com/OneDrive/onedrive-api-docs/issues/372#issuecomment-221749461

ginach commented 8 years ago

@opicko, you'll want to await the async method and not the client:

this.oneDriveClient = await BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync( new BusinessAppConfig { ActiveDirectoryAppId = AadClientId, ActiveDirectoryReturnUrl = AadReturnUrl, }, m_sRefreshToken);

opicko commented 8 years ago

Gina,

I have modified FormBrowser.cs and added a RefreshSignIn() method and added my hard coded values required to do a refresh from token signin. I still get an “authentication failure”.

How long does the refresh_token last?

Bill

From: Gina [mailto:notifications@github.com] Sent: Wednesday, May 25, 2016 8:51 PM To: OneDrive/onedrive-api-docs onedrive-api-docs@noreply.github.com Cc: Bill Pickowicz PICKOWICZ@omtool.com; Mention mention@noreply.github.com Subject: Re: [OneDrive/onedrive-api-docs] Use a refresh_token to gain a new access token (#372)

@opickohttps://github.com/opicko, we've just pushed a new version of the OneDriveSDK package that supports initializing a OneDrive for Business client using a refresh token. You can do this using BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync().

As for retrieving refresh token from a previous authentication request, this should be set in client.AuthenticationProvider.CurrentAccountSession.RefreshToken, if it was returned by the first authenticate call.

— You are receiving this because you were mentioned. Reply to this email directly or view it on GitHubhttps://github.com/OneDrive/onedrive-api-docs/issues/372#issuecomment-221749461

// ------------------------------------------------------------------------------ // Copyright (c) 2015 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------

namespace OneDriveApiBrowser { using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.OneDrive.Sdk; using Microsoft.OneDrive.Sdk.WindowsForms;

public partial class FormBrowser : Form
{
    private const string AadClientId = "e1801d98-8aef-4d5d-b4cc-0634c828d31a";
    private const string AadReturnUrl = "https://license.omtool.com/redirect";

    private const string MsaClientId = "000000004C10F00C";
    private const string MsaReturnUrl = "https://login.live.com/oauth20_desktop.srf";

    private static readonly string[] Scopes = { "onedrive.readwrite", "wl.signin" };

    private const int UploadChunkSize = 10 * 1024 * 1024;       // 10 MB
    private IOneDriveClient oneDriveClient { get; set; }
    private Item CurrentFolder { get; set; }
    private Item SelectedItem { get; set; }

    private OneDriveTile _selectedTile;

    public FormBrowser()
    {
        InitializeComponent();
    }

    private void ShowWork(bool working)
    {
        this.UseWaitCursor = working;
        this.progressBar1.Visible = working;

    }

    private async Task LoadFolderFromId(string id)
    {
        if (null == this.oneDriveClient) return;

        // Update the UI for loading something new
        ShowWork(true);
        LoadChildren(new Item[0]);

        try
        {
            var expandString = this.oneDriveClient.ClientType == ClientType.Consumer
                ? "thumbnails,children(expand=thumbnails)"
                : "thumbnails,children";

            var folder =
                await this.oneDriveClient.Drive.Items[id].Request().Expand(expandString).GetAsync();

            ProcessFolder(folder);
        }
        catch (Exception exception)
        {
            PresentOneDriveException(exception);
        }

        ShowWork(false);
    }

    private async Task LoadFolderFromPath(string path = null)
    {
        if (null == this.oneDriveClient) return;

        // Update the UI for loading something new
        ShowWork(true);
        LoadChildren(new Item[0]);

        try
        {
            Item folder;

            var expandValue = this.oneDriveClient.ClientType == ClientType.Consumer
                ? "thumbnails,children(expand=thumbnails)"
                : "thumbnails,children";

            if (path == null)
            {
                folder = await this.oneDriveClient.Drive.Root.Request().Expand(expandValue).GetAsync();
            }
            else
            {
                folder =
                    await
                        this.oneDriveClient.Drive.Root.ItemWithPath("/" + path)
                            .Request()
                            .Expand(expandValue)
                            .GetAsync();
            }

            ProcessFolder(folder);
        }
        catch (Exception exception)
        {
            PresentOneDriveException(exception);
        }

        ShowWork(false);
    }

    private void ProcessFolder(Item folder)
    {
        if (folder != null)
        {
            this.CurrentFolder = folder;

            LoadProperties(folder);

            if (folder.Folder != null && folder.Children != null && folder.Children.CurrentPage != null)
            {
                LoadChildren(folder.Children.CurrentPage);
            }
        }
    }

    private void LoadProperties(Item item)
    {
        this.SelectedItem = item;
        objectBrowser.SelectedItem = item;
    }

    private void LoadChildren(IList<Item> items)
    {
        flowLayoutContents.SuspendLayout();
        flowLayoutContents.Controls.Clear();

        // Load the children
        foreach (var obj in items)
        {
            AddItemToFolderContents(obj);
        }

        flowLayoutContents.ResumeLayout();
    }

    private void AddItemToFolderContents(Item obj)
    {
        flowLayoutContents.Controls.Add(CreateControlForChildObject(obj));
    }

    private void RemoveItemFromFolderContents(Item itemToDelete)
    {
        flowLayoutContents.Controls.RemoveByKey(itemToDelete.Id);
    }

    private Control CreateControlForChildObject(Item item)
    {
        OneDriveTile tile = new OneDriveTile(this.oneDriveClient);
        tile.SourceItem = item;
        tile.Click += ChildObject_Click;
        tile.DoubleClick += ChildObject_DoubleClick;
        tile.Name = item.Id;
        return tile;
    }

    void ChildObject_DoubleClick(object sender, EventArgs e)
    {
        var item = ((OneDriveTile)sender).SourceItem;

        // Look up the object by ID
        NavigateToFolder(item);
    }
    void ChildObject_Click(object sender, EventArgs e)
    {
        if (null != _selectedTile)
        {
            _selectedTile.Selected = false;
        }

        var item = ((OneDriveTile)sender).SourceItem;
        LoadProperties(item);
        _selectedTile = (OneDriveTile)sender;
        _selectedTile.Selected = true;
    }

    private void FormBrowser_Load(object sender, EventArgs e)
    {

    }

    private void NavigateToFolder(Item folder)
    {
        Task t = LoadFolderFromId(folder.Id);

        // Fix up the breadcrumbs
        var breadcrumbs = flowLayoutPanelBreadcrumb.Controls;
        bool existingCrumb = false;
        foreach (LinkLabel crumb in breadcrumbs)
        {
            if (crumb.Tag == folder)
            {
                RemoveDeeperBreadcrumbs(crumb);
                existingCrumb = true;
                break;
            }
        }

        if (!existingCrumb)
        {
            LinkLabel label = new LinkLabel();
            label.Text = "> " + folder.Name;
            label.LinkArea = new LinkArea(2, folder.Name.Length);
            label.LinkClicked += linkLabelBreadcrumb_LinkClicked;
            label.AutoSize = true;
            label.Tag = folder;
            flowLayoutPanelBreadcrumb.Controls.Add(label);
        }
    }

    private void linkLabelBreadcrumb_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        LinkLabel link = (LinkLabel)sender;

        RemoveDeeperBreadcrumbs(link);

        Item item = link.Tag as Item;
        if (null == item)
        {

            Task t = LoadFolderFromPath(null);
        }
        else
        {
            Task t = LoadFolderFromId(item.Id);
        }
    }

    private void RemoveDeeperBreadcrumbs(LinkLabel link)
    {
        // Remove the breadcrumbs deeper than this item
        var breadcrumbs = flowLayoutPanelBreadcrumb.Controls;
        int indexOfControl = breadcrumbs.IndexOf(link);
        for (int i = breadcrumbs.Count - 1; i > indexOfControl; i--)
        {
            breadcrumbs.RemoveAt(i);
        }
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void UpdateConnectedStateUx(bool connected)
    {
        signInAadToolStripMenuItem.Visible = !connected;
        signInMsaToolStripMenuItem.Visible = !connected;
        signOutToolStripMenuItem.Visible = connected;
        flowLayoutPanelBreadcrumb.Visible = connected;
        flowLayoutContents.Visible = connected;
    }

    private async void signInAadToolStripMenuItem_Click(object sender, EventArgs e)
    {
       //     await this.SignIn(ClientType.Business);
            await RefreshSignIn();
    }

    private async void signInMsaToolStripMenuItem_Click(object sender, EventArgs e)
    {
        await this.SignIn(ClientType.Consumer);
    }

    private const string myAadClientId = "e1801d98-8aef-4d5d-b4cc-0634c828d31a";
    private const string myAadReturnUrl = "https://license.omtool.com/redirect";

// private const string sDefaultRefreshToken = "AAABAAAAiL9Kn2Z27UubvWFPbm0gLe6f8TGi5rambqBZiaitHK5zkwHVKDsN7ikbYHkIX6O5FJVqW_DSeYy4smLdvYb-dEam0hGBwtkuobdLM3nFc0XP0P1FtVhu2Vk5hGcXyoEKyPZx0cF0JmO3R0BT7W_tAVVeCCV68qZkyW83OuLrX6z6o1rhVoFZ-tUD03Go7-fu2zpXXvK7xfsAJF6I49a3kHmj-G_qWp_pwuGsRq_D0vfzZjVBTHzSGJ7CJHwz01WPgCe2j3jhR1N-RYrBL_0r9oi8pW-Ij_a1fAOaxtrutgo8cGCavqA2Td9GRyLQRpVN-6p3k6eS-Eo3kw1XKN83f_w2kFCLRLcxIdrgBiufDjtJiBsNii5O7Xmlpf2vUtqATOo3gME22CWlmmzvZLT51Ve0tPkcuntSYj5LrAr0szLLTdv6TbZ95P99JTgrmlTiGgzFGd9BOIzAyKl1axgLKRnyyMpSkIIqKlHOFgAou1j0exE-M1McOIMwbR93y1E6gE1KMLEA7pGC7urwVLGpKSjWCZKQF3fWRpnVn4q9Fil-3pKGQ328zqW1W0U5biLDFBAkjq9pXQsNMTkj2o3-6o1I4HG43lOPxX_GNYMWMzJacLSnhHdkd-r7QUyAxP_ubK2itj1xQlNf159yhnK0qfbl_MlTTDNruQwrhnoibZQNNX79PO7B7h-mtXxDCGhCe7v6weGfGN2sADUUGj60gyAA"; private const string sDefaultRefreshToken = "AAABAAAAiL9Kn2Z27UubvWFPbm0gLbUArNPlZW9UMYFDY36f79TphvVVTxtpHxdAR7Lbl9-Tp0FO5eQDnYUB3vG14M5w7xhEK4mBzJ2nM2sMJEv3Ixt6D9snkfB6pNKXJDVPvGJCDIAsWAXxI5Fk-4PqZaPyfubIbthzI_tbrmxeAcXXvNNHxAfWNBXPMpnFNCj3Pi2HmouR-RRm1BFhdt8D2D-ohtgoY1wNR3nkFaEWb02gTvYw3iUhrMIpv7nrNfXUPxlfLMi6Bp52jbONw8lQE0ngRhsHR3r9sW-oOX1NO0lCFvHo53zE_dvCAT5whVfadDDJyquGdEgJVdHmrDCyBcM4pNasjNtMG-46wVWsMLSzG6IIACFkbAN1CXoMx_ZokSn7JCH-MkOfI_ZWV3yC0g5Zspu_Kf9QFCj9FPAQo3Rf8Wary4Fk4Q5nsJOc_XzrslDogw2JyJGBt6QA8lp9BCcmbOiPyXLJzhxtqcfXzjJba1XzfeK8nXNSsZ1stZeJcDyOHdlqF1JXd4kPxDOg3XIYIDGj2yfPYBBS5c4vHkWup5fguwCv7xruHewgtNdlGTzUE33dW3eQq0RdUX-IVPPiaR6DqZdeLoSWel7bik9KbKZzYsqFOXI0r_6ErbXaRhI7PNVCkIlQsdLejupMZbnRiNqcfV52vhr5LzEBDXhg7ArAtI9qZgyieBhHuPO2_A0fKATXWBM3oUQuwFES3hkyAA";

    private async Task RefreshSignIn()
{

    try
    {
            if (this.oneDriveClient == null)
            {
                this.oneDriveClient = await BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync(
                     new BusinessAppConfig
                     {
                         ActiveDirectoryAppId = myAadClientId,
                         ActiveDirectoryReturnUrl = myAadReturnUrl,
                         ActiveDirectoryServiceResource = "https://omtool-my.sharepoint.com/_api/v2.0/me",
                     },
                     sDefaultRefreshToken);
            }

            await LoadFolderFromPath();

        UpdateConnectedStateUx(true);
    }
    catch (OneDriveException exception)
    {
        // Swallow authentication cancelled exceptions, but reset the client
        if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
        {
            if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
            {
                MessageBox.Show(
                    "Authentication failed",
                    "Authentication failed",
                    MessageBoxButtons.OK);

                ((OneDriveClient)this.oneDriveClient).Dispose();
                this.oneDriveClient = null;
            }
            else
            {
                PresentOneDriveException(exception);
            }
        }
        else
        {
            ((OneDriveClient)this.oneDriveClient).Dispose();
            this.oneDriveClient = null;
        }
    }
}
private async Task SignIn(ClientType clientType)
    {
        if (this.oneDriveClient == null)
        {
            this.oneDriveClient = clientType == ClientType.Consumer
                ? OneDriveClient.GetMicrosoftAccountClient(
                    FormBrowser.MsaClientId,
                    FormBrowser.MsaReturnUrl,
                    FormBrowser.Scopes,
                    webAuthenticationUi: new FormsWebAuthenticationUi())
                : BusinessClientExtensions.GetClient(
                    new BusinessAppConfig
                    {
                        ActiveDirectoryAppId = FormBrowser.AadClientId,
                        ActiveDirectoryReturnUrl = FormBrowser.AadReturnUrl,
                    });
        }

        try
        {
            if (!this.oneDriveClient.IsAuthenticated)
            {
                await this.oneDriveClient.AuthenticateAsync();
            }

            await LoadFolderFromPath();

            UpdateConnectedStateUx(true);
        }
        catch (OneDriveException exception)
        {
            // Swallow authentication cancelled exceptions, but reset the client
            if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
            {
                if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
                {
                    MessageBox.Show(
                        "Authentication failed",
                        "Authentication failed",
                        MessageBoxButtons.OK);

                    ((OneDriveClient)this.oneDriveClient).Dispose();
                    this.oneDriveClient = null;
                }
                else
                {
                    PresentOneDriveException(exception);
                }
            }
            else
            {
                ((OneDriveClient)this.oneDriveClient).Dispose();
                this.oneDriveClient = null;
            }
        }
    }

    private async void signOutToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (this.oneDriveClient != null)
        {
            await this.oneDriveClient.SignOutAsync();
            ((OneDriveClient)this.oneDriveClient).Dispose();
            this.oneDriveClient = null;
        }

        UpdateConnectedStateUx(false);
    }

    private System.IO.Stream GetFileStreamForUpload(string targetFolderName, out string originalFilename)
    {
        OpenFileDialog dialog = new OpenFileDialog();
        dialog.Title = "Upload to " + targetFolderName;
        dialog.Filter = "All Files (*.*)|*.*";
        dialog.CheckFileExists = true;
        var response = dialog.ShowDialog();
        if (response != DialogResult.OK)
        {
            originalFilename = null;
            return null;
        }

        try
        {
            originalFilename = System.IO.Path.GetFileName(dialog.FileName);
            return new System.IO.FileStream(dialog.FileName, System.IO.FileMode.Open);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error uploading file: " + ex.Message);
            originalFilename = null;
            return null;
        }
    }

    private async void simpleUploadToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var targetFolder = this.CurrentFolder;

        string filename;
        using (var stream = GetFileStreamForUpload(targetFolder.Name, out filename))
        {
            if (stream != null)
            {
                string folderPath = targetFolder.ParentReference == null
                    ? "/drive/items/root:"
                    : targetFolder.ParentReference.Path + "/" + Uri.EscapeUriString(targetFolder.Name);
                var uploadPath = folderPath + "/" + Uri.EscapeUriString(System.IO.Path.GetFileName(filename));

                try
                {
                    var uploadedItem =
                        await
                            this.oneDriveClient.ItemWithPath(uploadPath).Content.Request().PutAsync<Item>(stream);

                    AddItemToFolderContents(uploadedItem);

                    MessageBox.Show("Uploaded with ID: " + uploadedItem.Id);
                }
                catch (Exception exception)
                {
                    PresentOneDriveException(exception);
                }
            }
        }
    }

    private async void simpleIDbasedToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var targetFolder = this.CurrentFolder;

        string filename;
        using (var stream = GetFileStreamForUpload(targetFolder.Name, out filename))
        {
            if (stream != null)
            {
                try
                {
                    var uploadedItem =
                        await
                            this.oneDriveClient.Drive.Items[targetFolder.Id].ItemWithPath(filename).Content.Request()
                                .PutAsync<Item>(stream);

                    AddItemToFolderContents(uploadedItem);

                    MessageBox.Show("Uploaded with ID: " + uploadedItem.Id);
                }
                catch (Exception exception)
                {
                    PresentOneDriveException(exception);
                }
            }
        }
    }

    private async void createFolderToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FormInputDialog dialog = new FormInputDialog("Create Folder", "New folder name:");
        var result = dialog.ShowDialog();
        if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(dialog.InputText))
        {
            try
            {
                var folderToCreate = new Item { Name = dialog.InputText, Folder = new Folder() };
                var newFolder =
                    await this.oneDriveClient.Drive.Items[this.SelectedItem.Id].Children.Request()
                        .AddAsync(folderToCreate);

                if (newFolder != null)
                {
                    MessageBox.Show("Created new folder with ID " + newFolder.Id);
                    this.AddItemToFolderContents(newFolder);
                }
            }
            catch(OneDriveException oneDriveException)
            {
                if (oneDriveException.IsMatch(OneDriveErrorCode.InvalidRequest.ToString()))
                {
                    MessageBox.Show(
                        "Please enter a valid folder name.",
                        "Invalid folder name",
                        MessageBoxButtons.OK);

                    dialog.Dispose();
                    this.createFolderToolStripMenuItem_Click(sender, e);
                }
                else
                {
                    PresentOneDriveException(oneDriveException);
                }
            }
            catch (Exception exception)
            {
                PresentOneDriveException(exception);
            }
        }
    }

    private static void PresentOneDriveException(Exception exception)
    {
        string message = null;
        var oneDriveException = exception as OneDriveException;
        if (oneDriveException == null)
        {
            message = exception.Message;
        }
        else
        {
            message = string.Format("{0}{1}", Environment.NewLine, oneDriveException.ToString());
        }

        MessageBox.Show(string.Format("OneDrive reported the following error: {0}", message));
    }

    private async void deleteSelectedItemToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var itemToDelete = this.SelectedItem;
        var result = MessageBox.Show("Are you sure you want to delete " + itemToDelete.Name + "?", "Confirm Delete", MessageBoxButtons.YesNo);
        if (result == System.Windows.Forms.DialogResult.Yes)
        {
            try
            {
                await this.oneDriveClient.Drive.Items[itemToDelete.Id].Request().DeleteAsync();

                RemoveItemFromFolderContents(itemToDelete);
                MessageBox.Show("Item was deleted successfully");
            }
            catch (Exception exception)
            {
                PresentOneDriveException(exception);
            }
        }
    }

    private async void getChangesHereToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            var result =
                await this.oneDriveClient.Drive.Items[this.CurrentFolder.Id].Delta(null).Request().GetAsync();

            Console.WriteLine(result);
        }
        catch (Exception ex)
        {
            PresentOneDriveException(ex);
        }
    }

    private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {

    }

    private async void openFromOneDriveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var cleanAppId = "0000000040131ABA";
        var result = await OneDriveSamples.Picker.FormOneDrivePicker.OpenFileAsync(cleanAppId, true, this);

        try
        {
            var pickedFilesContainer = await result.GetItemsFromSelectionAsync(this.oneDriveClient);

            ProcessFolder(pickedFilesContainer);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

        //// Do something with the picker result we got
        //var pickedFiles = await result.GetSelectionResponseAsync();
        //if (pickedFiles == null)
        //{
        //    MessageBox.Show("Error picking files.");
        //    return;
        //}

        //StringBuilder builder = new StringBuilder();
        //builder.AppendFormat("You selected {0} files\n", pickedFiles.Length);
        //foreach (var file in pickedFiles)
        //{
        //    builder.AppendLine(file.name);
        //}

        //MessageBox.Show(builder.ToString());
    }

    private async void saveSelectedFileToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var item = this.SelectedItem;
        if (null == item)
        {
            MessageBox.Show("Nothing selected.");
            return;
        }

        var dialog = new SaveFileDialog();
        dialog.FileName = item.Name;
        dialog.Filter = "All Files (*.*)|*.*";
        var result = dialog.ShowDialog();
        if (result != System.Windows.Forms.DialogResult.OK)
            return;

        using (var stream = await this.oneDriveClient.Drive.Items[item.Id].Content.Request().GetAsync())
        using (var outputStream = new System.IO.FileStream(dialog.FileName, System.IO.FileMode.Create))
        {
            await stream.CopyToAsync(outputStream);
        }
    }
}

}

opicko commented 8 years ago

this.oneDriveClient = await BusinessClientExtensions.GetSilentlyAuthenticatedClientAsync()

when I make the above call I get the following exception?

AADSTS50001: The application named https://omtool-my.sharepoint.com/_api/v2.0/me was not found in the tenant named 0fc1435a-1295-4804-882b-c99004d550b5. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant. Trace ID: 28f04c41-b023-4ccb-896f-b9583caaac62 Correlation ID: 90c32405-8009-4462-b35f-5c0b0f1fbd02 Timestamp: 2016-06-01 17:51:43Z

Where does the tenant come from I don't provide it in the call?

ginach commented 8 years ago

After following up offline, this was due to using an incorrect service resource ID. Closing issue.

ohs0612 commented 5 years ago

Hello Gina @ginach ,

Is that possible to get OneDriveClient object with "refresh token"or "access token" instead of using the authentication process on Android device by java code? Because user has already login my web server, so I can have these two tokens from backend server. And I would like to retrieve the user data from OneDrive.

I know it is not directly related to the topic here, just really want to know by the way.

Thank you a lot in advance.

Odee