TypeScript

OpenAPI Specificationから生成 されたTypeScript用クライアントライブラリを使用するサンプルを示します。

OAuth2認可コードフローを使用してAPIにアクセスする

以下は、OAuth2認可コードフローを使用してintdash APIにアクセスするウェブアプリケーションのサンプルです。 フレームワークとして Express を利用しています。

ウェブブラウザーでこのアプリケーションにアクセスすると、intdashの認証画面にリダイレクトされます。 アプリケーションは認可コードフローによってintdash APIのアクセストークンを取得します。 その後、アプリケーションはアクセストークンを使ってユーザーの名前を取得しそれを表示します。

実行するには、まず必要なライブラリをインストールしてください。

$ npm install client-oauth2 pkce-challenge uuid

サンプルアプリケーションのコードは以下のとおりです。

  • CLIENT_ID: サンプルアプリケーション用のOAuth2クライアントID [1]

  • INTDASH_BASE_URL: 接続先intdash APIのベースURL

  • REDIRECT_URI: アプリケーション(Expressで作成したこのアプリケーション)のURL

import express from "express";
import fs from "fs";
import https from "https";
import { v4 as uuidv4 } from "uuid";
import ClientOAuth2 from "client-oauth2";
import pkceChallenge from "pkce-challenge";
import { AuthMeApi } from "./intdash";

const app = express();

const options = {
  key: fs.readFileSync(".key/.key.pem"),
  cert: fs.readFileSync(".key/.cert.pem"),
};
const server = https.createServer(options, app);

// クライアント ID
const CLIENT_ID = "XXXX-XXXX-XXXX-XXXX";
// Intdash API のURL
const INTDASH_BASE_URL = "https://example.intdash.jp";
// リダイレクトURI
const REDIRECT_URI = "https://localhost:8443";
// PKCE の設定
const { code_verifier, code_challenge } = pkceChallenge();
// state の作成
const state = uuidv4();

// 認証のためのインスタンスの作成
const intdashAuth = new ClientOAuth2({
  clientId: CLIENT_ID,
  accessTokenUri: `${INTDASH_BASE_URL}/api/auth/oauth2/token`,
  authorizationUri: `${INTDASH_BASE_URL}/api/auth/oauth2/authorization`,
  redirectUri: REDIRECT_URI,
  state,
});

app.get("/", async (req: express.Request, res: express.Response) => {
  // 認証コードとアクセストークンを交換します
  try {
    const { accessToken } = await intdashAuth.code.getToken(req.originalUrl, {
      state,
      body: {
        code_verifier,
      },
    });

    // 生成したクライアントにリソース先サーバーのホストを設定します。
    // isJsonMime の値は任意に変更してください。
    const authMeApi = new AuthMeApi({
      isJsonMime: () => true,
      basePath: `${INTDASH_BASE_URL}/api`,
    });

    // Authorization Header にアクセストークンをBearer として設定します。
    const { data } = await authMeApi.getMe({
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });

    res.status(200).send(`Hello ${data.name}`);
  } catch (error) {
    // 初回アクセス時や、アクセストークンが交換できなかった場合は認証先にリダイレクトします。
    const uri = intdashAuth.code.getUri({
      state,
      query: {
        code_challenge,
        code_challenge_method: "S256",
      },
    });

    res.redirect(uri);
  }
});

server.listen(8443, () => {
  console.log("Start on port 8443.");
});