とほほのBox入門
目次
Boxとは
- 米国 Box Inc. が提供するクラウドストレージサービスです。
- ファイルの保存・共有・共同編集を安全かつ効率的に行うことができます。
- Windows や Linux にもマウントして使用することができます。
- Box API を使用してアクセスすることもできます。
- プランは下記を参照してください。
サインアップ
- https://www.box.com/ja-jp/home にアクセスします。
- [サインアップ] からサインアップします。
Windowsから利用する(Box Drive)
- https://www.box.com/ja-jp/resources/downloads にアクセスします。
- [Box Driveをダウンロード] でダウンロードしてインストールします。
Linuxから利用する(Rclone)
- Rclone をインストールします。
# curl -s https://rclone.org/install.sh -o install.sh # bash -x install.sh # rm install.sh
- Rclone config を実行し、
myboxという名前でリモートストレージを作成します。# rclone config No remotes found, make a new one? n) New remote s) Set configuration password q) Quit config n/s/q> n Enter name for new remote. name> mybox Option Storage. Type of storage to configure. Choose a number from below, or type in your own value. 1 / 1Fichier \ (fichier) : Storage> box Option client_id. OAuth Client Id. Leave blank normally. Enter a value. Press Enter to leave empty. client_id> (Enter) Option client_secret. OAuth Client Secret. Leave blank normally. Enter a value. Press Enter to leave empty. client_secret> (Enter) Option box_config_file. Box App config.json location Leave blank normally. Leading `~` will be expanded in the file name as will environment variables such as `${RCLONE_CONFIG_DIR}`. Enter a value. Press Enter to leave empty. box_config_file> (Enter) Option access_token. Box App Primary Access Token Leave blank normally. Enter a value. Press Enter to leave empty. access_token> (Enter) Option box_sub_type. Choose a number from below, or type in your own value of type string. Press Enter for the default (user). 1 / Rclone should act on behalf of a user. \ (user) 2 / Rclone should act on behalf of a service account. \ (enterprise) box_sub_type> (Enter) Edit advanced config? y) Yes n) No (default) y/n> (Enter) Use web browser to automatically authenticate rclone with remote? * Say Y if the machine running rclone has a web browser you can use * Say N if running rclone on a (remote) machine without web browser access If not sure try Y. If Y failed, try N. y) Yes (default) n) No y/n> (Enter) 2025/11/13 09:34:51 NOTICE: Make sure your Redirect URL is set to "http://127.0.0.1:53682/" in your custom config. 2025/11/13 09:34:51 ERROR : Failed to open browser automatically (exec: "xdg-open": executable file not found in $PATH) - please go to the following link: http://127.0.0.1:53682/auth?state=fkXqkpdsTiFXyxFn2cWe-A 2025/11/13 09:34:51 NOTICE: Log in and authorize rclone for access 2025/11/13 09:34:51 NOTICE: Waiting for code... - ブラウザから上記の
http://127.0.0.1:53682/auth?...にアクセスして [Boxへのアクセスを許可] します。2025/11/13 09:36:21 NOTICE: Got code Configuration complete. Options: - type: box - token: {"access_token":"****", ...} Keep this "mybox" remote? y) Yes this is OK (default) e) Edit this remote d) Delete this remote y/e/d> (Enter) Current remotes: Name Type ==== ==== mybox box e) Edit existing remote n) New remote d) Delete remote r) Rename remote c) Copy remote s) Set configuration password q) Quit config e/n/d/r/c/s/q> q - rclone コマンドで Box フォルダを操作することができます。
$ rclone lsf mybox:/folder1 # フォルダの中身を参照 $ rclone copy mybox:/folder1/file1.txt . # ファイルをコピー
- 下記の様に Box をファイルシステムにマウントすることもできます。
# mkdir /box # rclone mount mybox:/ /box &
APIからアクセスする(Box API)
- Box 上のファイル等に対してでアクセスするための Web API です。
- Box開発者コンソールの画面上で Platform アプリを登録し、そのアプリに対して発行された認証情報を用いて API からアクセスします。
- 下記の3種類の Platform アプリがあります。
- カスタムアプリ : Box に API 経由でアクセスするのに最適なアプリ。
- アクセス制限付きアプリ : マニュアルの一般公開など Box の一部機能を画面付きで公開するアプリ。
- Box Custom Skill : Box 上のファイルに対して AI 処理を行う際などに利用する拡張機能。
- カスタムアプリには、下記の4つの認証方式があります。
- 開発者トークン : 開発時の動作確認用の認証方式です。60分で有効期限が切れるため本番運用には向きません。
- OAuth 2.0 : ブラウザを用いてユーザ認証を行う形式の認証。
- クライアント資格情報付与 : JWT より簡素ですが、発行されたサービスアカウントのみで操作することができます。
- JWT : 少し面倒ですが、発行されたサービスアカウントまたは任意の Box ユーザアカウントで操作することができます。
- 開発者トークンと OAuth 2.0 は無料版の Box でも使用できます。
- クライアント資格情報付与 と JWT は認証作業が必要で、Box の有償プランへの加入が必要です。
- マニュアルは下記で公開されています。
Python からルートフォルダ(フォルダID:0)にファイルをアップロードするサンプルを下記に示します。
開発者トークン認証
- 開発者コンソール にアクセスします。
- [Platformアプリの作成] から [カスタムアプリ] でカスタムアプリを作成します。
アプリ名: MyCustomApp 説明: (省略可) 目的: 自動化 アプリケーションの作成者: (省略可) 認証方法: (開発者トークンの場合はいずれでも可)
- 作成したアプリの [構成] タブで [Boxに格納されているすべてのファイルとフォルダへの書込み] にチェックを入れて [変更を保存] します。
- 同じく [構成] タブで [開発者トークン] を発行します。
- 開発者トークンは 60分間のみ有効なので、期限がきれた場合は再発行してください。
- 下記プログラムの
YOUR_DEV_TOKENに [開発者トークン] を指定してプログラムを実行してください。import json import requests DEV_TOKEN = 'YOUR_DEV_TOKEN' # 開発者トークン FOLDER_ID = '0' # アップロード先フォルダID(例: '0' はルートフォルダ) FILE_NAME = 'example.txt' # アップロードするファイル名 FILE_PATH = './example.txt' # アップロードするファイルパス名 # ファイルをアップロードする url = 'https://upload.box.com/api/2.0/files/content' headers = { 'Authorization': f'Bearer {DEV_TOKEN}' } with open(FILE_PATH, 'rb') as f: files = { 'file': (FILE_NAME, f) } attributes = { 'name': FILE_NAME, 'parent': { 'id': FOLDER_ID } } data = { 'attributes': json.dumps(attributes) } response = requests.post(url, headers=headers, files=files, data=data, timeout=30) # 結果を表示する if response.status_code == 201: print('OK') print(response.json()) else: print('NG') print(response.status_code) print(response.text)
OAuth 2.0認証
- OAuth 2.0 認証を行うには、リダイレクトURI を2つ用意しておく必要があります。ここでは仮に下記としますが、この URL は外部からアクセス可能で、http:// ではなく https:// である必要があります。
REDIRECT_URI_1: https://www.example.com/oauth2REDIRECT_URI_2: https://www.example.com/redirect
- 開発者コンソール にアクセスします。
- [Platformアプリの作成] から [カスタムアプリ] でカスタムアプリを作成します。
アプリ名: MyOAuthApp 説明: (省略可) 目的: 自動化 アプリケーションの作成者: (省略可) 認証方法: ユーザー認証(OAuth 2.0)
- 作成したアプリの [構成] タブで [Boxに格納されているすべてのファイルとフォルダへの書込み] にチェックを入れます。
- 同じく [構成] タブで [リダイレクトURI] に
REDIRECT_URI_1(例:https://www.example.com/oauth2を入力して [追加] します。 - 同じく [構成] タブで [リダイレクトURI] に
REDIRECT_URI_2(例:https://www.example.com/redirectを入力して [追加] します。 - [変更を保存] します。
- [構成] タブの [クライアントID] と [クライアントシークレット] をメモしておきます。
- サーバープログラムはまず、ブラウザにリダイレクトを発行して、下記の URL にアクセスさせます。
CLIENT_IDとREDIRECT_URI_1にはクライアントIDとリダイレクトURIを指定してください。https://account.box.com/api/oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI_1
- ブラウザは上記の URL にアクセスし、必要に応じでログインを行います。ログイン後、Box はブラウザにリダイレクトを発行し、下記の URL にアクセスさせます。
STATUSとCODEにはステータス情報とコードが格納されています。https://www.example.com/oauth2/status=STATUS&code=CODE
- サーバープログラムは下記の URL に POST します。
CODE,CLIENT_ID,CLIENT_SECRET,REDIRECT_URI_2にはそれぞれ上記で得た値を設定してください。POST https://api.box.com/oauth2/token grant_type=authorization_code code=CODE client_id=CLIENT_ID client_secret=CLIENT_SECRET redirect_uri=REDIRECT_URI_2
- 例えば Python であれば次のようなコードになります。
import requests data = { 'grant_type': 'authorization_code', 'code': 'CODE', 'client_id': 'CLIENT_ID', 'client_secret': 'CLIENT_SECRET', 'redirect_uri': 'REDIRECT_URI_2', } result = requests.post('https://api.box.com/oauth2/token', data=data, timeout=30) - レスポンスには下記の JSON が含まれます。
{ "access_token": "ACCESS_TOKEN", "expires_in": EXPIRES_IN, "restricted_to": [], "refresh_token": "REFRESH_TOKEN", "token_type": "bearer" } - ここで得たアクセストークン
ACCESS_TOKENを用いてファイルをアップロードします。例えば Python であれば次のようなコードになります。import json import requests ACCESS_TOKEN = 'ACCESS_TOKEN' FILE_NAME = 'example.txt' FILE_PATH = './example.txt' FOLDER_ID = '0' # ファイルをアップロードする url = 'https://upload.box.com/api/2.0/files/content' headers = { 'Authorization': f'Bearer {ACCESS_TOKEN}' } with open(FILE_PATH, 'rb') as f: files = { 'file': (FILE_NAME, f) } attributes = { 'name': FILE_NAME, 'parent': { 'id': FOLDER_ID } } data = { 'attributes': json.dumps(attributes) } response = requests.post(url, headers=headers, files=files, data=data, timeout=30) - ブラウザの再表示で再送されないように
REDIRECT_URI_2にリダイレクトします。
クライアント資格情報許可認証
- 開発者コンソール にアクセスします。
- [Platformアプリの作成] から [カスタムアプリ] でカスタムアプリを作成します。
アプリ名: MyClientApp 説明: (省略可) 目的: 自動化 アプリケーションの作成者: (省略可) 認証方法: サーバー認証(クライアント資格情報許可)
- 作成したアプリの [構成] タブで [Boxに格納されているすべてのファイルとフォルダへの書込み] にチェックを入れて [変更を保存] します。
- アプリは作成や変更後、管理者による承認を行う必要があります。
- 下記の様なプログラムでファイルをアップロードします。
import json import requests CLIENT_ID = 'YOUR_CLIENT_ID' # クライアントID CLIENT_SECRET = 'YOUR_CLIENT_SECRET' # クライアントシークレット BOX_SUBJECT_TYPE = 'enterprise' # 'enterprise' または 'user' BOX_SUBJECT_ID = 'YOUR_ENTERPRISE_ID' # エンタープライズIDまたはユーザーID FOLDER_ID = '0' # フォルダID(ルートは0) FILE_NAME = 'example.txt' # ファイル名 FILE_PATH = './example.txt' # ファイルパス名 # アクセストークンを得る token_url = 'https://api.box.com/oauth2/token' data = { 'grant_type': 'client_credentials', 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'box_subject_type': BOX_SUBJECT_TYPE, 'box_subject_id': BOX_SUBJECT_ID } res = requests.post(token_url, data=data, timeout=30) access_token = res.json()['access_token'] # ファイルをアップロードする url = 'https://upload.box.com/api/2.0/files/content' headers = { 'Authorization': f'Bearer {access_token}' } with open(FILE_PATH, 'rb') as f: files = { 'file': (FILE_NAME, f) } attributes = { 'name': FILE_NAME, 'parent': { 'id': FOLDER_ID } } data = { 'attributes': json.dumps(attributes) } response = requests.post(url, headers=headers, files=files, data=data, timeout=30)
JWT認証
- 開発者コンソール にアクセスします。
- [Platformアプリの作成] から [カスタムアプリ] でカスタムアプリを作成します。
アプリ名: MyJWTApp 説明: (省略可) 目的: 自動化 アプリケーションの作成者: (省略可) 認証方法: サーバー認証(JWT使用)
- 作成したアプリの [構成] タブで [Boxに格納されているすべてのファイルとフォルダへの書込み] にチェックを入れて [変更を保存] します。
- [公開/秘密キーペアを生成] ボタンを押し、JSON ファイルをダウンロードします。ダウンロードしたファイルを config.json として読み込みます。
- アプリは作成や変更後、管理者による承認を行う必要があります。
- Python の場合下記のパッケージをインストールしておきます。
pip install cryptography pyjwt requests
- 下記の様なプログラムでファイルをアップロードします。
import json import time import jwt import requests from cryptography.hazmat.primitives import serialization FOLDER_ID = '0' # フォルダID(ルートは0) FILE_NAME = 'example.txt' # ファイル名 FILE_PATH = './example.txt' # ファイルパス名 # config.jsonを読み込む with open('config.json') as f: config = json.load(f) client_id = config['boxAppSettings']['clientID'] client_secret = config['boxAppSettings']['clientSecret'] enterprise_id = config['enterpriseID'] public_key_id = config['boxAppSettings']['appAuth']['publicKeyID'] private_key_text = config['boxAppSettings']['appAuth']['privateKey'] passphrase = config['boxAppSettings']['appAuth']['passphrase'].encode() # 秘密鍵を読み込む private_key = serialization.load_pem_private_key( private_key_text.encode(), password=passphrase, ) # JWTを生成する claims = { 'iss': client_id, 'sub': enterprise_id, 'box_sub_type': 'enterprise', 'aud': 'https://api.box.com/oauth2/token', 'jti': str(time.time()), 'exp': int(time.time()) + 45 } assertion = jwt.encode(claims, private_key, algorithm='RS256', headers={'kid': public_key_id}) # アクセストークンを取得する data = { 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'client_id': client_id, 'client_secret': client_secret, 'assertion': assertion } token_url = 'https://api.box.com/oauth2/token' res = requests.post(token_url, data=data, timeout=30) access_token = res.json()['access_token'] # ファイルをアップロードする url = 'https://upload.box.com/api/2.0/files/content' headers = { 'Authorization': f'Bearer {access_token}' } with open(FILE_PATH, 'rb') as f: files = { 'file': (FILE_NAME, f) } attributes = { 'name': FILE_NAME, 'parent': { 'id': FOLDER_ID } } data = { 'attributes': json.dumps(attributes) } response = requests.post(url, headers=headers, files=files, data=data, timeout=30) - ファイルは Enterprise ID が参照するフォルダ空間にアップロードされます。これは通常のユーザーが見ているフォルダ空間とは異なります。
- 特定ユーザーが見ているフォルダ空間にファイルをアップロードするには as-user ヘッダを用います。
- アプリの [構成] タブで [as-userヘッダーを使用してAPIコールを行う] にチェックをつけて保存し、管理者による承認を行ってください。
- 上記プログラムで HTTP ヘッダを設定している箇所を次のように変更してください。
USER_IDには特定ユーザーのユーザーIDを指定してください。headers = { 'Authorization': f'Bearer {access_token}', 'as-user': 'USER_ID', }
Copyright (C) 2025 杜甫々
https://www.tohoho-web.com/ex/box.html