Use Token from Server Token Provider
This example demonstrates how to create and use a simple server-side token provider. Rather than having a login that works on all accounts for demo purposes, the token provider generates login tokens based on your own credentials only. A client application can request and use these tokens for all further requests.
Credentials are stored on the server, and only a short-lived token is given to the client application. This example hands out tokens to anyone who has access, so ensure that access to the server is additionally protected by some other means, such as a company-specific authentication mechanism.
This example is implemented in JavaScript with NodeJS. To run it, you should first obtain an archive with Data Inspector example applications, then open the /src/tokenProvider
folder, and follow the instructions in the README
file. Because this example requires its own server with credentials, it is not provided as a hosted live demo.
Token Provider
The first step is to create a file, token-provider.js
, where the implementation of the provider is described.
token-provider.js
reads the AAA URL and credentials from the credentials.properties
file, as shown below:
const credentials = require("fs").readFileSync("./credentials.properties");
const url = (/here\.token\.endpoint\.url\s*=\s*([\S]*)/g).exec(credentials)[1];
const consumerKey = (/here\.access\.key\.id\s*=\s*([\S]*)/g).exec(credentials)[1];
const secretKey = (/here\.access\.key\.secret\s*=\s*([\S]*)/g).exec(credentials)[1];
const scope = ((/here\.token\.scope\s*=\s*([\S]*)/g).exec(credentials) || [])[1];
The require("@here/olp-sdk-authentication")
package provides a method called requestToken
that accepts the AAA URL, credentials, and expiration time. This is the main function that can be used to get a token based on the credentials:
const requestToken = require("@here/olp-sdk-authentication").requestToken;
const tokenInfo = await requestToken({
url: URL,
expiresIn: 600,
consumerKey: id,
secretKey: secret
});
requestToken
returns the following JSON:
{
"accessToken":"eyJhbGciO...",
"tokenType":"bearer",
"expiresIn":599
}
This example uses the Express framework to create a standalone server application.
In the API definition, we define the query parameter to set the custom TTL (time to live) for the token. This parameter is used as the expiresIn
property to set how long we cache the token.
Note that if the token provider and client application are hosted on different servers, we should enable Cross-Origin Resource Sharing (CORS) for all users.
let tokenExpirationTime = new Date();
let tokenInfo = null;
app.get("/getToken", async (request, response) => {
try {
if (new Date() >= tokenExpirationTime) {
console.log('Request a new token...');
tokenInfo = await requestToken({
url,
expiresIn: request.query.ttl,
consumerKey,
secretKey,
scope
});
tokenExpirationTime = new Date(Date.now() + tokenInfo.expiresIn * 1000);
console.log(`The token expires on: ${tokenExpirationTime}`);
}
response.set("Access-Control-Allow-Origin", "*");
response.status(200).send(tokenInfo.accessToken);
} catch (e) {
console.error(`Error acquiring new token: ${e.message}`);
response.status(500).send(e.message);
}
});
As a final step, provide the port that the server app should listen to. Once this is created, client apps can receive the token through this API.
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Token provider is listening port ${PORT}`);
});
To run the server, save the file and execute the following command in the terminal:
node token-provider.js
To verify that the token provider is working correctly, open http://localhost:3000/getToken
in a web browser to display the token. Refresh the page and it will display the same token, as the token has already been cached.
Use Token Provider in Client Application
Now that the server has been created, we can build a client application that uses fetch
to call the GET API and get a token. To implement the client application, provide a function that sends a request to our token provider on the server and returns the token from the response:
const TTL = 3600;
async function getBearerToken() {
const response = await fetch(`http://localhost:3000/getToken?ttl=${TTL}`);
if (!response.ok) {
throw new Error(response.statusText);
}
return response.text();
}
Next, pass this to the constructor of the DataInspector
. DataInspector
accepts the getBearerToken
property that provides tokens for all data requests:
new DataInspector({
getBearerToken,
...
});