private string DeleteUser() { var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey, Passphrase, JwtPublicKey); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(UserId); var client = boxJWT.AdminClient(adminToken); var usersRes = client.UsersManager.GetEnterpriseUsersAsync(); usersRes.Wait(); foreach (var user in usersRes.Result.Entries) { if (user.Login == UserIdToDelete) { var delUserRes = client.UsersManager.DeleteEnterpriseUserAsync(user.Id, false, false); delUserRes.Wait(); return("Success"); } } return("User Not Found"); }
private string DeleteGroup() { var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey, Passphrase, JwtPublicKey); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(UserId); var client = boxJWT.AdminClient(adminToken); var groupId = GetGroupIdByGroupName(client, GroupName); if (groupId == null) { return("Group not found."); } var res = client.GroupsManager.DeleteAsync(groupId); res.Wait(); if (res.Exception != null) { return(res.Exception.Message); } return("Success"); }
public async Task <ICustomActivityResult> Execute() { var Message = string.Empty; var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(USER_ID); var adminClient = boxJWT.AdminClient(adminToken); using (FileStream fileStream = new FileStream(FilePath, FileMode.Open)) { BoxFileRequest requestParams = new BoxFileRequest() { Name = NameFile, Parent = new BoxRequestEntity() { Id = FolderID } }; BoxFile file = await adminClient.FilesManager.UploadAsync(requestParams, fileStream); Message = file.Id; } return(this.GenerateActivityResult(Message)); }
public static void Initialize(TestContext testContext) { jsonConfig = Environment.GetEnvironmentVariable("JSON_CONFIG"); if (string.IsNullOrEmpty(jsonConfig)) { Debug.WriteLine("No json config found!"); } else { Debug.WriteLine("json config content length : " + jsonConfig.Length); var config = BoxConfig.CreateFromJsonString(jsonConfig); var session = new BoxJWTAuth(config); // create a new app user // client with permissions to manage application users var adminToken = session.AdminToken(); adminClient = session.AdminClient(adminToken); var user = CreateNewUser(adminClient).Result; userId = user.Id; Debug.WriteLine("New app user created : " + userId); // user client with access to user's data (folders, files, etc) userToken = session.UserToken(userId); userClient = session.UserClient(userToken, userId); } }
private string AddUser() { var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey, Passphrase, JwtPublicKey); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(UserId); var client = boxJWT.AdminClient(adminToken); var userRes = client.UsersManager.CreateEnterpriseUserAsync(new BoxUserRequest() { Name = UserName, Login = Login }); userRes.Wait(); if (userRes.Exception != null) { return(userRes.Exception.Message); } return("Success"); }
private async Task ExecuteMainAsync() { var config = ConfigureBoxApi(); var session = new BoxJWTAuth(config); // client with permissions to manage application users var adminToken = session.AdminToken(); var client = session.AdminClient(adminToken); var user = await CreateNewUser(client); Console.WriteLine("New app user created with Id = {0}", user.Id); // user client with access to user's data (folders, files, etc) var userToken = session.UserToken(user.Id); var userClient = session.UserClient(userToken, user.Id); // root folder has id = 0 var newFolder = await CreateNewFolder(userClient); Console.WriteLine("New folder created with Id = {0}", newFolder.Id); var timer = Stopwatch.StartNew(); var file = File.OpenRead("box_logo.png"); var uploaded = await UploadFile(newFolder, userClient, file); Console.WriteLine("New file uploaded with Id = {0} in {1} ms", uploaded.Id, timer.ElapsedMilliseconds); }
public Box(string userId, TraceWriter log) { traceWriter = log; var boxJwt = new BoxJWTAuth(ConfigureBoxApi()); var userToken = boxJwt.UserToken(userId); //valid for 60 minutes so should be cached and re-used userClient = boxJwt.UserClient(userToken, userId); }
static async Task MainAsync() { // rename the private_key.pem.example to private_key.pem and put your JWT private key in the file var privateKey = File.ReadAllText("private_key.pem"); var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID); // Proxy configuration - set isProxyEnabled = true if using Fiddler!! if (isProxyEnabled != false) { System.Net.WebProxy webProxy = new System.Net.WebProxy("http://127.0.0.1:8888"); NetworkCredential credential = new NetworkCredential("testUser", "testPass"); webProxy.Credentials = credential; boxConfig.WebProxy = webProxy; } var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.AdminToken(); Console.WriteLine("Admin Token: " + adminToken); Console.WriteLine(); var adminClient = boxJWT.AdminClient(adminToken); var adminFunc = new Func(adminClient); adminFunc.GetFolderItems(); var userId = "3768478578"; var userToken = boxJWT.UserToken(userId); // valid for 60 minutes so should be cached and re-used BoxClient userClient = boxJWT.UserClient(userToken, userId); var userFunc = new Func(userClient); userFunc.GetFolderItems(); // Stream fileContents = await userClient.FilesManager.DownloadStreamAsync(id: "675996854920"); // Download the file 675996854920 // var userRequest = new BoxUserRequest() { Name = "test appuser", IsPlatformAccessOnly = true }; // var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest); // Console.WriteLine("Created App User"); // var userToken = boxJWT.UserToken(appUser.Id); // var userClient = boxJWT.UserClient(userToken, appUser.Id); // var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync(); // Console.WriteLine("\nApp User Details:"); // Console.WriteLine("\tId: {0}", userDetails.Id); // Console.WriteLine("\tName: {0}", userDetails.Name); // Console.WriteLine("\tStatus: {0}", userDetails.Status); // Console.WriteLine(); // await adminClient.UsersManager.DeleteEnterpriseUserAsync(appUser.Id, false, true); // Console.WriteLine("Deleted App User"); }
static async Task MainAsync() { // rename the private_key.pem.example to private_key.pem and put your JWT private key in the file var privateKey = File.ReadAllText("private_key.pem"); var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.AdminToken(); Console.WriteLine("Admin Token: " + adminToken); Console.WriteLine(); var adminClient = boxJWT.AdminClient(adminToken); Console.WriteLine("Admin root folder items"); var items = await adminClient.FoldersManager.GetFolderItemsAsync("0", 500); items.Entries.ForEach(i => { Console.WriteLine("\t{0}", i.Name); //if (i.Type == "file") //{ // var previewLink = adminClient.FilesManager.GetPreviewLinkAsync(i.Id).Result; // Console.WriteLine("\tPreview Link: {0}", previewLink.ToString()); // Console.WriteLine(); //} }); Console.WriteLine(); var userRequest = new BoxUserRequest() { Name = "test appuser", IsPlatformAccessOnly = true }; var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest); Console.WriteLine("Created App User"); var userToken = boxJWT.UserToken(appUser.Id); var userClient = boxJWT.UserClient(userToken, appUser.Id); var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync(); Console.WriteLine("\nApp User Details:"); Console.WriteLine("\tId: {0}", userDetails.Id); Console.WriteLine("\tName: {0}", userDetails.Name); Console.WriteLine("\tStatus: {0}", userDetails.Status); Console.WriteLine(); await adminClient.UsersManager.DeleteEnterpriseUserAsync(appUser.Id, false, true); Console.WriteLine("Deleted App User"); }
public async Task <ICustomActivityResult> Execute() { var Message = string.Empty; var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(USER_ID); var adminClient = boxJWT.AdminClient(adminToken); await adminClient.FilesManager.DeleteAsync(id : FileID); Message = "Success"; return(this.GenerateActivityResult(Message)); }
//ToDo: change to accept the token or userId as parameter based on the windows authenticated user making the call private void CreateBoxClient() { IBoxConfig config = null; using (FileStream fs = new FileStream("CONFIG.JSON", FileMode.Open)) { config = BoxConfig.CreateFromJsonFile(fs); } var userId = "3420422604"; var session = new BoxJWTAuth(config); var userToken = session.UserToken(userId); boxClient = session.UserClient(userToken, userId); }
private string AddUserToGroup() { var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey, Passphrase, JwtPublicKey); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(UserId); var client = boxJWT.AdminClient(adminToken); var groupId = GetGroupIdByGroupName(client, GroupName); if (groupId == null) { return("Group not found."); } var usersRes = client.UsersManager.GetEnterpriseUsersAsync(); usersRes.Wait(); foreach (var user in usersRes.Result.Entries) { if (user.Login == UserIdToBeAdded) { var memberResult = client.GroupsManager.AddMemberToGroupAsync(new BoxGroupMembershipRequest { User = new BoxRequestEntity { Id = user.Id }, Group = new BoxGroupRequest { Id = groupId } }); memberResult.Wait(); memberResult.Wait(); if (memberResult.Exception != null) { return(memberResult.Exception.Message); } return("Success"); } } return("User Not Found"); }
static async Task validateUser(string name, string sub) { // Configure Box SDK instance var reader = new StreamReader("config.json"); var json = reader.ReadToEnd(); var config = BoxConfig.CreateFromJsonString(json); var sdk = new BoxJWTAuth(config); var token = sdk.AdminToken(); BoxClient client = sdk.AdminClient(token); // Search for matching Box app user for Okta ID BoxCollection <BoxUser> users = await client.UsersManager.GetEnterpriseUsersAsync(externalAppUserId : sub); System.Diagnostics.Debug.WriteLine(users.TotalCount); if (users.TotalCount > 0) { // Box user found, get token var userId = users.Entries[0].Id; var userToken = sdk.UserToken(userId); BoxClient userClient = sdk.UserClient(userToken, userId); // Get current user BoxUser currentUser = await userClient.UsersManager.GetCurrentUserInformationAsync(); System.Diagnostics.Debug.WriteLine("Current user name: " + currentUser.Name); } else { // No associated user found, create app user var userRequest = new BoxUserRequest() { Name = name, ExternalAppUserId = sub, IsPlatformAccessOnly = true }; var user = await client.UsersManager.CreateEnterpriseUserAsync(userRequest); System.Diagnostics.Debug.WriteLine("New user created: " + user.Name); } }
public async Task <ICustomActivityResult> Execute() { var Message = string.Empty; var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(USER_ID); var adminClient = boxJWT.AdminClient(adminToken); var requestParams = new BoxFileRequest() { Id = FileID, Parent = new BoxRequestEntity() { Id = FolderID }, Name = Name }; BoxFile fileCopy = await adminClient.FilesManager.CopyAsync(requestParams); Message = "Success"; return(this.GenerateActivityResult(Message)); }
public async Task <ICustomActivityResult> Execute() { var Message = string.Empty; var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, PRIVATE_KEY, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(USER_ID); var adminClient = boxJWT.AdminClient(adminToken); Stream fileContents = await adminClient.FilesManager.DownloadAsync(FileID); using (Stream file = File.Create(FilePath)) { byte[] buffer = new byte[8 * 1024]; int len; while ((len = fileContents.Read(buffer, 0, buffer.Length)) > 0) { file.Write(buffer, 0, len); } } Message = "Success"; return(this.GenerateActivityResult(Message)); }
public BoxClient UserClient(string userId) { //check cache for existing user token var cacheKey = $"/box/{_boxConfig.ClientId}/user-token/{userId}"; var userToken = _distributedCache.GetString(cacheKey); if (string.IsNullOrEmpty(userToken)) { //fetch a new user token from Box userToken = _boxJWTAuth.UserToken(userId); //store the token in the cache with a 45 minute expiration var options = new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = CACHE_ITEM_TTL }; _distributedCache.SetString(cacheKey, userToken, options); } return(_boxJWTAuth.UserClient(userToken, userId)); }
private string AddGroup() { var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey, Passphrase, JwtPublicKey); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(UserId); var client = boxJWT.AdminClient(adminToken); var res = client.GroupsManager.CreateAsync(new BoxGroupRequest() { Name = GroupName }); res.Wait(); if (res.Exception != null) { return(res.Exception.Message); } return("Success"); }
private string RemoveUserFromGroup() { var boxConfig = new BoxConfig(ClientId, ClientSecret, EntrepriseId, PrivateKey, Passphrase, JwtPublicKey); var boxJWT = new BoxJWTAuth(boxConfig); var adminToken = boxJWT.UserToken(UserId); var client = boxJWT.AdminClient(adminToken); var groupId = GetGroupIdByGroupName(client, GroupName); if (groupId == null) { return("Group not found."); } var membersResult = client.GroupsManager.GetAllGroupMembershipsForGroupAsync(groupId); membersResult.Wait(); foreach (var member in membersResult.Result.Entries) { if (member.User.Login == UserIdToBeRemoved) { var res = client.GroupsManager.DeleteGroupMembershipAsync(member.Id); res.Wait(); if (res.Exception != null) { return(res.Exception.Message); } return("Success"); } } return("User Not Found"); }
static void test_app_mycapp_2() { IBoxConfig config = null; using (FileStream fs = new FileStream("87881712_nqkf95rj_config.json", FileMode.Open)) { config = BoxConfig.CreateFromJsonFile(fs); } var boxJWT = new BoxJWTAuth(config); var adminToken = boxJWT.AdminToken(); var adminClient = boxJWT.AdminClient(adminToken); var user_info = adminClient.UsersManager.GetCurrentUserInformationAsync().Result; var items = adminClient.FoldersManager.GetFolderItemsAsync("0", 100).Result; var users = adminClient.UsersManager.GetEnterpriseUsersAsync().Result; user_info = adminClient.UsersManager.GetUserInformationAsync("224172711").Result; var client_token = boxJWT.UserToken("224172711"); var client = boxJWT.UserClient(client_token, "224172711"); items = client.FoldersManager.GetFolderItemsAsync("0", 100).Result; }
public static string UserToken(string boxUserId) { object userTokenObject = BoxJwtAuth.UserToken(boxUserId); return((string)userTokenObject); }
static async Task MainAsync() { try { /* Read the config file that is provided when an application is * created in the Box Dev Consolse * */ string jsonConfig = System.IO.File.ReadAllText(configFile()); var config = BoxConfig.CreateFromJsonString(jsonConfig); /* Authenticate. This will provide access to the service account */ var boxJWT = new BoxJWTAuth(config); var adminToken = ""; adminToken = boxJWT.AdminToken(); Console.WriteLine("Admin Token:" + adminToken); /* * Searching for a particular user from the enterprise given the login name */ BoxClient boxClient = boxJWT.AdminClient(adminToken); BoxCollection <BoxUser> boxUserCollection = await boxClient.UsersManager.GetEnterpriseUsersAsync(userLogin(), 0, 100, null, "managed", null, false); List <BoxUser> userList = boxUserCollection.Entries; Console.WriteLine("Entries:" + userList.Count); if (userList.Count > 0) { foreach (var user in userList) { Console.WriteLine("User Login:"******" ID:" + user.Id); } } /* Replace this variable for the user you want. This is the users * internal Box ID and is all numbers e.g. 3445252385. Suggest that * the list of users in the system is cached in the Token Factory * and synced perdiodically. */ var userId = userInformation(); /* Ask box for a token for the user */ var userToken = boxJWT.UserToken(userId); Console.WriteLine("User Token:" + userToken); /* Generate a downscoped token to the ITEM_PREVIEW scope */ var exchanger = new TokenExchange(adminToken, "item_preview"); /*Optionally you can downscope to a particular resource. Omitting this will downscope * all resources to the scope set above regardless of resource. * exchanger.SetResource("https://api.box.com/2.0/files/123456789"); */ string downscopedToken = exchanger.Exchange(); Console.WriteLine("Downscoped ITEM_PREVIEW Token:" + downscopedToken); /* Print out some user information for the demo */ var userClient = boxJWT.UserClient(userToken, userId); var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync(); Console.WriteLine("\n User Details:"); Console.WriteLine("\tId: {0}", userDetails.Id); Console.WriteLine("\tName: {0}", userDetails.Name); Console.WriteLine("\tStatus: {0}", userDetails.Status); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } }
public static string UserToken(string boxUserId = null) { if (boxUserId == null) { //first check the session var id = (string)HttpContext.Current.Session[BOX_USER_ID_KEY]; if (id == null) { //didn't find in session so call Auth0 and look in user's metadata var auth0UserId = ClaimsPrincipal.Current.Claims.FirstOrDefault(c => c.Type == "user_id").Value; id = GetBoxIdFromAuth0(auth0UserId); //save it in the session HttpContext.Current.Session[BOX_USER_ID_KEY] = id; } boxUserId = id; } string cache_key = USER_TOKEN_CACHE_KEY + "/" + boxUserId; object userTokenObject = CacheHelper.Fetch(cache_key, CACHE_EXPIRES_IN_DEFAULT, () => { return(BOX_JWT_HELPER.UserToken(boxUserId)); }); return((string)userTokenObject); }