Auxiliar de autenticação em JavaScript
Os auxiliares de autenticação do Amazon Location simplificam a autenticação ao fazer chamadas de API do Amazon Location a partir do seu aplicativo JavaScript. Os auxiliares de autenticação ajudam você, especificamente, ao usar o Amazon Cognito ou as chaves de API como método de autenticação. Essa é uma biblioteca de código aberto que está disponível no GitHub, aqui: https://github.com/aws-geospatial/amazon-location-utilities-auth-helper-js.
nota
O suporte ao Amazon Cognito no auxiliar de autenticação não oferece suporte ao atributo de identidades federadas do Amazon Cognito.
Instalação
Você pode usar as bibliotecas com uma instalação local, se usar um sistema de compilação, como o webpack, ou incluindo pacotes de JavaScript pré-criados com tags <script>
em seu html.
-
Use o comando a seguir para instalar a biblioteca, usando NPM:
npm install @aws/amazon-location-utilities-auth-helper
-
Use o comando a seguir em seu arquivo HTML para carregar o script:
<script src="https://unpkg.com/@aws/amazon-location-utilities-auth-helper@1.x/dist/amazonLocationAuthHelper.js"></script>
Importar
Para usar uma função específica em seu aplicativo JavaScript, você deve importar essa função. O código a seguir é usado para importar a função withIdentityPoolId
para seu aplicativo.
import { withIdentityPoolId } from '@aws/amazon-location-utilities-auth-helper';
Funções de autenticação
Os auxiliares de autenticação de localização da Amazon incluem as seguintes funções que retornam um objeto AuthHelper
:
-
async withIdentityPoolId( identityPoolId: string): AuthHelper
: esta função retorna um objeto AuthHelper, inicializado para funcionar com o Amazon Cognito -
async withAPIKey( API_KEY: string): AuthHelper
: esta função retorna um objeto AuthHelper, inicializado para funcionar com chaves de API.
O objeto AuthHelper
fornece as seguintes funções:
-
AuthHelper.getMapAuthenticationOptions()
: esta função do objeto AuthHelper retorna um objeto JavaScript com otransformRequest
que pode ser usado com as opções de mapa no MapLibre JS. Fornecido somente quando inicializado com um banco de identidades. -
AuthHelper.getLocationClientConfig()
: esta função do objeto AuthHelper retorna um objeto JavaScript com ocredentials
que pode ser usado para inicializar um LocationClient. -
AuthHelper.getCredentials()
: esta função do objeto AuthHelper retorna as credenciais internas do Amazon Cognito. Fornecido somente quando inicializado com um banco de identidades.
Exemplo: inicializando o objeto de mapa MapLibre com o Amazon Cognito, usando um AuthHelper
import { withIdentityPoolId } from '@aws/amazon-location-utilities-auth-helper'; const authHelper = await withIdentityPoolId("
identity-pool-id
"); // use Cognito pool id for credentials const map = new maplibregl.Map({ container: "map
", // HTML element ID of map element center: [-123.1187, 49.2819], // initial map center point zoom: 16, // initial map zoom style: https://maps.geo.region
.amazonaws.com/maps/v0/maps/mapName
/style-descriptor', // Defines the appearance of the map ...authHelper.getMapAuthenticationOptions(), // Provides credential options required for requests to Amazon Location });
Exemplo: inicializando o objeto de mapa MapLibre com uma chave de API (AuthHelper
não é necessário neste caso)
const map = new maplibregl.Map({ container: "
map
", // HTML element ID of map element center: [-123.1187, 49.2819], // initial map center point zoom: 16, // initial map zoom style: https://maps.geo.region
.amazonaws.com/maps/v0/maps/${mapName
}/style-descriptor?key=api-key-id
', });
Exemplo: inicialize o cliente de localização a partir do AWS SDK para JS, usando o Amazon Cognito e o AuthHelper
Este exemplo usa o AWS SDK v3 para JavaScript.
import { withIdentityPoolId } from '@aws/amazon-location-utilities-auth-helper'; const authHelper = await withIdentityPoolId("
identity-pool-id
"); // use Cognito pool id for credentials //initialize the Location client: const client = new LocationClient({ region: "region
", ...authHelper.getLocationClientConfig() // sets up the Location client to use the Cognito pool defined above }); //call a search function with the location client: const result = await client.send(new SearchPlaceIndexForPositionCommand({ IndexName: "place-index
", // Place index resource to use Position: [-123.1187, 49.2819], // position to search near MaxResults: 10 // number of results to return });
Exemplo: inicialize o cliente de localização a partir do AWS SDK para JS, usando uma chave de API e o AuthHelper
Este exemplo usa o AWS SDK v3 para JavaScript.
import { withAPIKey } from '@aws/amazon-location-utilities-auth-helper'; const authHelper = await withAPIKey("
api-key-id
"); // use API Key id for credentials //initialize the Location client: const client = new LocationClient({ region: "region
", ...authHelper.getLocationClientConfig() // sets up the Location client to use the API Key defined above }); //call a search function with the location client: const result = await client.send(new SearchPlaceIndexForPositionCommand({ IndexName: "place-index
", // Place index resource to use Position: [-123.1187, 49.2819], // position to search near MaxResults: 10 // number of results to return });