所以我将 OneDrive 与 MS Graph 一起使用,它默认内置函数,如下所示,用于将当前令牌存储在缓存中,因此您不需要每次都请求它,如下面的 program.cs 所示:
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
builder.Configuration.Bind("AzureAd", options);
}).EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
MS Graph Identity sdk 的 AddInMemoryTokenCaches() 函数将令牌存储在缓存中供以后使用,并且如果令牌通过重定向过期,sdk 会处理获取新的刷新令牌。但是,我没有看到 Box API 有这样的功能,我很好奇做这样的事情的最佳方法。我相信这可能会出现在其他场景中,而不仅仅是 Box。我目前的方法是在我的 program.cs 中为 box 的接口启动服务
builder.Services.AddTransient<IBoxDrive, BoxDrive>();
然后在这个接口和它的扩展中,我使用依赖注入来获取配置文件,然后在每个请求中请求一个新的令牌。这看起来效率很低,但我不确定如何缓存它,而且如果令牌确实过期,我如何确保我获得一个新的刷新令牌而不是每次都像我不那样请求它。我的界面如下:
namespace TestProject.Repositories
{ 公共接口 IBoxDrive { 任务 FileInfoAsync(字符串 BoxId); }
public class BoxDrive : IBoxDrive
{
private readonly IWebHostEnvironment _env;
private readonly BoxJWTAuth _session;
public BoxDrive(IWebHostEnvironment env) {
var _env = env;
var RootPath = _env.ContentRootPath;
var boxConfigLocation = Path.Combine(System.IO.Directory.GetParent(RootPath).ToString(), "box/699422622_746zo0rh_config.json");
var config = BoxConfigBuilder.CreateFromJsonString(System.IO.File.ReadAllText(boxConfigLocation)).Build();
_session = new BoxJWTAuth(config);
}
public async Task<BoxFile> FileInfoAsync(string BoxId)
{
BoxFile file = null;
try
{
var adminToken = await _session.AdminTokenAsync(); //valid for 60 minutes so should be cached and re-used
BoxClient adminClient = _session.AdminClient(adminToken);
file = await adminClient.FilesManager.GetInformationAsync(id: BoxId);
return file;
}
catch (Exception ex2)
{
return file;
}
}
}
}