Search code examples
c#.netasp.net-mvcdropbox

.Net how to refresh token for DropBox?


I making .Net MVC application that use DropBox as file storage. I successfuly made uploading files to DropBox from my application but I get short time life token that expires evry 4 hour. I need some code examples how to refresh token.

 OAuth2Response CodeResponse = await DropboxOAuth2Helper.ProcessCodeFlowAsync(result.Data.Code, AppKey, AppSecret, RedirectUri);


                Settings.AccessToken = CodeResponse.AccessToken;
                Settings.RefreshToken = CodeResponse.RefreshToken;

Solution

  • The First-step is open this url on your browser:

    https://www.dropbox.com/oauth2/authorize?client_id=<APP_KEY>&token_access_type=offline&response_type=code
    

    Save this string code.

    Next-step: You will create a simple project console to read the refresh token:

        using System;
        using System.Collections.Generic;
        using System.Net.Http;
        using System.Threading.Tasks;
        using Newtonsoft.Json;
        
        class Program
        {
            private const string AppKey = "YOUR APP KEY"; 
            private const string AppSecret = "APP SECRET"; 
            private const string AccessCode = "CODE WHATYOU RECEIVED"; 
            private static string RefreshToken = "REPEATE-EXPIRED-TOKEN"; 
            private static string AccessToken = "YOUR-EXPIRED-TOKEN"; 
            static async Task Main(string[] args)
            {
                await GetRefreshToken();
                await RefreshAccessToken();
            }
        
            private static async Task GetRefreshToken()
            {
                try
                {
                    var base64Authorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{AppKey}:{AppSecret}"));
                    using (var client = new HttpClient())
                    {
                        var requestBody = new FormUrlEncodedContent(new[]
                        {
                            new KeyValuePair<string, string>("code", AccessCode),
                            new KeyValuePair<string, string>("grant_type", "authorization_code"),
                        });
        
                        client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Authorization}");
        
                        var response = await client.PostAsync("https://api.dropbox.com/oauth2/token", requestBody);
                        var responseString = await response.Content.ReadAsStringAsync();
        
                        Console.WriteLine("Refresh Token Response: " + responseString);
                        if (response.IsSuccessStatusCode)
                        {
                            var tokenResponse = JsonConvert.DeserializeObject<DropboxTokenResponse>(responseString);
                            RefreshToken = tokenResponse.RefreshToken; // Atualize o refresh token
                            Console.WriteLine("🚀 ~ getRefreshToken ~ REFRESH_TOKEN: " + RefreshToken);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error getting refresh token: " + ex.Message);
                }
            }
        
            private static async Task RefreshAccessToken()
            {
                try
                {
                    var base64Authorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{AppKey}:{AppSecret}"));
                    using (var client = new HttpClient())
                    {
                        var requestBody = new FormUrlEncodedContent(new[]
                        {
                            new KeyValuePair<string, string>("refresh_token", RefreshToken),
                            new KeyValuePair<string, string>("grant_type", "refresh_token"),
                        });
        
                        client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Authorization}");
        
                        var response = await client.PostAsync("https://api.dropbox.com/oauth2/token", requestBody);
                        var responseString = await response.Content.ReadAsStringAsync();
        
                        Console.WriteLine("Access Token Response: " + responseString);
                        if (response.IsSuccessStatusCode)
                        {
                            var tokenResponse = JsonConvert.DeserializeObject<DropboxTokenResponse>(responseString);
                            AccessToken = tokenResponse.AccessToken; // Atualize o access token
                            Console.WriteLine("🚀 ~ refreshAccessToken ~ ACCESS_TOKEN: " + AccessToken);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error refreshing access token: " + ex.Message);
                }
            }
        
            private class DropboxTokenResponse
            {
                [JsonProperty("access_token")]
                public string AccessToken { get; set; }
        
                [JsonProperty("refresh_token")]
                public string RefreshToken { get; set; }
        
                [JsonProperty("expires_in")]
                public int ExpiresIn { get; set; }
            }
        }
    

    The last step, you have to create a HTTP Client Dropbox with that configuration:

    public async Task<IActionResult> Index()
    {
        try
        {
            DropboxClientConfig config = new();
            
            List<Metadata> Pdfs = new List<Metadata>();
    
            using (var _client = new DropboxClient(_configuration["DropboxToken"], _configuration["DropboxRefreshToken"], _configuration["DropboxAppKey"], _configuration["DropboxAppSecret"], config))
            {
                var isRefresh = await _client.RefreshAccessToken(null);
    
                var listItems = await _client.Files.ListFolderAsync(_configuration["DropboxFolder"]);
                foreach (var item in listItems.Entries)
                {
                    if (item.IsFile)
                    {
                        Pdfs.Add(item);
                    }
                }
            }
            return View(Pdfs);
        }
        catch(Exception e)
        {
            return View("Erro", "");
        }
       
    }