

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 如何使用身分驗證協助程式
<a name="how-to-auth-helper"></a>

本節提供有關身分驗證協助程式的其他資訊。

## Web
<a name="loc-sdk-auth-web"></a>

Amazon Location JavaScript 身分驗證公用程式可協助從 JavaScript 應用程式進行 Amazon Location Service API 呼叫時進行身分驗證。這些公用程式特別支援使用 API 金鑰或 Amazon Cognito 進行身分驗證。

**安裝**
+ 使用 NPM 安裝此程式庫：

  ```
  npm install @aws/amazon-location-utilities-auth-helper
  ```
+ 若要直接在瀏覽器中使用它，請在 HTML 檔案中包含下列項目：

  ```
  <script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script>
  ```

### Usage
<a name="loc-sdk-auth-usage"></a>

若要使用身分驗證協助程式，請匯入程式庫並呼叫必要的公用程式函數。此程式庫支援驗證來自 Amazon Location Service SDKs請求，包括 [Maps](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-maps/)、[Places](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-places/) 和 [Routes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/geo-routes/) 獨立SDKs，以及使用 [MapLibre GL JS ](https://github.com/maplibre/maplibre-gl-js)轉譯地圖。

**使用 模組**

此範例示範如何使用獨立的 Places SDK，讓請求透過 API 金鑰進行身分驗證：

```
npm install @aws-sdk/client-geo-places

import { GeoPlacesClient, GeocodeCommand } from "@aws-sdk/client-geo-places";
import { withAPIKey } from "@aws/amazon-location-utilities-auth-helper";

const authHelper = withAPIKey("<API Key>", "<Region>");
const client = new GeoPlacesClient(authHelper.getClientConfig());

const input = { ... };
const command = new GeocodeCommand(input);
const response = await client.send(command);
```

此範例示範如何使用獨立的 Routes SDK，以 API 金鑰對請求進行身分驗證：

```
npm install @aws-sdk/geo-routes-client

import { GeoRoutesClient, CalculateRoutesCommand } from "@aws-sdk/geo-routes-client";
import { withAPIKey } from "@aws/amazon-location-utilities-auth-helper";

const authHelper = withAPIKey("<API Key>", "<Region>");
const client = new GeoRoutesClient(authHelper.getClientConfig());

const input = { ... };
const command = new CalculateRoutesCommand(input);
const response = await client.send(command);
```

此範例使用 Location SDK 搭配 API 金鑰身分驗證：

```
npm install @aws-sdk/client-location

import { LocationClient, ListGeofencesCommand } from "@aws-sdk/client-location";
import { withAPIKey } from "@aws/amazon-location-utilities-auth-helper";

const authHelper = withAPIKey("<API Key>", "<Region>");
const client = new LocationClient(authHelper.getClientConfig());

const input = { ... };
const command = new ListGeofencesCommand(input);
const response = await client.send(command);
```

**使用瀏覽器**

直接在瀏覽器環境中使用時，公用程式函數可在 amazonLocationAuthHelper 全域物件下存取。

此範例示範使用 API 金鑰進行身分驗證的 Amazon Location Client 請求：

```
<script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-client@1"></script>

const authHelper = amazonLocationClient.withAPIKey("<API Key>", "<Region>");
const client = new amazonLocationClient.GeoRoutesClient(authHelper.getClientConfig());
const input = { ... };
const command = new amazonLocationClient.routes.CalculateRoutesCommand(input);
const response = await client.send(command);
```

此範例示範使用以 API 金鑰驗證的 MapLibre GL JS 轉譯映射：

```
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x"></script>

const apiKey = "<API Key>";
const region = "<Region>";
const styleName = "Standard";

const map = new maplibregl.Map({
  container: "map",
  center: [-123.115898, 49.295868],
  zoom: 10,
  style: `https://maps.geo.${region}.amazonaws.com/v2/styles/${styleName}/descriptor?key=${apiKey}`,
});
```

此範例示範如何使用 Amazon Cognito 使用 MapLibre GL JS 轉譯映射：

```
<script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.x"></script>
<script src="https://cdn.jsdelivr.net/npm/@aws/amazon-location-utilities-auth-helper@1"></script>

const identityPoolId = "<Identity Pool ID>";
const authHelper = await amazonLocationAuthHelper.withIdentityPoolId(identityPoolId);

const map = new maplibregl.Map({
  container: "map",
  center: [-123.115898, 49.295868],
  zoom: 10,
  style: `https://maps.geo.${region}.amazonaws.com/v2/styles/${styleName}/descriptor`,
  ...authHelper.getMapAuthenticationOptions(),
});
```

**使用已驗證身分的替代用量**

您可以修改 withIdentityPoolId 函數，以包含已驗證身分的自訂參數：

```
const userPoolId = "<User Pool ID>";

const authHelper = await amazonLocationAuthHelper.withIdentityPoolId(identityPoolId, {
  logins: {
    [`cognito-idp.${region}.amazonaws.com/${userPoolId}`]: "cognito-id-token"
  }
});
```

## iOS
<a name="loc-sdk-auth-ios"></a>

適用於 iOS 的 Amazon Location Service Mobile Authentication SDK 可協助驗證來自 iOS 應用程式的 Amazon Location Service APIs請求。它特別支援透過 API 金鑰或 Amazon Cognito 進行身分驗證。

**安裝**
+ 開啟 Xcode 並前往**檔案 > 新增套件相依性**。
+ 在搜尋列中輸入套件 URL ([https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios/](https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios/))，然後按 Enter 鍵。
+ 選取「amazon-location-mobile-auth-sdk-ios」套件，然後按一下**新增套件**。
+ 選擇「AmazonLocationiOSAuthSDK」套件產品，然後按一下**新增套件**。

### Usage
<a name="loc-sdk-auth-usage"></a>

安裝程式庫之後，請使用 `AuthHelper`類別來設定 API 金鑰或 Amazon Cognito 的用戶端設定。

**API 金鑰**

以下是使用獨立 Places SDK 搭配 API 金鑰身分驗證的範例：

```
import AmazonLocationiOSAuthSDK
import AWSGeoPlaces

func geoPlacesExample() {
    let apiKey = "<API key>"
    let region = "<Region>"

    let authHelper = try await AuthHelper.withApiKey(apiKey: apiKey, region: region)
    let client: GeoPlacesClient = GeoPlacesClient(config: authHelper.getGeoPlacesClientConfig())

    let input = AWSGeoPlaces.SearchTextInput(
        biasPosition: [-97.7457518, 30.268193],
        queryText: "tacos"
    )

    let output = try await client.searchText(input: input)
}
```

以下是使用具有 API 金鑰身分驗證的獨立 Routes SDK 的範例：

```
import AmazonLocationiOSAuthSDK
import AWSGeoRoutes

func geoRoutesExample() {
    let apiKey = "<API key>"
    let region = "<Region>"

    let authHelper = try await AuthHelper.withApiKey(apiKey: apiKey, region: region)
    let client: GeoRoutesClient = GeoRoutesClient(config: authHelper.getGeoRoutesClientConfig())

    let input = AWSGeoRoutes.CalculateRoutesInput(
        destination: [-123.1651031, 49.2577281],
        origin: [-97.7457518, 30.268193]
    )

    let output = try await client.calculateRoutes(input: input)
}
```

以下是使用 Location SDK 搭配 API 金鑰身分驗證的範例：

```
import AmazonLocationiOSAuthSDK
import AWSLocation

func locationExample() {
    let apiKey = "<API key>"
    let region = "<Region>"

    let authHelper = try await AuthHelper.withApiKey(apiKey: apiKey, region: region)
    let client: LocationClient = LocationClient(config: authHelper.getLocationClientConfig())

    let input = AWSLocation.ListGeofencesInput(
        collectionName: "<Collection name>"
    )

    let output = try await client.listGeofences(input: input)
}
```

以下是搭配 Amazon Cognito 使用獨立 Places SDK 的範例：

```
import AmazonLocationiOSAuthSDK
import AWSGeoPlaces

func geoPlacesExample() {
    let identityPoolId = "<Identity Pool ID>"

    let authHelper = try await AuthHelper.withIdentityPoolId(identityPoolId: identityPoolId)
    let client: GeoPlacesClient = GeoPlacesClient(config: authHelper.getGeoPlacesClientConfig())

    let input = AWSGeoPlaces.SearchTextInput(
        biasPosition: [-97.7457518, 30.268193],
        queryText: "tacos"
    )

    let output = try await client.searchText(input: input)
}
```

以下是搭配 Amazon Cognito 使用獨立 Routes SDK 的範例：

```
import AmazonLocationiOSAuthSDK
import AWSGeoRoutes

func geoRoutesExample() {
    let identityPoolId = "<Identity Pool ID>"

    let authHelper = try await AuthHelper.withIdentityPoolId(identityPoolId: identityPoolId)
    let client: GeoRoutesClient = GeoRoutesClient(config: authHelper.getGeoRoutesClientConfig())

    let input = AWSGeoRoutes.CalculateRoutesInput(
        destination: [-123.1651031, 49.2577281],
        origin: [-97.7457518, 30.268193]
    )

    let output = try await client.calculateRoutes(input: input)
}
```

以下是搭配 Amazon Cognito 使用 Location SDK 的範例：

```
import AmazonLocationiOSAuthSDK
import AWSLocation

func locationExample() {
    let identityPoolId = "<Identity Pool ID>"

    let authHelper = try await AuthHelper.withIdentityPoolId(identityPoolId: identityPoolId)
    let client: LocationClient = LocationClient(config: authHelper.getLocationClientConfig())

    let input = AWSLocation.ListGeofencesInput(
        collectionName: "<Collection name>"
    )

    let output = try await client.listGeofences(input: input)
}
```

## Android
<a name="loc-sdk-auth-android"></a>

適用於 Android 的 Amazon Location Service Mobile Authentication SDK 可協助您驗證來自 Android 應用程式的 Amazon Location Service APIs 請求，特別是支援使用 Amazon Cognito 進行身分驗證。

**安裝**
+ 此身分驗證 SDK 可與整體 AWS Kotlin SDK 搭配使用。這兩個 SDKs都會發佈至 Maven Central。檢查 Maven Central 上[身分驗證開發套件](https://mvnrepository.com/artifact/software.amazon.location/auth)的最新版本。
+ 將下列幾行新增至 Android Studio 中 `build.gradle` 檔案的相依性區段：

  ```
  implementation("software.amazon.location:auth:1.1.0")
  implementation("org.maplibre.gl:android-sdk:11.5.2")
  implementation("com.squareup.okhttp3:okhttp:4.12.0")
  ```
+ 對於獨立 Maps、Places 和 Routes SDKs，新增下列行：

  ```
  implementation("aws.sdk.kotlin:geomaps:1.3.65")
  implementation("aws.sdk.kotlin:geoplaces:1.3.65")
  implementation("aws.sdk.kotlin:georoutes:1.3.65")
  ```
+ 對於包含地理圍欄和追蹤的合併位置開發套件，新增以下行：

  ```
  implementation("aws.sdk.kotlin:location:1.3.65")
  ```

### Usage
<a name="loc-sdk-auth-usage"></a>

在程式碼中匯入下列類別：

```
// For the standalone Maps, Places, and Routes SDKs
import aws.sdk.kotlin.services.geomaps.GeoMapsClient
import aws.sdk.kotlin.services.geoplaces.GeoPlacesClient
import aws.sdk.kotlin.services.georoutes.GeoRoutesClient

// For the consolidated Location SDK
import aws.sdk.kotlin.services.location.LocationClient

import software.amazon.location.auth.AuthHelper
import software.amazon.location.auth.LocationCredentialsProvider
import software.amazon.location.auth.AwsSignerInterceptor
import org.maplibre.android.module.http.HttpRequestUtil
import okhttp3.OkHttpClient
```

您可以建立 `AuthHelper` 並搭配 AWS Kotlin SDK 使用：

**範例：具有身分集區 ID 的登入資料提供者**

```
private suspend fun exampleCognitoLogin() {
    val authHelper = AuthHelper.withCognitoIdentityPool("MY-COGNITO-IDENTITY-POOL-ID", applicationContext)
    
    var geoMapsClient = GeoMapsClient(authHelper?.getGeoMapsClientConfig())
    var geoPlacesClient = GeoPlacesClient(authHelper?.getGeoPlacesClientConfig())
    var geoRoutesClient = GeoRoutesClient(authHelper?.getGeoRoutesClientConfig())
    
    var locationClient = LocationClient(authHelper?.getLocationClientConfig())
}
```

**範例：具有自訂登入資料提供者的登入資料提供者**

```
private suspend fun exampleCustomCredentialLogin() {
    var authHelper = AuthHelper.withCredentialsProvider(MY-CUSTOM-CREDENTIAL-PROVIDER, "MY-AWS-REGION", applicationContext)

    var geoMapsClient = GeoMapsClient(authHelper?.getGeoMapsClientConfig())
    var geoPlacesClient = GeoPlacesClient(authHelper?.getGeoPlacesClientConfig())
    var geoRoutesClient = GeoRoutesClient(authHelper?.getGeoRoutesClientConfig())
    
    var locationClient = LocationClient(authHelper?.getLocationClientConfig())
}
```

**範例：具有 API 金鑰的登入資料提供者**

```
private suspend fun exampleApiKeyLogin() {
    var authHelper = AuthHelper.withApiKey("MY-API-KEY", "MY-AWS-REGION", applicationContext)

    var geoMapsClient = GeoMapsClient(authHelper?.getGeoMapsClientConfig())
    var geoPlacesClient = GeoPlacesClient(authHelper?.getGeoPlacesClientConfig())
    var geoRoutesClient = GeoRoutesClient(authHelper?.getGeoRoutesClientConfig())
    
    var locationClient = LocationClient(authHelper?.getLocationClientConfig())
}
```

您可以使用 `LocationCredentialsProvider` 載入 MapLibre 映射。請見此處範例：

```
HttpRequestUtil.setOkHttpClient(
    OkHttpClient.Builder()
        .addInterceptor(
            AwsSignerInterceptor(
                "geo",
                "MY-AWS-REGION",
                locationCredentialsProvider,
                applicationContext
            )
        )
        .build()
)
```

使用建立的用戶端來呼叫 Amazon Location Service。以下是搜尋接近指定經緯度的位置的範例：

```
val suggestRequest = SuggestRequest {
       biasPosition = listOf(-97.718833, 30.405423)
       maxResults = MAX_RESULT
       language = "PREFERRED-LANGUAGE"
   }
val nearbyPlaces = geoPlacesClient.suggest(suggestRequest)
```