รับโทเค็นการให้สิทธิ์

โทเค็นคืออะไร

Fleet Engine กำหนดให้ใช้ JSON Web Token (JWT) ที่ลงนามโดย บัญชีบริการที่เหมาะสมสำหรับการเรียกเมธอด API จาก low-Trust สภาพแวดล้อมการทำงาน สภาพแวดล้อมที่มีความน่าเชื่อถือต่ำรวมถึงสมาร์ทโฟนและเบราว์เซอร์ต่างๆ JWT จะทำงานในเซิร์ฟเวอร์ของคุณ ซึ่งเป็นสภาพแวดล้อมที่เชื่อถือได้อย่างสมบูรณ์ JWT ลงชื่อ เข้ารหัส และส่งต่อไปยังไคลเอ็นต์สำหรับเซิร์ฟเวอร์ต่อๆ ไป การโต้ตอบต่างๆ จนกว่าหมดอายุหรือใช้ไม่ได้

แบ็กเอนด์ของคุณควรตรวจสอบสิทธิ์และให้สิทธิ์กับ Fleet Engine โดยใช้ กลไก Application Default Credentials แบบมาตรฐาน สร้าง อย่าลืมใช้ JWT ที่ลงชื่อโดยบัญชีบริการที่เหมาะสม สำหรับ รายการของบทบาทบัญชีบริการ โปรดดูบทบาทบัญชีบริการ Fleet Engine ในข้อมูลพื้นฐานเกี่ยวกับ Fleet Engine

สำหรับข้อมูลเพิ่มเติมเกี่ยวกับ JSON Web Token โปรดดู JSON Web Token ใน Fleet Engine Essentials

วิธีที่ลูกค้าจะได้รับโทเค็น

เมื่อคนขับหรือผู้บริโภคเข้าสู่ระบบแอปของคุณโดยใช้ ข้อมูลเข้าสู่ระบบการตรวจสอบสิทธิ์ การอัปเดตที่มาจากอุปกรณ์จะต้องใช้ โทเค็นการให้สิทธิ์ที่เหมาะสม ซึ่งจะสื่อสารกับ Fleet Engine สิทธิ์ของแอป

ในฐานะนักพัฒนาซอฟต์แวร์ การใช้งานของลูกค้าของคุณควรช่วยให้คุณสามารถ ให้ทำดังนี้

  • เรียก JSON Web Token จากเซิร์ฟเวอร์ของคุณ
  • ใช้โทเค็นซ้ำจนกว่าจะหมดอายุเพื่อลดการรีเฟรชโทเค็น
  • โปรดรีเฟรชโทเค็นเมื่อหมดอายุ

โปรโตคอล GMTDAuthorization ดึงโทเค็นเว็บ JSON ณ เวลาที่อัปเดตตำแหน่ง อิงตามออบเจ็กต์ GMTD AuthorizationContext SDK ต้องสร้างแพ็กเกจโทเค็นที่มีข้อมูลอัปเดตเพื่อส่งไปยัง Fleet Engine โปรดตรวจสอบว่าการใช้งานฝั่งเซิร์ฟเวอร์สามารถออกโทเค็นได้ก่อน การเริ่มต้น SDK

โปรดดูรายละเอียดโทเค็นที่ Fleet Engine คาดหวังที่ ออกโทเค็นเว็บ JSON สำหรับ Fleet Engine

รหัสผู้ให้บริการจะเหมือนกับรหัสโปรเจ็กต์ของ Google Cloud โปรเจ็กต์ สำหรับข้อมูลเกี่ยวกับการตั้งค่าโปรเจ็กต์ Google Cloud โปรดดู สร้างโปรเจ็กต์ Fleet Engine

ตัวอย่างตัวดึงข้อมูลโทเค็นการตรวจสอบสิทธิ์

ตัวอย่างต่อไปนี้ใช้ผู้ให้บริการโทเค็นการให้สิทธิ์

Swift

/*
 * SampleAccessTokenProvider.swift
 */
import GoogleRidesharingConsumer

private let providerURL = "INSERT_YOUR_TOKEN_PROVIDER_URL"

class SampleAccessTokenProvider: NSObject, GMTCAuthorization {
  private struct AuthToken {
    // The cached trip token.
    let token: String
    // Keep track of when the token expires for caching.
    let expiration: TimeInterval
    // Keep track of the trip ID the cached token is for.
    let tripID: String
  }

  enum AccessTokenError: Error {
    case missingAuthorizationContext
    case missingData
  }

  private var authToken: AuthToken?

  func fetchToken(
    with authorizationContext: GMTCAuthorizationContext?,
    completion: @escaping GMTCAuthTokenFetchCompletionHandler
  ) {
    // Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
    guard let authorizationContext = authorizationContext else {
      completion(nil, AccessTokenError.missingAuthorizationContext)
      return
    }
    let tripID = authorizationContext.tripID

    // If appropriate, use the cached token.
    if let authToken = authToken,
      authToken.expiration > Date.now.timeIntervalSince1970 && authToken.tripID == tripID
    {
      completion(authToken.token, nil)
      return
    }

    // Otherwise, try to fetch a new token from your server.
    let request = URLRequest(url: URL(string: providerURL))
    let task = URLSession.shared.dataTask(with: request) { [weak self] data, _, error in
      guard let strongSelf = self else { return }
      guard error == nil else {
        completion(nil, error)
        return
      }

      // Replace the following key values with the appropriate keys based on your
      // server's expected response.
      let tripTokenKey = "TRIP_TOKEN_KEY"
      let tokenExpirationKey = "TOKEN_EXPIRATION"
      guard let data = data,
        let fetchData = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
        let token = fetchData[tripTokenKey] as? String,
        let expiration = fetchData[tokenExpirationKey] as? Double
      else {
        completion(nil, AccessTokenError.missingData)
        return
      }

      strongSelf.authToken = AuthToken(token: token, expiration: expiration, tripID: tripID)
      completion(token, nil)
    }
    task.resume()
  }
}

Objective-C

/*
 * SampleAccessTokenProvider.h
 */
#import <Foundation/Foundation.h>
#import <GoogleRidesharingConsumer/GoogleRidesharingConsumer.h>

NS_ASSUME_NONNULL_BEGIN

@interface SampleAccessTokenProvider : NSObject <GMTCAuthorization>

@end

NS_ASSUME_NONNULL_END

/*
 * SampleAccessTokenProvider.m
 */
#import "SampleAccessTokenProvider.h"
#import "GoogleRidesharingConsumer/GoogleRidesharingConsumer.h"

static NSString *const PROVIDER_URL = @"INSERT_YOUR_TOKEN_PROVIDER_URL";

// SampleAccessTokenProvider.m
@implementation SampleAccessTokenProvider {
  // The cached token with claims to the current trip.
  NSString *_cachedTripToken;
  // Keep track of the Trip ID the cached token is for.
  NSString *_lastKnownTripID;
  // Keep track of when tokens expire for caching.
  NSTimeInterval _tokenExpiration;
}

- (void)fetchTokenWithContext:(nullable GMTCAuthorizationContext *)authorizationContext
                   completion:(nonnull GMTCAuthTokenFetchCompletionHandler)completion {
  // Get the trip ID from the authorizationContext. This is set by the Consumer SDK.
  NSString *tripID = authorizationContext.tripID;

  // Clear cached trip token if trip ID has changed.
  if (![_lastKnownTripID isEqual:tripID]) {
    _tokenExpiration = 0.0;
    _cachedTripToken = nil;
  }
  _lastKnownTripID = tripID;

  // Clear cached tripToken if it has expired.
  if ([[NSDate date] timeIntervalSince1970] > _tokenExpiration) {
    _cachedTripToken = nil;
  }

  // If appropriate, use the cached token.
  if (_cachedTripToken) {
    completion(_cachedTripToken, nil);
    return;
  }
  // Otherwise, try to fetch a new token from your server.
  NSURL *requestURL = [NSURL URLWithString:PROVIDER_URL];
  NSMutableURLRequest *request =
      [[NSMutableURLRequest alloc] initWithURL:requestURL];
  request.HTTPMethod = @"GET";

  // Replace the following key values with the appropriate keys based on your
  // server's expected response.
  NSString *tripTokenKey = @"TRIP_TOKEN_KEY";
  NSString *tokenExpirationKey = @"TOKEN_EXPIRATION";

  __weak typeof(self) weakSelf = self;
  void (^handler)(NSData *_Nullable data, NSURLResponse *_Nullable response,
                  NSError *_Nullable error) =
      ^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
        typeof(self) strongSelf = weakSelf;
        if (error) {
          completion(nil, error);
          return;
        }

        NSError *JSONError;
        NSMutableDictionary *JSONResponse =
            [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&JSONError];

        if (JSONError) {
          completion(nil, JSONError);
          return;
        } else {
          // Sample code only. No validation logic.
          id expirationData = JSONResponse[tokenExpirationKey];
          if ([expirationData isKindOfClass:[NSNumber class]]) {
            NSTimeInterval expirationTime = ((NSNumber *)expirationData).doubleValue;
            strongSelf->_tokenExpiration = [[NSDate date] timeIntervalSince1970] + expirationTime;
          }
          strongSelf->_cachedTripToken = JSONResponse[tripTokenKey];
          completion(JSONResponse[tripTokenKey], nil);
        }
      };
  NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
  NSURLSession *mainQueueURLSession =
      [NSURLSession sessionWithConfiguration:config delegate:nil
                               delegateQueue:[NSOperationQueue mainQueue]];
  NSURLSessionDataTask *task = [mainQueueURLSession dataTaskWithRequest:request completionHandler:handler];
  [task resume];
}

@end

ขั้นต่อไปคืออะไร

เริ่มต้น SDK ของผู้บริโภค