Como usar auxiliares de autenticação - Amazon Location Service

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Como usar auxiliares de autenticação

Esta seção fornece informações adicionais sobre os auxiliares de autenticação.

Os utilitários de JavaScript autenticação de localização da Amazon ajudam na autenticação ao fazer chamadas de API do Amazon Location Service a partir de JavaScript aplicativos. Esses utilitários permitem especificamente a autenticação que usa chaves de API ou o Amazon Cognito.

Instalação

  • Instale esta biblioteca usando o NPM:

    npm install @aws/amazon-location-utilities-auth-helper
  • Para usá-la diretamente no navegador, inclua o seguinte em seu arquivo HTML:

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

Usage

Para usar os auxiliares de autenticação, importe a biblioteca e chame as funções utilitárias necessárias. Essa biblioteca suporta solicitações de autenticação do Amazon Location Service SDKs, incluindo Maps, Places e Routes independentes SDKs, bem como a renderização de mapas com MapLibre o GL JS.

Uso com módulos

Este exemplo demonstra o uso do SDK autônomo de Locais para fazer uma solicitação autenticada com chaves de 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);

Este exemplo demonstra o uso do SDK autônomo de Rotas para fazer uma solicitação autenticada com chaves de 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);

Este exemplo usa o SDK de Localização com autenticação por chave de 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);

Uso com um navegador

As funções utilitárias podem ser acessadas sob o objeto global amazonLocationAuth Helper quando usadas diretamente em um ambiente de navegador.

Este exemplo demonstra uma solicitação com o cliente Amazon Location, autenticada usando chaves de API:

<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);

Este exemplo demonstra a renderização de um mapa com MapLibre GL JS, autenticado com uma chave de API:

<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}`, });

Este exemplo demonstra a renderização de um mapa com MapLibre GL JS usando o Amazon Cognito:

<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(), });

Uso alternativo com identidades autenticadas

Você pode modificar a função withIdentityPool Id para incluir parâmetros personalizados para identidades autenticadas:

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

O Amazon Location Service Mobile Authentication SDK para iOS ajuda a autenticar solicitações para o Amazon Location Service a APIs partir de aplicativos iOS. Ele permite especificamente a autenticação por meio de chaves de API ou do Amazon Cognito.

Instalação

  • Abra o Xcode e acesse File > Add Package Dependencies.

  • Digite a URL do pacote (https://github.com/aws-geospatial/amazon-location-mobile-auth-sdk-ios/) na barra de pesquisa e pressione Enter.

  • Selecione o pacote "amazon-location-mobile-auth-sdk-ios” e clique em Add Package.

  • Escolha o produto do pacote "AmazonLocationiOSAuthSDK” e clique em Add Package.

Usage

Depois de instalar a biblioteca, use a classe AuthHelper para definir as configurações do cliente para as chaves de API ou para o Amazon Cognito.

Chaves de API

Veja um exemplo que usa o SDK autônomo de Locais com autenticação de chave de 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) }

Veja um exemplo que usa o SDK autônomo de Rotas com autenticação de chave de API:

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) }

Veja um exemplo que usa o SDK de Localização com autenticação de chave de 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) }

Veja um exemplo que usa o SDK autônomo de Locais com o Amazon Cognito:

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) }

Veja um exemplo que usa o SDK autônomo de Rotas com o Amazon Cognito:

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) }

Veja um exemplo que usa o SDK de Localização com o Amazon Cognito:

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) }

O Amazon Location Service Mobile Authentication SDK para Android ajuda você a autenticar solicitações para o Amazon Location APIs Service a partir de aplicativos Android, oferecendo suporte específico à autenticação usando o Amazon Cognito.

Instalação

  • Esse SDK de autenticação funciona com o SDK geral do AWS Kotlin. Ambos SDKs são publicados no Maven Central. Verifique a versão mais recente do auth SDK no Maven Central.

  • Adicione as seguintes linhas à seção de dependências do arquivo build.gradle no Android Studio:

    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")
  • Para os Mapas, Locais e Rotas independentes SDKs, adicione as seguintes linhas:

    implementation("aws.sdk.kotlin:geomaps:1.3.65") implementation("aws.sdk.kotlin:geoplaces:1.3.65") implementation("aws.sdk.kotlin:georoutes:1.3.65")
  • Para o SDK de Localização consolidado que inclui geocercas e rastreamento, adicione a seguinte linha:

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

Usage

Importe as seguintes classes em seu código:

// 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

Você pode criar um AuthHelper e usá-lo com o AWS SDK do Kotlin:

Exemplo: provedor de credenciais com ID do banco de identidades

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()) }

Exemplo: provedor de credenciais com provedor de credenciais personalizado

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()) }

Exemplo: provedor de credenciais com chave de 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()) }

Você pode usar LocationCredentialsProvider para carregar o MapLibre mapa. Exemplo:

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

Use os clientes criados para fazer chamadas para o Amazon Location Service. Este exemplo pesquisa lugares próximos a uma latitude e longitude especificadas:

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