サーバートークンプロバイダのトークンを使用します

この例では、単純なサーバーサイドトークンプロバイダを作成して使用する方法を示します。 トークンプロバイダは、デモ目的ですべてのアカウントで機能するログインを持たずに、自分自身の資格情報のみに基づいてログイントークンを生成します。 クライアント アプリケーションは、これらのトークンを要求して、それ以降のすべての要求に使用できます。

資格情報はサーバに保存され、トークンには存続期間の短いクライアント アプリケーションのみが付与されます。 この例では、アクセス権を持つすべてのユーザーにトークンを渡します。そのため、サーバーへのアクセスが、会社固有の認証メカニズムなどの他の手段によって追加で保護されていることを確認します。

この例は、 NodeJS を使用して JavaScript に実装されています。 実行するには、まずデータ インスペクターサンプルアプリケーションでアーカイブを取得してから、/src/tokenProviderフォルダを開き、READMEファイルの指示に従います。 この例では、資格情報を備えた独自のサーバーが必要であるため、ホストされたライブデモとしては提供されていません。

トークンプロバイダ

まず、 token-provider.jsプロバイダの実装を記述するファイルを作成します。

token-provider.jscredentials.properties のように、ファイルから AAA URL および資格情報を読み取ります。

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

require("@here/olp-sdk-authentication") このパッケージには、 requestToken AAA URL 、資格情報、および有効期限を受け取るというメソッドがあります。 これは、資格情報に基づいてトークンを取得するために使用できる主な機能です。

この機能の実装方法の詳細については、『 Identity & Access Management 開発者ガイド』の「 OAuth 2.0 トークンリクエストのコード化」を参照してください。

const requestToken = require("@here/olp-sdk-authentication").requestToken;
const tokenInfo = await requestToken({
    url: URL,
    expiresIn: 600,

    consumerKey: id,
    secretKey: secret
});

requestToken 次の JSON を返します。

{
    "accessToken":"eyJhbGciO...",
    "tokenType":"bearer",
    "expiresIn":599
}

この例では 、 Express フレームワークを使用して、スタンドアロンのサーバーアプリケーションを作成します。

API 定義では、トークンのカスタム TTL (存続可能時間)を設定するようにクエリ パラメーターを定義します。 expiresIn このパラメータは、トークンをキャッシュする期間を設定するプロパティとして使用されます。

トークンプロバイダとクライアント アプリケーションが異なるサーバーでホストされている場合は、すべてのユーザーに対してクロスオリジンリソース共有 (CORS) を有効にする必要があります。

// Cached data
let tokenExpirationTime = new Date();
let tokenInfo = null;

// Add GET endpoint on this server, that will fetch the token from the token endpoint.
// API format: /getToken?ttl={number}, where ttl is an optional parameter which defines the time to
// live of a token in seconds.
app.get("/getToken", async (request, response) => {
    try {
        if (new Date() >= tokenExpirationTime) {
            console.log('Request a new token...');

            tokenInfo = await requestToken({
                // Set the token endpoint
                url,

                // Set the time to live of the token. If not defined, then 3600 sec will be used by default.
                expiresIn: request.query.ttl,

                // Pass credential data.
                consumerKey,
                secretKey,
                scope
            });

            tokenExpirationTime = new Date(Date.now() + tokenInfo.expiresIn * 1000);

            console.log(`The token expires on: ${tokenExpirationTime}`);
        }

        // Allow CORS. Optional, if token provider and client application will be hosted on different server
        response.set("Access-Control-Allow-Origin", "*");

        // Send back token to the requestor.
        response.status(200).send(tokenInfo.accessToken);
    } catch (e) {
        // For code brevity, we don't analyze error type and return HTTP 500 response.
        console.error(`Error acquiring new token: ${e.message}`);
        response.status(500).send(e.message);
    }
});

最後のステップとして、サーバーのアプリがリッスンするポートを指定します。 作成されたクライアントアプリは、この API を介してトークンを受信できます。

// Define the server port.
const PORT = 3000;

// Start the server.
app.listen(PORT, () => {
    console.log(`Token provider is listening port ${PORT}`);
});

サーバーを実行するには、ファイルを保存してターミナルで次のコマンドを実行します。

node token-provider.js

トークンプロバイダが正しく動作していることを確認 http://localhost:3000/getToken するには、 Web ブラウザでトークンを開きます。 ページを更新すると、トークンがすでにキャッシュされているのと同じトークンが表示されます。

クライアント アプリケーションでトークンプロバイダを使用します

サーバーが作成されたので、 fetch を使用して GET API を呼び出し、トークンを取得するクライアント アプリケーションを作成できます。 クライアント アプリケーションを実装するには、サーバー上のトークンプロバイダにリクエストを送信し、応答からトークンを返す関数を提供します。

/** Time to live of the token, in seconds. */
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();
}

次に、のコンストラクタにこの値を渡します DataInspectorDataInspectorgetBearerToken 、すべてのデータ要求にトークンを提供するプロパティを受け入れます。

new DataInspector({
    getBearerToken,
    ...
});

」に一致する結果は 件です

    」に一致する結果はありません