Consumer SDK는 JSON 웹 토큰을 사용한 승인을 제공합니다. JSON 웹 토큰(JWT)은 서비스에 대한 하나 이상의 클레임을 제공하는 승인 토큰입니다.
Consumer SDK는 애플리케이션에서 제공하는 JSON 웹 토큰을 사용하여 Fleet Engine과 통신합니다. Fleet Engine 서버에서 예상하는 토큰에 관한 자세한 내용은 JSON 웹 토큰 및 JSON 웹 토큰 발급을 참고하세요.
인증 토큰은 다음 Fleet Engine 서비스에 대한 액세스를 제공합니다.
TripService
- 소비자 SDK에 차량 위치, 경로, 예상 도착 시간 등 이동 세부정보에 대한 액세스 권한을 부여합니다. 이동 서비스의 승인 토큰에는 토큰의authorization
헤더에tripid:TRIP_ID
클레임이 포함되어야 합니다. 여기서TRIP_ID
은 공유되는 주문형 이동의 이동 ID입니다.VehicleService
- 차량 밀도 레이어를 표시하고 픽업 지점 예상 도착 시간을 추정하기 위해 Consumer SDK에 대략적인 차량 위치에 관한 정보를 제공합니다. 소비자 SDK는 대략적인 위치만 사용하므로 차량 서비스의 승인 토큰에는vehicleid
클레임이 필요하지 않습니다.
토큰이란 무엇인가요?
Fleet Engine에서는 신뢰도가 낮은 환경(스마트폰 및 브라우저)에서 API 메서드를 호출할 때 JSON 웹 토큰(JWT)을 사용해야 합니다.
JWT는 서버에서 생성되고 서명, 암호화되어 만료되거나 더 이상 유효하지 않을 때까지 후속 서버 상호작용을 위해 클라이언트에 전달됩니다.
주요 세부정보
- 애플리케이션 기본 사용자 인증 정보를 사용하여 Fleet Engine에 대해 인증하고 승인합니다.
- 적절한 서비스 계정을 사용하여 JWT에 서명합니다. Fleet Engine 기본사항의 Fleet Engine 서비스 계정 역할을 참고하세요.
JSON 웹 토큰에 관한 자세한 내용은 Fleet Engine 필수사항의 JSON 웹 토큰을 참고하세요.
클라이언트는 어떻게 토큰을 받나요?
드라이버 또는 소비자가 적절한 승인 사용자 인증 정보를 사용하여 앱에 로그인하면 해당 기기에서 발행된 업데이트는 앱의 권한을 Fleet Engine에 전달하는 적절한 승인 토큰을 사용해야 합니다.
개발자로서 클라이언트 구현은 다음 기능을 제공해야 합니다.
- 서버에서 JSON 웹 토큰을 가져옵니다.
- 토큰이 만료될 때까지 재사용하여 토큰 새로고침을 최소화합니다.
- 토큰이 만료되면 토큰을 새로고침합니다.
AuthTokenFactory
클래스는 위치 업데이트 시간에 승인 토큰을 생성합니다. SDK는 Fleet Engine에 전송할 업데이트 정보와 함께 토큰을 패키징해야 합니다. SDK를 초기화하기 전에 서버 측 구현에서 토큰을 발급할 수 있는지 확인하세요.
Fleet Engine 서비스에서 예상하는 토큰에 관한 자세한 내용은 Fleet Engine용 JSON 웹 토큰 발급을 참고하세요.
승인 토큰 가져오기의 예
다음 코드 예는 승인 토큰 콜백을 구현하는 방법을 보여줍니다.
자바
class JsonAuthTokenFactory implements AuthTokenFactory {
private static final String TOKEN_URL =
"https://yourauthserver.example/token";
private static class CachedToken {
String tokenValue;
long expiryTimeMs;
String tripId;
}
private CachedToken token;
/*
* This method is called on a background thread. Blocking is OK. However, be
* aware that no information can be obtained from Fleet Engine until this
* method returns.
*/
@Override
public String getToken(AuthTokenContext context) {
// If there is no existing token or token has expired, go get a new one.
String tripId = context.getTripId();
if (tripId == null) {
throw new RuntimeException("Trip ID is missing from AuthTokenContext");
}
if (token == null || System.currentTimeMillis() > token.expiryTimeMs ||
!tripId.equals(token.tripId)) {
token = fetchNewToken(tripId);
}
return token.tokenValue;
}
private static CachedToken fetchNewToken(String tripId) {
String url = TOKEN_URL + "/" + tripId;
CachedToken token = new CachedToken();
try (Reader r = new InputStreamReader(new URL(url).openStream())) {
com.google.gson.JsonObject obj
= com.google.gson.JsonParser.parseReader(r).getAsJsonObject();
token.tokenValue = obj.get("ServiceToken").getAsString();
token.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 5 minutes from that time.
*/
token.expiryTimeMs -= 5 * 60 * 1000;
} catch (IOException e) {
/*
* It's OK to throw exceptions here. The error listeners will receive the
* error thrown here.
*/
throw new RuntimeException("Could not get auth token", e);
}
token.tripId = tripId;
return token;
}
}
Kotlin
class JsonAuthTokenFactory : AuthTokenFactory() {
private var token: CachedToken? = null
/*
* This method is called on a background thread. Blocking is OK. However, be
* aware that no information can be obtained from Fleet Engine until this
* method returns.
*/
override fun getToken(context: AuthTokenContext): String {
// If there is no existing token or token has expired, go get a new one.
val tripId =
context.getTripId() ?:
throw RuntimeException("Trip ID is missing from AuthTokenContext")
if (token == null || System.currentTimeMillis() > token.expiryTimeMs ||
tripId != token.tripId) {
token = fetchNewToken(tripId)
}
return token.tokenValue
}
class CachedToken(
var tokenValue: String? = "",
var expiryTimeMs: Long = 0,
var tripId: String? = "",
)
private companion object {
const val TOKEN_URL = "https://yourauthserver.example/token"
fun fetchNewToken(tripId: String) {
val url = "$TOKEN_URL/$tripId"
val token = CachedToken()
try {
val reader = InputStreamReader(URL(url).openStream())
reader.use {
val obj = com.google.gson.JsonParser.parseReader(r).getAsJsonObject()
token.tokenValue = obj.get("ServiceToken").getAsString()
token.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 5 minutes from that time.
*/
token.expiryTimeMs -= 5 * 60 * 1000
}
} catch (e: IOException) {
/*
* It's OK to throw exceptions here. The error listeners will receive the
* error thrown here.
*/
throw RuntimeException("Could not get auth token", e)
}
token.tripId = tripId
return token
}
}
}