Nhận mã thông báo uỷ quyền

Mã thông báo là gì?

Fleet Engine yêu cầu sử dụng Mã thông báo web JSON (JWT) được ký bởi tài khoản dịch vụ thích hợp cho các lệnh gọi phương thức API từ độ tin cậy thấp môi trường. Môi trường đáng tin cậy thấp bao gồm điện thoại thông minh và trình duyệt. JWT bắt nguồn từ máy chủ của bạn – một môi trường hoàn toàn đáng tin cậy. JWT được ký, mã hoá và chuyển đến máy khách để máy chủ cho đến khi hết hạn hoặc không còn hợp lệ.

Phần phụ trợ của bạn phải xác thực và uỷ quyền dựa trên Fleet Engine bằng cách sử dụng cơ chế Thông tin đăng nhập mặc định của ứng dụng tiêu chuẩn. Nhãn hiệu sử dụng JWT đã được ký bằng một tài khoản dịch vụ thích hợp. Đối với danh sách vai trò trong tài khoản dịch vụ, hãy xem các vai trò trong tài khoản dịch vụ Fleet Engine trong Fleet Engine cơ bản.

Để biết thêm thông tin về Mã thông báo web JSON, hãy xem Mã thông báo web JSON trong Kiến thức cơ bản về động cơ cho phương tiện vận chuyển.

Khách hàng nhận mã thông báo bằng cách nào?

Sau khi người lái xe hoặc người dùng đăng nhập vào ứng dụng của bạn bằng thông tin xác thực, mọi bản cập nhật được phát hành từ thiết bị đó phải sử dụng mã thông báo uỷ quyền thích hợp để thông báo cho Fleet Engine cho ứng dụng.

Với tư cách là nhà phát triển, việc triển khai cho khách hàng của bạn phải mang lại khả năng hãy làm như sau:

  • Tìm nạp Mã thông báo web JSON qua máy chủ của bạn.
  • Hãy sử dụng lại mã thông báo cho đến khi hết hạn để giảm thiểu số lượt làm mới mã thông báo.
  • Làm mới mã thông báo khi mã này hết hạn.

Giao thức GMTDAuthorization tìm nạp mã thông báo Web JSON tại thời điểm cập nhật vị trí dựa trên đối tượng GMTD AuthorizationContext. SDK phải đóng gói mã thông báo cùng với thông tin cập nhật để gửi đến Fleet Engine. Đảm bảo rằng phương thức triển khai phía máy chủ của bạn có thể phát hành mã thông báo trước khởi chạy SDK.

Để biết thông tin chi tiết về các mã thông báo mà Fleet Engine dự kiến, hãy xem Phát hành mã thông báo web JSON cho Fleet Engine.

Mã nhà cung cấp giống với Mã dự án trên Google Cloud của bạn Dự án. Để biết thông tin về cách thiết lập dự án Google Cloud, hãy xem Tạo dự án Fleet Engine.

Ví dụ về trình tìm nạp mã xác thực

Ví dụ sau đây minh hoạ cách triển khai GMTDAuthorization giao thức.

Swift

import GoogleRidesharingDriver

private let providerURL = "INSERT_YOUR_TOKEN_PROVIDER_URL"

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

  enum AccessTokenError: Error {
    case missingAuthorizationContext
    case missingData
  }

  private var authToken: AuthToken?

  func fetchToken(
    with authorizationContext: GMTDAuthorizationContext?,
    completion: @escaping GMTDAuthTokenFetchCompletionHandler
  ) {
    // Get the vehicle ID from the authorizationContext. This is set by the Driver SDK.
    guard let authorizationContext = authorizationContext else {
      completion(nil, AccessTokenError.missingAuthorizationContext)
      return
    }
    let vehicleID = authorizationContext.vehicleID

    // If appropriate, use the cached token.
    if let authToken = authToken,
      authToken.expiration > Date.now.timeIntervalSince1970 && authToken.vehicleID == vehicleID
    {
      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 vehicleTokenKey = "VEHICLE_TOKEN_KEY"
      let tokenExpirationKey = "TOKEN_EXPIRATION"
      guard let data = data,
        let fetchData = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
        let token = fetchData[vehicleTokenKey] as? String,
        let expiration = fetchData[tokenExpirationKey] as? Double
      else {
        completion(nil, AccessTokenError.missingData)
        return
      }

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

Objective-C

#import "SampleAccessTokenProvider.h"
#import <GoogleRidesharingDriver/GoogleRidesharingDriver.h>

// SampleAccessTokenProvider.h
@interface SampleAccessTokenProvider : NSObject<GMTDAuthorization>
@end

static NSString *const PROVIDER_URL = @"INSERT_YOUR_TOKEN_PROVIDER_URL";

// SampleAccessTokenProvider.m
@implementation SampleAccessTokenProvider{
  // The cached vehicle token.
  NSString *_cachedVehicleToken;
  // Keep track of the vehicle ID the cached token is for.
  NSString *_lastKnownVehicleID;
  // Keep track of when tokens expire for caching.
  NSTimeInterval _tokenExpiration;
}

-   (void)fetchTokenWithContext:(nullable GMTDAuthorizationContext *)authorizationContext
                   completion:(nonnull GMTDAuthTokenFetchCompletionHandler)completion {

  if (!completion) {
   NSAssert(NO, @"%s encountered an unexpected nil completion.", __PRETTY_FUNCTION__);
   return;
  }

  // Get the vehicle ID from the authorizationContext. This is set by the Driver SDK.
  NSString *vehicleID = authorizationContext.vehicleID;
  if (!vehicleID) {
    NSAssert(NO, @"Vehicle ID is missing from authorizationContext.");
    return;
  }

  // Clear cached vehicle token if vehicle ID has changed.
  if (![_lastKnownVehicleID isEqual:vehicleID]) {
    _tokenExpiration = 0.0;
    _cachedVehicleToken = nil;
  }
  _lastKnownVehicleID = vehicleID;

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

  // If appropriate, use the cached token.
  if (_cachedVehicleToken) {
    completion(_cachedVehicleToken, 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 *vehicleTokenKey = @"VEHICLE_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->_cachedVehicleToken = JSONResponse[vehicleTokenKey];
          completion(JSONResponse[vehicleTokenKey], 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

Các bước tiếp theo

Khởi chạy SDK trình điều khiển