Server-to-Server (JWT) .Net
回答済みIs it possible to use the service account to upload files, or is it really required to create an App User with the Service account, and then use the App User to upload files? T
-
As near as I can tell the answer is no, you cannot use a service account to upload content. You need to create an App User. There are many steps in the Box Portal: https://developer.box.com/docs/authentication-with-jwt
using System;
using System.IO;
using System.Threading.Tasks;
using Box.V2.Config;
using Box.V2.JWTAuth;
using Box.V2;
using Box.V2.Auth;
using Box.V2.Models;
using Box.V2.Utility;namespace BoxPlayground
{
public class Program
{
static void Main(string[] args)
{
try
{
// Create an async method to execute and await Box SDK methods.
ExecuteMainAsync().Wait();
}
catch (Exception ex)
{
// Log any errors for debugging
Console.WriteLine(ex);
}
}private static async Task ExecuteMainAsync()
{
// Open a stream to read and dispose of the automatically created Box configuration file.
using (FileStream fs = new FileStream($"./config.json", FileMode.Open))
{
// Use the downloaded config.json file to get a service-client
var session = new BoxJWTAuth(BoxConfig.CreateFromJsonFile(fs));
var serviceAccountClient = session.AdminClient(session.AdminToken());// User the service client to create an "App User"
var userRequest = new BoxUserRequest() { Name = "test appuser", IsPlatformAccessOnly = true };
var appUser = await serviceAccountClient.UsersManager.CreateEnterpriseUserAsync(userRequest);// Get the App User token and client
var userToken = session.UserToken(appUser.Id); //valid for 60 minutes so should be cached and re-used
var appUserClient = session.UserClient(userToken, appUser.Id);// The rest of this is just example to show how to use an App User client to work with files
BoxFile newFile;
// Create request object with name and parent folder the file should be uploaded to
using (FileStream stream = new FileStream($"./BoxView.pptx", FileMode.Open))
{
BoxFileRequest req = new BoxFileRequest()
{
Name = "BoxView.pptx",
Parent = new BoxRequestEntity() { Id = "0" }
};// Use the App User client to upload a file
newFile = await appUserClient.FilesManager.UploadAsync(req, stream);
}var fileId = newFile.Id;
// Use the Appp User client to get a file, or in this case the download link.
var downloadUri = await appUserClient.FilesManager.GetDownloadUriAsync(fileId);
}
}
}
}
サインインしてコメントを残してください。
コメント
1件のコメント