

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

# 使用 API 金鑰進行身分驗證
<a name="using-apikeys"></a>

**注意**  
API 金鑰僅適用於**映射**、**放置**和**路由**資源，您無法修改或建立這些資源。如果您的應用程式需要存取未經驗證使用者的其他資源或動作，您可以使用 Amazon Cognito 來提供存取，以及 API 金鑰，或代替 API 金鑰。如需詳細資訊，請參閱[使用 Amazon Cognito 進行身分驗證](authenticating-using-cognito.md)。

*API 金鑰*是與 中特定 Amazon Location Service 資源或 API 相關聯的金鑰值 AWS 帳戶，以及您可以在這些資源上執行的特定動作。您可以在應用程式中使用 API 金鑰，對這些資源的 Amazon Location APIs 進行未經驗證的呼叫。

例如，如果您將 API 金鑰與資源和/或 `GetPlace*` API 建立關聯，則使用該 API 金鑰的應用程式將能夠呼叫特定 APIs。相同的 API 金鑰不會授予變更或更新任何資源的許可，也不會呼叫與其沒有關聯的 APIs。

當您在應用程式中呼叫 Amazon Location Service APIs 時，通常會以授權進行 API 呼叫*的已驗證使用者*身分進行此呼叫。不過，在某些情況下，您不想驗證應用程式的每位使用者。

例如，您可能希望顯示您的商業位置的 Web 應用程式可供任何使用網站的人使用，無論他們是否登入。在這種情況下，其中一個替代方法是使用 API 金鑰進行 API 呼叫。

[API 金鑰最佳實務](#api-keys-best-practices) 如需何時使用 API 金鑰的其他資訊，請參閱 。

如需使用 Amazon Location Service API 使用金鑰的詳細資訊，請參閱《*Amazon Location Service API 參考*》中的下列主題：
+ [CreateKey](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_CreateKey.html)
+ [DeleteKey](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_DeleteKey.html)
+ [DescribeKey](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_DescribeKey.html)
+ [ListKeys](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_ListKeys.html)

## 建立 Amazon Location Service 的 API 金鑰
<a name="create-api-key"></a>

您可以透過 Amazon Location Service 主控台 AWS CLI或 Amazon Location API 建立 API 金鑰。繼續執行下列適當的程序。

------
#### [ Amazon Location console ]

**使用 Amazon Location Service 主控台建立 API 金鑰**

1. 在 [https://console.aws.amazon.com/location](https://console.aws.amazon.com/location)中，從左側選單中選擇 **API 金鑰**。

1. 在 **API 金鑰**頁面上，選擇**建立 API 金鑰**。

1. 在**建立 API 金鑰**頁面上，填寫下列資訊：
   + **名稱** – API 金鑰的名稱，例如 `ExampleKey`。
   + **描述** – API 金鑰的選用描述。
   + **資源** – 在下拉式清單中，選擇 Amazon Location 資源，以使用此 API 金鑰授予 的存取權。您可以選擇新增資源來**新增多個資源**。
   + **動作** – 指定您要使用此 API 金鑰授權的動作。您必須至少選取一個動作，以符合您選取的每個資源類型。例如，如果您選取了位置資源，則必須在**位置動作**下至少選取其中一個選項。
   + **過期時間** – 選擇性地為您的 API 金鑰新增過期日期和時間。如需詳細資訊，請參閱[API 金鑰最佳實務](#api-keys-best-practices)。
   + **用戶端限制** – 選擇性地新增一或多個 Web 網域，或一或多個 Android 或 Apple 應用程式，您可以在其中使用 API 金鑰。例如，如果 API 金鑰是允許在網站 上執行的應用程式`example.com`，則可以將 `*.example.com/`做為允許的推薦者。
   + **標籤** – 選擇性地將標籤新增至 API 金鑰。

1. 選擇**建立 API 金鑰**以建立 API 金鑰。

1. 在 API 金鑰的詳細資訊頁面上，您可以查看已建立之 API 金鑰的相關資訊。選擇**顯示 API 金鑰**以查看您在呼叫 Amazon Location APIs 時所使用的金鑰值。索引鍵值的格式為 `v1.public.a1b2c3d4...`。

------
#### [ AWS CLI ]

1. 使用 [create-key](https://docs.aws.amazon.com/cli/latest/reference/location/create-key.html) 命令。下列範例會建立名為 的 API 金鑰`ExampleKey`，沒有過期日期和對單一映射資源的存取權。

   ```
   aws location \
     create-key \
     --key-name ExampleKey \
     --restrictions '{"AllowActions":["geo-maps:*"],"AllowResources":["arn:aws:geo-maps:region::provider/default"]}' \
     --no-expiry
   ```

1. 回應包含存取應用程式中資源時要使用的 API 金鑰值。索引鍵值的格式為 `v1.public.a1b2c3d4...`。若要進一步了解如何使用 API 金鑰轉譯映射，請參閱 [使用 API 金鑰呼叫 Amazon Location API](#using-apikeys-in-api)。create-key 的回應如下所示：

   ```
   {
       "Key": "v1.public.a1b2c3d4...",
       "KeyArn": "arn:aws:geo:region:accountId:api-key/ExampleKey",
       "KeyName": "ExampleKey",
       "CreateTime": "2023-02-06T22:33:15.693Z"
   }
   ```

1. 您也可以稍後使用 `describe-key` 來尋找索引鍵值。下列範例示範如何在名為 的 API 金鑰`describe-key`上呼叫 `ExampleKey`。

   ```
   aws location describe-key \
       --key-name ExampleKey
   ```

------
#### [ Amazon Location API ]

從 Amazon Location APIs使用 [CreateKey](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_CreateKey.html) 操作。下列範例是 API 請求，可建立名為 的 API 金鑰`ExampleKey`，沒有過期日期和對單一映射資源的存取權。

```
POST /metadata/v0/keys HTTP/1.1
Content-type: application/json
{
  "KeyName": "ExampleKey",
  "NoExpiry": true,
  "Restrictions": {
    "AllowActions": [
      "geo-places:*",
      "geo-routes:*",
      "geo-maps:*"
    ],
    "AllowResources": [
      "arn:aws:geo-places:Region::provider/default",
      "arn:aws:geo-routes:Region::provider/default",
      "arn:aws:geo-maps:Region::provider/default"
    ]
  }
}
```

回應包含存取應用程式中資源時要使用的 API 金鑰值。索引鍵值的格式為 `v1.public.a1b2c3d4...`。

您也可以使用 [DescribeKey](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_DescribeKey.html) API 稍後尋找金鑰的金鑰值。

------

## 使用 API 金鑰呼叫 Amazon Location API
<a name="using-apikeys-in-api"></a>

建立 API 金鑰後，您可以使用金鑰值來呼叫應用程式中的 Amazon Location APIs。

------
#### [ API ]

支援 API 金鑰APIs 具有接受 API 金鑰值的額外參數。例如，如果您呼叫 `GetPlace` API，您可以填入[金鑰](https://docs.aws.amazon.com/location/latest/APIReference/API_geoplaces_GetPlace.html)參數，如下所示

```
curl --request GET —url 'https://places.geo.eu-central-1.amazonaws.com/v2/place/{PLACEID}?key={APIKEY}&language=jp'
```

------
#### [ AWS CLI ]

使用 `--key` 參數時，您也應該使用 `--no-sign-request` 參數，以避免使用 Sig v4 簽署。

```
aws geo-places get-place --place-id $PLACEID --language jp --key $APIKEY
```

------
#### [ SDK (web) ]

使用下列程式碼：

```
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Display a map</title>
        <meta property="og:description" content="Initialize a map in an HTML element with MapLibre GL JS." />
        <meta charset='utf-8'>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.x/dist/maplibre-gl.css' />
        <script src='https://unpkg.com/maplibre-gl@5.x/dist/maplibre-gl.js'></script>
        <style>
            body { margin: 0; }
            #map { height: 100vh; }
        </style>
    </head>
    <body>
         
        <div id="map"></div>
        <script>
     
            const apiKey = "<api key>"; // check how to create api key for Amazon Location
            const mapStyle = "Standard";  // eg. Standard, Monochrome, Hybrid, Satellite  
            const awsRegion = "eu-central-1"; // eg. us-east-2, us-east-1, us-west-2, ap-south-1, ap-southeast-1, ap-southeast-2, ap-northeast-1, ca-central-1, eu-central-1, eu-west-1, eu-west-2, eu-south-2, eu-north-1, sa-east-1
            const styleUrl = `https://maps.geo.${awsRegion}.amazonaws.com/v2/styles/${mapStyle}/descriptor?key=${apiKey}`;


            const map = new maplibregl.Map({
                container: 'map', // container id
                style: styleUrl, // style URL
                center: [25.24,36.31], // starting position [lng, lat]
                zoom: 2, // starting zoom
            });
        </script>
    </body>
</html>
```

------
#### [ SDK (iOS, Swift) ]

使用下列程式碼：

```
import UIKit
import MapLibre

class ViewController: UIViewController {
    let apiKey = "Enter your API key" // The previously-created API Key to use
    let regionName = "Enter your region name" // The service region - us-east-1, ap-south-1, etc
    var mapView: MLNMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadMap()
    }
    
    func loadMap() {
        let styleName = "Standard" // The map style - Standard, Monochrome, Hybrid, Satellite
        let colorName = "Light" // The color scheme - Light, Dark
        
        // The Amazon Location Service map style URL that MapLibre will use to render the maps.
        let styleURL = URL(string: "https://maps.geo.\(regionName).amazonaws.com/v2/styles/\(styleName)/descriptor?key=\(apiKey)&color-scheme=\(colorName)")

        // Initialize MapLibre        
        mapView = MLNMapView(frame: view.bounds)
        mapView.styleURL = styleURL
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        // Set the starting camera position and zoom level for the map
        mapView.setCenter(CLLocationCoordinate2D(latitude: 49.246559, longitude: -123.063554), zoomLevel: 10, animated: false)
        view.addSubview(mapView!)
    }
}
```

------
#### [ SDK (Android, Kotlin) ]

使用下列程式碼：

```
class MapActivity : Activity(), OnMapReadyCallback {

    private lateinit var mBinding: ActivityMapBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initializeMap(savedInstanceState)
    }

    private fun initializeMap(savedInstanceState: Bundle?) {
        // Init MapLibre
        // See the MapLibre Getting Started Guide for more details
        // https://maplibre.org/maplibre-native/docs/book/android/getting-started-guide.html
        MapLibre.getInstance(this@MapActivity)
        mBinding = ActivityMapBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        mBinding.mapView.onCreate(savedInstanceState)
        mBinding.mapView.getMapAsync(this)
    }

    override fun onMapReady(mapLibreMap: MapLibreMap) {
        mapLibreMap.setStyle(Style.Builder().fromUri(getMapUrl())) {
            // Set the starting camera position
            mapLibreMap.cameraPosition = CameraPosition.Builder().target(LatLng(49.246559, -123.063554)).zoom(10.0).build()
            mapLibreMap.uiSettings.isLogoEnabled = false
            mapLibreMap.uiSettings.attributionGravity = Gravity.BOTTOM or Gravity.END
            mapLibreMap.uiSettings.setAttributionDialogManager(AttributionDialogManager(this, mapLibreMap))
        }
    }

    // Return the Amazon Location Service map style URL
    // MapLibre will use this to render the maps.
    // awsRegion: The service region - us-east-1, ap-south-1, etc
    // mapStyle: The map style - Standard, Monochrome, Hybrid, Satellite  
    // API_KEY: The previously-created API Key to use
    // colorName: The color scheme to use - Light, Dark
    private fun getMapUrl() =
           "https://maps.geo.${getString(R.string.awsRegion)}.amazonaws.com/v2/styles/${getString(R.string.mapStyle)}/descriptor?key=${BuildConfig.API_KEY}&color-scheme=${getString(R.string.colorName)}"

    override fun onStart() {
        super.onStart()
        mBinding.mapView.onStart()
    }

    override fun onResume() {
        super.onResume()
        mBinding.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBinding.mapView.onPause()
    }

    override fun onStop() {
        super.onStop()
        mBinding.mapView.onStop()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mBinding.mapView.onSaveInstanceState(outState)
    }

    override fun onLowMemory() {
        super.onLowMemory()
        mBinding.mapView.onLowMemory()
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.mapView.onDestroy()
    }
}
```

------

## 依請求原始伺服器限制 API 金鑰用量
<a name="restrict-usage-by-origin"></a>

您可以使用用戶端限制來設定 API 金鑰，以限制對特定網域或行動應用程式的存取。依網域限制時，只有在 HTTP 參考者標頭符合您提供的值時，才會授權請求。限制 Android 或 Apple 應用程式時，只有在應用程式識別符 HTTP 標頭欄位符合您提供的值時，才會授權請求。

如需詳細資訊，請參閱《*Amazon Location Service API 參考*》中的 [ApiKeyRestrictions](https://docs.aws.amazon.com/location/latest/APIReference/API_geotags_ApiKeyRestrictions.html)。

**Android 應用程式識別符：**
+ `X-Android-Package`:

  Android 應用程式的唯一識別符，在應用程式的 `build.gradle` 檔案中定義，通常遵循反向網域格式。

  範例：

  `com.mydomain.appname`
+ `X-Android-Cert`:

  用來簽署 Android APK 之簽署憑證的 SHA-1 雜湊。

  範例：

  `BB:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75`

**Apple 應用程式識別符：**
+ `X-Apple-Bundle-Id `:

  Apple (iOS、macOS 等） 應用程式的唯一識別符，在應用程式的 中定義`Info.plist`，通常遵循反向網域格式。

  範例：

  `com.mydomain.appname`

## API 金鑰最佳實務
<a name="api-keys-best-practices"></a>

API 金鑰包含純文字*值*，可讓您存取 中的一或多個資源或 APIs AWS 帳戶。如果有人複製您的 API 金鑰，他們可以存取這些相同的資源和 APIs。若要將潛在影響降至最低，請檢閱下列最佳實務：
+ **限制 API 金鑰**

  為了避免上述情況，最好限制您的 API 金鑰。建立金鑰時，您可以指定可以使用金鑰的網域、Android 應用程式或 Apple 應用程式。
+ **管理 API 金鑰生命週期**

  您可以建立無限期運作的 API 金鑰。不過，如果您想要建立暫時 API 金鑰、定期輪換 API 金鑰，或撤銷現有的 API 金鑰，您可以使用 *API 金鑰過期*。
  + 您可以在建立或更新 API 金鑰時設定其過期時間。
  + 當 API 金鑰達到到期時間時，金鑰會自動停用。非作用中金鑰無法再用於提出請求。
  + 您可以移除過期時間，將臨時金鑰變更為永久金鑰。
  + 您可以在停用 API 金鑰的 90 天後將其刪除。
  + 如果您嘗試停用過去七天內已使用的 API 金鑰，系統會提示您確認是否要進行變更。

    如果您使用的是 Amazon Location Service API 或 AWS CLI，請將 `ForceUpdate` 參數設定為 `true`，否則您會收到錯誤。