Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        public static async Task AssemblyInitialize(TestContext testContext)
        {
            var jsonConfig = Environment.GetEnvironmentVariable("INTEGRATION_TESTING_CONFIG");

            if (string.IsNullOrEmpty(jsonConfig))
            {
                Debug.WriteLine("No json config found in environment variables Reading from config.json.");
                jsonConfig = ReadFromJson("config.json");
            }

            var config = BoxConfigBuilder.CreateFromJsonString(jsonConfig)
                         .Build();
            var session = new BoxJWTAuth(config);

            var json       = JObject.Parse(jsonConfig);
            var adminToken = await session.AdminTokenAsync();

            AdminClient = session.AdminClient(adminToken);

            if (json["userID"] != null && json["userID"].ToString().Length != 0)
            {
                UserId = json["userID"].ToString();
            }
            else
            {
                var user = await CreateNewUser(AdminClient);

                UserId = user.Id;
            }
            var userToken = await session.UserTokenAsync(UserId);

            UserClient = session.UserClient(userToken, UserId);

            EnterpriseId = config.EnterpriseId;
        }
Ejemplo n.º 3
0
        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);
            }
        }
        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);
        }
Ejemplo n.º 5
0
        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");
        }
Ejemplo n.º 6
0
        private 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.example");

            var boxConfig = new BoxConfigBuilder(_clientId, _clientSecret, _enterpriseId, privateKey, _jwtPrivateKeyPassword, _jwtPublicKeyId)
                            .Build();
            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = await boxJWT.AdminTokenAsync();

            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 = await boxJWT.UserTokenAsync(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");
        }
Ejemplo n.º 7
0
        static async Task MainAsync()
        {
            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 preview_link = adminClient.FilesManager.GetPreviewLinkAsync(i.Id).Result;
                //    Console.WriteLine("\tPreview Link: {0}", preview_link.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");
        }
Ejemplo n.º 8
0
        //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);
        }
Ejemplo n.º 9
0
    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 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));
        }
Ejemplo n.º 11
0
        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;
        }
Ejemplo n.º 12
0
        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);
            }
        }
Ejemplo n.º 13
0
 public static BoxClient UserClient(string boxUserId = null)
 {
     return(BOX_JWT_HELPER.UserClient(UserToken(boxUserId), boxUserId));
 }
Ejemplo n.º 14
0
 public static BoxClient UserClient(string boxUserId)
 {
     return(BoxJwtAuth.UserClient(UserToken(boxUserId), boxUserId));
 }