我正在制作使用 DropBox 作为文件存储的 .Net MVC 应用程序。 我成功地从我的应用程序将文件上传到 DropBox,但我得到的令牌有效期很短,每 4 小时就会过期。我需要一些如何刷新令牌的代码示例。
OAuth2Response CodeResponse = await DropboxOAuth2Helper.ProcessCodeFlowAsync(result.Data.Code, AppKey, AppSecret, RedirectUri);
Settings.AccessToken = CodeResponse.AccessToken;
Settings.RefreshToken = CodeResponse.RefreshToken;
应用程序可以通过请求“离线”访问来获得长期访问,在这种情况下,应用程序会收到一个“刷新令牌”,可用于根据需要检索新的短期访问令牌,而无需进一步的手动用户干预。您可以在OAuth指南和授权文档中找到更多信息。 这篇博文中有处理此流程的基本轮廓,这可以作为一个有用的示例。
如果您使用 .NET,我们建议使用 官方 Dropbox API v2 .NET SDK。当您使用官方 Dropbox API v2 .NET SDK 时,您无需自行实现 OAuth 流程的所有代码。 SDK 将为您完成大部分工作。您可以在这里找到使用此功能的示例。
第一步是在浏览器上打开此网址:
https://www.dropbox.com/oauth2/authorize?client_id=<APP_KEY>&token_access_type=offline&response_type=code
保存该字符串代码。
下一步:您将创建一个简单的项目控制台来读取刷新令牌:
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; }
}
}
最后一步,您必须使用该配置创建一个 HTTP 客户端 Dropbox:
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", "");
}
}