> For the complete documentation index, see [llms.txt](https://docs.payments.thalescloud.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.payments.thalescloud.io/secure-card-display/ja/integrate-d1-api/get-oauth2.0-access-token.md).

# OAuth 2.0 アクセストークンを取得する

D1 API は OAuth 2.0 JWT ベアラーフロー（[RFC 7523](https://datatracker.ietf.org/doc/html/rfc7523)).

あなたの **イシュアバックエンド** は JSON Web Token (JWT) に署名し、それを D1 アクセストークンと交換します。

D1 アクセストークンを使用して D1 API を呼び出します。

<figure><img src="/spaces/62lLFDcmLCeqqwmy4Fee/files/G3vNReECvDpjaD6K8JIv" alt=""><figcaption><p>イシュアバックエンドと D1 バックエンドの間の OAuth 2.0 JWT ベアラーフロー。</p></figcaption></figure>

API リファレンスのリクエストおよびレスポンスフィールドを参照してください: [認可トークンを取得する](/secure-card-display/ja/integrate-d1-api/d1-api-reference/inbound-api-to-d1/oauth2-api.md#post-oauth2-token).

### D1 アクセストークンを使用する

イシュアバックエンドから D1 バックエンドへのすべての API では、D1 アクセストークンが必要です。

それを `Authorization` ヘッダーに `Bearer` スキームを使って送信します:

`Authorization: Bearer <Base64_Encoded_JWT>`

D1 アクセストークンの有効期限は 15 分です。

トークンは期限切れになるまで再利用してください。

呼び出さないでください `/oauth2/token` を毎回の D1 API 呼び出し前に。

### JWT アサーション

その `/oauth2/token` API は JWT アサーション（[RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519)).

イシュアバックエンドは、有効な JWT を生成して署名する必要があります。

次のことができます:

* ID プロバイダー（たとえば Keycloak）を使用して JWT を生成する。
* イシュアバックエンドで JWT を生成する。

どちらの場合も、署名検証に使用する公開鍵を D1 バックエンドにプロビジョニングします。

ID プロバイダーを使用しない場合は、以下の説明に従って鍵ペアと JWT を生成します。

#### サポートされているアルゴリズム

で署名された JWT のみが `ES256` サポートされます（[RFC 7518](https://datatracker.ietf.org/doc/html/rfc7518)).

D1 は非対称暗号方式を使用します。

D1 バックエンドは公開鍵のみを保存します。

#### JWT の形式

JWT は、ドット（`.`):

* ヘッダー
* ペイロード
* 署名

例: `hhhhhhh.pppppppp.ssssssssss`

#### ヘッダー

ヘッダーにはアルゴリズムとトークンタイプが含まれます。

`kid` は必須です。

D1 バックエンドはこれを使用して適切な公開鍵を選択します。

ヘッダーの例:

```json
{
  "alg": "ES256",
  "typ": "JWT",
  "kid": "your_tenant_key_id"
}
```

#### ペイロード

ペイロードは次のクレームをサポートします:

| クレーム  | 型   | 必須  | 説明                                                                                                                         |
| ----- | --- | --- | -------------------------------------------------------------------------------------------------------------------------- |
| `iss` | 文字列 | はい  | D1 のオンボーディング中に提供された issuerId を使用します。D1 はこれを使ってプロビジョニング済みの公開鍵を検索します。アグリゲーターモデルを使用する場合は、これを aggregatorId に設定してください。          |
| `sub` | 文字列 | はい  | issuerId を使用します。（アグリゲーターの場合、この値は aggregatorId と同じです。）                                                                      |
| `exp` | 整数  | はい  | UTC のエポック秒での有効期限。最大値は現在時刻 + 15 分です。                                                                                        |
| `aud` | 文字列 | いいえ | D1 認可サーバーのベース URL。対象環境の URL を使用してください: Sandbox = `https://api.d1-stg.thalescloud.io`、本番 = `https://api.d1.thalescloud.io`. |

{% hint style="info" %}
D1 は最大有効期限を強制します。もし `exp` 許可されたウィンドウを超えると、D1はリクエストを拒否します。
{% endhint %}

ペイロードの例:

```json
{
  "iss": "イシュア_id",
  "sub": "監査用のユーザー",
  "exp": 1545222654,
  "aud": "https://api.d1.thalescloud.io"
}
```

#### 署名

署名は、Base64URLでエンコードされたヘッダーとペイロードに対して計算されます。

3つの JWT 部分はドット（`.`).

### 鍵ペアを生成します

OpenSSL を使用して P-256 鍵ペアを生成します:

イシュア側のバックエンド用の秘密鍵を生成します。

環境内で安全に保管してください。

```bash
openssl ecparam -name prime256v1 -genkey -noout -out issuerId-jwt-priv-key.pem
```

D1 バックエンドに配置する公開鍵を生成します:

```bash
openssl ec -in issuerId-jwt-priv-key.pem -pubout > issuerId-jwt-pub-key.pem
```

イシュア側のバックエンドは、JWT に署名するために秘密鍵を使用します。

D1 バックエンドは公開鍵（およびその `kid`）JWT署名を検証するために。

公開鍵を共有し、 `kid` D1オンボーディング中にThalesのデリバリーチームとともに。

### JWTを生成する

JWTを生成する方法はたくさんあります。

この例では次を使用します： `jose` Node.jsライブラリ：

```js
/*
プロジェクトに*jose*ライブラリをインストールしてください。
https://www.npmjs.com/package/jose

この例では 3.19.0 を使用します
*/
const { SignJWT } = require("jose/jwt/sign");
const { createPrivateKey } = require("crypto");

const alg = "ES256";
const kid = "your_tenant_key_id";
const iss = "your_イシュア_id";
const aud = "your_audience";
const expirationTime = "3mins";
const sub = "our_user_for_audit";

const privateKeyPem = `-----BEGIN EC PRIVATE KEY----- 
MHcCAQEEILlIXMnH1if8EuWykPmWw/LyXZuoNVCzMp3Yhbj9/sEUoAoGCCqGSM49 
AwEHoUQDQgAE6swczLIRn/lPxQPpdUb2pHjCr0YeC02lkG7vMmqCNpalwIQSl+TR 
fZVDwCKJmajRgK3+n5SyAgCp4oH8qNluwQ==
-----END EC PRIVATE KEY-----`;

async function generateJwt() {
  const privateKey = createPrivateKey(privateKeyPem);

  console.log(
    await new SignJWT({})
      .setProtectedHeader({ alg, kid })
      .setIssuedAt()
      .setIssuer(iss)
      .setAudience(aud)
      .setExpirationTime(expirationTime)
      .setSubject(sub)
      .sign(privateKey)
  );
}

(async () => {
  await generateJwt();
})();
```

JWT出力例:

```shellscript
eyJhbGciOiJFUzI1NiIsImtpZCI6InlvdXJfdGVuYW50X2tleV9pZCJ9.eyJpYXQiOjE2MzYwMzMxODYsImlzcyI6InlvdXJfaXNzdWVyX2lkIiwiYXVkIjoieW91cl9hdWRpZW5jZSIsImV4cCI6MTYzNjAzMzM2Niwic3ViIjoib3VyX3VzZXJfZm9yX2F1ZGl0In0.lgVzN8k9IGcv1s-FZACpEyVxXcS9LAh4ahY3DO5Fg6MRl-Twa_wVAfw_Oe0XiH1Am-RFfafgDrepNi3Jz05Gvg
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.payments.thalescloud.io/secure-card-display/ja/integrate-d1-api/get-oauth2.0-access-token.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
