認証トークンを取得する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
トークンとは
Fleet Engine では、スマートフォンやブラウザなどの信頼度の低い環境からの API メソッド呼び出しに JSON Web Token(JWT)を使用する必要があります。
JWT はサーバーで生成され、署名と暗号化が行われてクライアントに渡されます。有効期限が切れるか無効になるまで、以降のサーバーとのやり取りで使用されます。
主な詳細
JSON ウェブトークンの詳細については、Fleet Engine の基本の JSON ウェブトークンをご覧ください。
クライアントがトークンを取得する方法
ドライバーまたは消費者が適切な認証情報を使用してアプリにログインすると、そのデバイスから発行される更新はすべて、適切な認証トークンを使用する必要があります。これにより、アプリの権限が Fleet Engine に伝達されます。
デベロッパーとして、クライアント実装で次の操作を行えるようにする必要があります。
- サーバーから JSON ウェブトークンを取得します。
- トークンが期限切れになるまで再利用して、トークンの更新を最小限に抑えます。
- トークンの有効期限が切れたら更新します。
AuthTokenFactory
クラスは、位置情報の更新時に承認トークンを生成します。SDK は、トークンを更新情報とともにパッケージ化して Fleet Engine に送信する必要があります。SDK を初期化する前に、サーバーサイドの実装でトークンを発行できることを確認してください。
Fleet Engine サービスで想定されるトークンの詳細については、Fleet Engine の JSON Web Token を発行するをご覧ください。
認証トークン フェッチャーの例
AuthTokenFactory
のスケルトン実装を次に示します。
class JsonAuthTokenFactory implements AuthTokenFactory {
private String vehicleServiceToken; // initially null
private long expiryTimeMs = 0;
private String vehicleId;
// This method is called on a thread whose only responsibility is to send
// location updates. Blocking is OK, but just know that no location updates
// can occur until this method returns.
@Override
public String getToken(AuthTokenContext authTokenContext) {
String vehicleId = requireNonNull(context.getVehicleId());
if (System.currentTimeMillis() > expiryTimeMs || !vehicleId.equals(this.vehicleId)) {
// The token has expired, go get a new one.
fetchNewToken(vehicleId);
}
return vehicleServiceToken;
}
private void fetchNewToken(String vehicleId) {
String url = "https://yourauthserver.example/token/" + vehicleId;
try (Reader r = new InputStreamReader(new URL(url).openStream())) {
com.google.gson.JsonObject obj
= com.google.gson.JsonParser.parseReader(r).getAsJsonObject();
vehicleServiceToken = obj.get("VehicleServiceToken").getAsString();
expiryTimeMs = obj.get("TokenExpiryMs").getAsLong();
// The expiry time could be an hour from now, but just to try and avoid
// passing expired tokens, we subtract 10 minutes from that time.
expiryTimeMs -= 10 * 60 * 1000;
this.vehicleId = vehicleId;
} catch (IOException e) {
// It's OK to throw exceptions here. The StatusListener you passed to
// create the DriverContext class will be notified and passed along the failed
// update warning.
throw new RuntimeException("Could not get auth token", e);
}
}
}
この実装では、組み込みの Java HTTP クライアントを使用して、JSON 形式のトークンを認可サーバーから取得します。クライアントは、再利用のためにトークンを保存し、古いトークンの有効期限が 10 分以内になった場合はトークンを再取得します。
実装によっては、バックグラウンド スレッドを使用してトークンを更新するなど、異なる処理を行う場合があります。
Fleet Engine で使用可能なクライアント ライブラリについては、スケジュール設定されたタスク サービスのクライアント ライブラリをご覧ください。
次のステップ
Driver SDK を初期化する
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-08-31 UTC。
[null,null,["最終更新日 2025-08-31 UTC。"],[[["\u003cp\u003eFleet Engine requires JSON Web Tokens (JWTs) for API calls from low-trust environments like smartphones and browsers, which are generated on your server and passed to the client.\u003c/p\u003e\n"],["\u003cp\u003eYour server should authenticate with Fleet Engine using Application Default Credentials and issue JWTs signed by an appropriate service account.\u003c/p\u003e\n"],["\u003cp\u003eClients must fetch, reuse, and refresh these JWTs to authorize their interactions with Fleet Engine, ensuring they have the necessary permissions.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eAuthTokenFactory\u003c/code\u003e class facilitates the process of generating and managing authorization tokens within your client application.\u003c/p\u003e\n"],["\u003cp\u003eRefer to the provided links for detailed information about JWTs, service accounts, and client libraries.\u003c/p\u003e\n"]]],[],null,["# Get authorization tokens\n\nWhat is a token?\n----------------\n\nFleet Engine requires the use of **JSON Web Tokens** (JWTs) for API method calls\nfrom **low-trust environments**: smartphones and browsers.\n\nA JWT originates on your server, is signed, encrypted, and passed to the client\nfor subsequent server interactions until it expires or is no longer valid.\n\n**Key details**\n\n- Use [Application Default Credentials](https://google.aip.dev/auth/4110) to authenticate and authorize against Fleet Engine.\n- Use an appropriate service account to sign JWTs. See [Fleet Engine serviceaccount](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/service-accounts#fleet_engine_service_account_roles) roles in **Fleet Engine Basics**.\n\nFor more information about JSON Web Tokens, see [JSON Web Tokens](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/jwt) in\n**Fleet Engine Essentials**.\n\nHow do clients get tokens?\n--------------------------\n\nOnce a driver or consumer logs in to your app using the appropriate\nauthorization credentials, any updates issued from that device must use\nappropriate authorization tokens, which communicates to Fleet Engine the\npermissions for the app.\n\nAs the developer, your client implementation should provide the ability to do\nthe following:\n\n- Fetch a JSON Web Token from your server.\n- Reuse the token until it expires to minimize token refreshes.\n- Refresh the token when it expires.\n\nThe `AuthTokenFactory` class generates authorization tokens at location update\ntime. The SDK must package the tokens with the update\ninformation to send to Fleet Engine. Make sure that your server-side\nimplementation can issue tokens before initializing the SDK.\n\nFor details of the tokens expected by the Fleet Engine service, see [Issue JSON\nWeb Tokens](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt) for Fleet Engine.\n\nExample of an authorization token fetcher\n-----------------------------------------\n\nHere is a skeleton implementation of an `AuthTokenFactory`: \n\n class JsonAuthTokenFactory implements AuthTokenFactory {\n private String vehicleServiceToken; // initially null\n private long expiryTimeMs = 0;\n private String vehicleId;\n\n // This method is called on a thread whose only responsibility is to send\n // location updates. Blocking is OK, but just know that no location updates\n // can occur until this method returns.\n @Override\n public String getToken(AuthTokenContext authTokenContext) {\n String vehicleId = requireNonNull(context.getVehicleId());\n\n if (System.currentTimeMillis() \u003e expiryTimeMs || !vehicleId.equals(this.vehicleId)) {\n // The token has expired, go get a new one.\n fetchNewToken(vehicleId);\n }\n\n return vehicleServiceToken;\n }\n\n private void fetchNewToken(String vehicleId) {\n String url = \"https://yourauthserver.example/token/\" + vehicleId;\n\n try (Reader r = new InputStreamReader(new URL(url).openStream())) {\n com.google.gson.JsonObject obj\n = com.google.gson.JsonParser.parseReader(r).getAsJsonObject();\n vehicleServiceToken = obj.get(\"VehicleServiceToken\").getAsString();\n expiryTimeMs = obj.get(\"TokenExpiryMs\").getAsLong();\n\n // The expiry time could be an hour from now, but just to try and avoid\n // passing expired tokens, we subtract 10 minutes from that time.\n expiryTimeMs -= 10 * 60 * 1000;\n this.vehicleId = vehicleId;\n } catch (IOException e) {\n // It's OK to throw exceptions here. The StatusListener you passed to\n // create the DriverContext class will be notified and passed along the failed\n // update warning.\n throw new RuntimeException(\"Could not get auth token\", e);\n }\n }\n }\n\nThis particular implementation uses the built-in Java HTTP client to fetch a\ntoken in JSON format from the authorization server. The client saves the token\nfor reuse and re-fetches the token if the old token is within 10 minutes of its\nexpiry time.\n\nYour implementation may do things differently, such as using a background thread\nto refresh tokens.\n\nFor the available client libraries for Fleet Engine, see\n[Client libraries for scheduled tasks services](/maps/documentation/mobility/fleet-engine/essentials/client-libraries-tasks).\n\nWhat's next\n-----------\n\n[Initialize the Driver SDK](/maps/documentation/mobility/driver-sdk/scheduled/android/initialize-sdk)"]]