승인 토큰 가져오기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
토큰이란 무엇인가요?
Fleet Engine에서는 신뢰도가 낮은 환경(스마트폰 및 브라우저)에서 API 메서드를 호출할 때 JSON 웹 토큰(JWT)을 사용해야 합니다.
JWT는 서버에서 생성되고 서명, 암호화되어 만료되거나 더 이상 유효하지 않을 때까지 후속 서버 상호작용을 위해 클라이언트에 전달됩니다.
주요 세부정보
JSON 웹 토큰에 관한 자세한 내용은 Fleet Engine 필수사항의 JSON 웹 토큰을 참고하세요.
클라이언트는 어떻게 토큰을 받나요?
드라이버 또는 소비자가 적절한 승인 사용자 인증 정보를 사용하여 앱에 로그인하면 해당 기기에서 발행된 업데이트는 앱의 권한을 Fleet Engine에 전달하는 적절한 승인 토큰을 사용해야 합니다.
개발자로서 클라이언트 구현은 다음 기능을 제공해야 합니다.
- 서버에서 JSON 웹 토큰을 가져옵니다.
- 토큰이 만료될 때까지 재사용하여 토큰 새로고침을 최소화합니다.
- 토큰이 만료되면 토큰을 새로고침합니다.
AuthTokenFactory
클래스는 위치 업데이트 시간에 승인 토큰을 생성합니다. SDK는 Fleet Engine으로 전송할 업데이트 정보와 함께 토큰을 패키징해야 합니다. SDK를 초기화하기 전에 서버 측 구현에서 토큰을 발급할 수 있는지 확인하세요.
Fleet Engine 서비스에서 예상하는 토큰에 관한 자세한 내용은 Fleet Engine용 JSON 웹 토큰 발급을 참고하세요.
승인 토큰 가져오기의 예
다음은 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 초기화
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-31(UTC)
[null,null,["최종 업데이트: 2025-08-31(UTC)"],[[["\u003cp\u003eFleet Engine utilizes JSON Web Tokens (JWTs) for API method calls originating from low-trust environments like smartphones and browsers, requiring these tokens to be signed by an appropriate service account on your server.\u003c/p\u003e\n"],["\u003cp\u003eClients, after logging in, must employ authorization tokens for updates, which are fetched from your server, reused until expiration, and then refreshed to maintain communication with Fleet Engine.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eAuthTokenFactory\u003c/code\u003e class generates authorization tokens for location updates, which are then packaged with the update information by the SDK and sent to Fleet Engine, requiring a server-side implementation for token issuance.\u003c/p\u003e\n"],["\u003cp\u003eAn example \u003ccode\u003eAuthTokenFactory\u003c/code\u003e implementation demonstrates fetching tokens in JSON format from an authorization server, saving them for reuse, and refreshing them within 10 minutes of expiry to ensure continuous authorization.\u003c/p\u003e\n"]]],[],null,["What is a token?\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\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\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 on-demand trips services](/maps/documentation/mobility/fleet-engine/essentials/client-libraries-trips).\n\nWhat's next\n\n[Initialize the Driver SDK](/maps/documentation/mobility/driver-sdk/on-demand/android/initialize-sdk)"]]