オープンAPIで使用するためのJWT認証トークンの作成
12 分
オープンAPIリクエストフォーマット
ZEPETOオープンAPIはHTTP経由で呼び出されます。
リクエストにボディが含まれている場合、パラメータはJSON形式で送信する必要があります。 有効なコンテンツタイプの例は以下に示されており、各プログラミング言語のライブラリによって若干の違いがある場合があります。
Content-Type: application/json; charset=utf-8
ZEPETO Studioからアクセスキーとシークレットキーを取得する
JWT認証トークンを作成する前に、ZEPETO Studioコンソールからアクセスキーとシークレットキーを取得する必要があります。
📘 以下のガイドを参照してください。 オープンAPIの管理
JWT認証トークンの作成
ZEPETOオープンAPIは、各リクエストに発行されたアクセスキーとシークレットキーに基づいてJWT(https://jwt.io)形式のトークンを生成し、Authorizationヘッダーに送信します。
署名方法としてHS256が推奨されており、署名に使用する秘密は発行されたシークレットキーです。
JWTトークンのペイロードは次の形式です:
{
"access_key": "発行されたアクセスキー(必須)",
"nonce": "ランダム化されたUUID値(必須)",
"uri_hash": "クエリパラメータを含むURIのハッシュ値、ベースパスは除外(必須)",
"body_hash": "リクエストボディのハッシュ値"
}
- uri_hashは、ベースパスを除くクエリパラメータを含むuriのハッシュ値です。
- body_hashは、リクエストボディが存在する場合にのみペイロードに挿入されるように変換されたjson文字列の値であり、リクエストボディが存在しない場合は省略されます。
- その場合、json文字列のキーと値の間にスペースがあってはなりません。
- uri_hashとbody_hashは、リクエストに送信されたクエリパラメータとリクエストボディと同じ値にハッシュ化されなければなりません。(値の順序も同じでなければなりません。)
- APIコールの回数制限:1分間に最大300回のコールが可能です。
リクエストボディがない場合の例
使用したいAPIに従って、アクセスキー、シークレットキー、ワールドID、URI、およびクエリパラメータを入力してください。
以下の例コードは、DataStorageカテゴリのGet Player Data APIに基づいて記述されています。
Java
String accessKey = "accessKey";
String secretKey = "secretKey";
String worldId = "com.test.world";
String uri = "/datastorage/v1/worlds/" + worldId + "/player-data";
MessageDigest uriHash = MessageDigest.getInstance("SHA-256");
uriHash.update(uri.getBytes(StandardCharsets.UTF_8));
byte[] uriHashBytes = uriHash.digest();
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> payload = new HashMap<>();
payload.put("access_key", accessKey);
payload.put("nonce", UUID.randomUUID().toString());
payload.put("uri_hash", new String(Base64.encodeBase64(uriHashBytes), StandardCharsets.UTF_8));
String jwtToken = Jwts.builder()
.setPayload(objectMapper.writeValueAsString(payload))
.signWith(SignatureAlgorithm.HS256, secretKey.getBytes(StandardCharsets.UTF_8))
.compact();
String authorization = "Bearer " + jwtToken;
Python
import jwt
import uuid
import hashlib
import base64
accessKey = 'accessKey'
secretKey = 'secretKey'
worldId = 'com.test.world'
uri = '/datastorage/v1/worlds/' + worldId + '/player-data?playerId=testplayerid&keys=test'
hash = hashlib.sha256()
hash.update(uri.encode())
payload = {
'access_key': accessKey,
'nonce': str(uuid.uuid4()),
'uri_hash': base64.b64encode(hash.digest()).decode('utf8')
}
jwt_token = jwt.encode(payload, secretKey)
authorization = 'Bearer {}'.format(jwt_token)
NodeJS
import * as jwt from 'jsonwebtoken';
import * as uuid from 'uuid';
import * as crypto from 'crypto-js';
import { Buffer } from 'safe-buffer';
const accessKey = 'accessKey';
const secretKey = 'secretKey';
const worldId = 'com.test.world';
const uri = '/datastorage/v1/worlds/' + worldId + '/player-data?playerId=testplayerid&keys=test';
const hash = crypto.SHA256(uri);
const payload = {
access_key: accessKey,
nonce: uuid.v4(),
uri_hash: Buffer.from(hash.toString(), 'hex').toString('base64')
};
const jwtToken = jwt.sign(payload, secretKey);
const authorization = `Bearer ${jwtToken}`;
リクエストボディがある場合の例
使用したいAPIに応じて、アクセスキー、シークレットキー、ワールドID、URI、およびボディパラメータを入力してください。
以下の例コードは、DataStorageカテゴリのSet Player Data APIに基づいて記述されています。
Java
String accessKey = "アクセスキー";
String secretKey = "シークレットキー";
String worldId = "com.test.world";
String uri = "/datastorage/v1/worlds/" + worldId + "/player-data";
MessageDigest uriHash = MessageDigest.getInstance("SHA-256");
uriHash.update(uri.getBytes(StandardCharsets.UTF_8));
byte[] uriHashBytes = uriHash.digest();
ObjectMapper objectMapper = new ObjectMapper();
PlayerData dataMap = new PlayerData("テスト", "テスト値");
List<PlayerData> dataList = new ArrayList<>();
dataList.add(dataMap);
PlayerDataSetParam param = new PlayerDataSetParam(dataList, "testplayerid");
MessageDigest paramHash = MessageDigest.getInstance("SHA-256");
paramHash.update(objectMapper.writeValueAsString(param).getBytes(StandardCharsets.UTF_8));
byte[] paramHashBytes = paramHash.digest();
Map<String, Object> payload = new HashMap<>();
payload.put("access_key", accessKey);
payload.put("nonce", UUID.randomUUID().toString());
payload.put("uri_hash", new String(Base64.encodeBase64(uriHashBytes), StandardCharsets.UTF_8));
payload.put("body_hash", new String(Base64.encodeBase64(paramHashBytes), StandardCharsets.UTF_8));
String jwtToken = Jwts.builder()
.setPayload(objectMapper.writeValueAsString(payload))
.signWith(SignatureAlgorithm.HS256, secretKey.getBytes(StandardCharsets.UTF_8))
.compact();
String authorization = "ベアラー " + jwtToken;
Python
import jwt
import uuid
import hashlib
import base64
import simplejson as json
accessKey = 'アクセスキー' secretKey = 'シークレットキー'
worldId = 'com.test.world'
uri = '/datastorage/v1/worlds/' + worldId + '/player-data'
hash = hashlib.sha256()
hash.update(uri.encode())
param = {
'playerId': 'testplayerid',
'data':[
{
'key': 'テスト',
'value': 'テスト値'
}
]
}
param_hash = hashlib.sha256()
param_hash.update(json.dumps(param, ensure_ascii=False, encoding='surrogatepass').encode())
payload = {
'access_key': accessKey,
'nonce': str(uuid.uuid4()),
'uri_hash': base64.b64encode(hash.digest()).decode('utf8'),
'body_hash': base64.b64encode(param_hash.digest()).decode('utf8')
}
jwt_token = jwt.encode(payload, secretKey)
authorization = 'ベアラー {}'.format(jwt_token)
NodeJS
import * as jwt from 'jsonwebtoken';
import * as uuid from 'uuid';
import * as crypto from 'crypto-js';
import { Buffer } from 'safe-buffer';
const accessKey = 'accessKey';
const secretKey = 'secretKey';
const worldId = 'com.test.world';
const uri = '/datastorage/v1/worlds/' + worldId + '/player-data';
const hash = crypto.SHA256(uri);
const param = {
playerId: 'testplayerid',
data: [
{
value: 'test value',
key: 'test'
}
]
};
const paramHash = crypto.SHA256(JSON.stringify(param,null,0));
const payload = {
access_key: accessKey,
nonce: uuid.v4(),
uri_hash: Buffer.from(hash.toString(), 'hex').toString('base64'),
body_hash: Buffer.from(paramHash.toString(), 'hex').toString('base64')
};
const jwtToken = jwt.sign(payload, secretKey);
const authorization = `Bearer ${jwtToken}`;
❗️ 注意
- OpenAPIは、別のWebまたはアプリで使用するために提供される機能です。
- 現在、ZEPETOサーバースクリプトはZEPETO Open API呼び出しを行うことができません。
- ZEPETOマルチプレイヤーでOpen API呼び出しを行いたい場合、以下の方法をお勧めします:
- Open APIと通信して必要なビジネスロジックを実行するために、別のサーバーを設定します。
- ZEPETOサーバー内で直接通信するために、設定したサーバーと通信するためにhttpServiceパッケージを使用します。
- HTTP認証ヘッダーを使用するなど、サーバー間で比較的簡単な認証方法を実装して、ZEPETOサーバーによってサポートされている機能内での呼び出しを可能にします。