> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Go APIを保護する

> このガイドでは、go-jwt-middleware v3 SDK を使用して、JWTアクセストークンで Go API のエンドポイントを保護する方法を説明します。

> [accordion] AI を使って Auth0 を統合する
>
> Claude Code、Cursor、GitHub Copilot などの AI コーディングアシスタントを使っている場合は、[Agent Skills](https://agentskills.io/home) を使うことで、数分で Auth0 API 認証を自動的に追加できます。
>
> **インストール:**
>
> ```bash theme={null}
> npx skills add auth0/agent-skills --skill auth0
> ```
>
> **次に、AI アシスタントに以下のように依頼します。**
>
> ```text theme={null}
> Add Auth0 JWT authentication to my Go API
> ```
>
> AI アシスタントが、Auth0 API の作成、資格情報の取得、`go-jwt-middleware` のインストール、バリデーター の設定、JWT バリデーションによる API エンドポイントの保護を自動的に行います。[Agent Skills の完全なドキュメント →](/docs/docs/ja-jp/quickstart/agent-skills)

> [!NOTE]
>
> **前提条件:** 始める前に、以下がインストールされていることを確認してください。
>
> * **[Go](https://go.dev/doc/install)** 1.24 以降 (go-jwt-middleware v3 で ジェネリクス をサポートするために必要)
> * **[Git](https://git-scm.com/downloads)** (バージョン管理用)
>
> インストールを確認するには、`go version` を実行します。

## はじめに

パブリックアクセス、JWT 認証、権限ごとにスコープが設定されたアクセスという、保護レベルの異なる 3 つのエンドポイントを備えた Go API を構築します。完全な実装では、Go 標準の `net/http` ライブラリと [go-jwt-middleware v3](https://github.com/auth0/go-jwt-middleware) を使用します。

> [card] [GitHubでサンプルを見る](https://github.com/auth0-samples/auth0-golang-api-samples/tree/master/01-Quickstart-Go-API)
>
> テストを含む完全な動作例

**1. 新しいプロジェクトを作成**

Go API用の新しいディレクトリを作成し、モジュールを初期化します。

```shellscript theme={null}
mkdir myapi && cd myapi
go mod init github.com/yourorg/myapi
```

必要な依存関係をインストールしてください:

```shellscript theme={null}
go get github.com/auth0/go-jwt-middleware/v3
go get github.com/joho/godotenv
go mod download
```

プロジェクトの構成を作成します：

```shellscript theme={null}
mkdir -p cmd/server internal/auth internal/config internal/handlers
touch .env cmd/server/main.go internal/config/auth.go internal/auth/claims.go internal/auth/validator.go internal/auth/middleware.go internal/handlers/api.go
```

> [accordion] 想定されるgo.modを表示
>
> ```go go.mod theme={null}
> module github.com/yourorg/myapi
>
> go 1.24
>
> require (
>     github.com/auth0/go-jwt-middleware/v3 v3.1.0
>     github.com/joho/godotenv v1.5.1
> )
> ```

**2. Auth0 API の設定**

次に、Auth0 テナントに新しい API を作成し、環境変数をプロジェクトに追加する必要があります。

Auth0 API を設定する方法は 2 つあります。CLI コマンドを使う方法と、Auth0 Dashboard から手動で設定する方法です。

> [tab] CLI
>
> Auth0 API を作成するには、プロジェクトのルートディレクトリで次のコマンドを実行します。
>
> ```shellscript Mac theme={null}
> # Auth0 CLI をインストールします（まだインストールしていない場合）
> brew tap auth0/auth0-cli && brew install auth0
>
> # Auth0 API を作成します
> auth0 apis create \
>   --name "My Go API" \
>   --identifier https://my-go-api.example.com
> ```
>
> ```powershell Windows theme={null}
> # Auth0 CLI をインストールします（まだインストールしていない場合）
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Auth0 API を作成します
> auth0 apis create `
>   --name "My Go API" `
>   --identifier https://my-go-api.example.com
> ```
>
> 作成後、**Identifier** と **Domain** の値をコピーして、`.env` ファイルを作成します。
>
> > [!NOTE]
> >
> > このコマンドでは次の処理が行われます。
> >
> > 1. 認証済みかどうかを確認します (必要に応じてログインを求められます)
> > 2. 指定した identifier で Auth0 API を作成します
> > 3. ドメインと identifier を含む API の詳細を表示します

> [tab] Dashboard
>
> 1. [Auth0 Dashboard](https://manage.auth0.com/dashboard/) を開きます
> 2. **アプリケーション** → **APIs** → **Create API** の順に進みます
> 3. API の名前を入力します (例: "My Go API")
> 4. **Identifier** を設定します (例: `https://my-go-api.example.com`)
>    * これは API の audience であり、有効な URL 形式である必要があります
>    * 実在する URL である必要はなく、単なる識別子です
> 5. **Signing Algorithm** は **RS256** のままにします
> 6. **Create** をクリックします
> 7. **設定** タブから **Identifier** の値をコピーします
>
> 次の値を使って `.env` ファイルを作成します。
>
> ```bash .env theme={null}
> AUTH0_DOMAIN=YOUR_AUTH0_DOMAIN
> AUTH0_AUDIENCE=YOUR_API_IDENTIFIER
> ```
>
> > [!WARNING]
> >
> > `YOUR_AUTH0_DOMAIN` は Auth0 テナントのドメイン (例: `dev-abc123.us.auth0.com`) に、`YOUR_API_IDENTIFIER` は Auth0 Dashboard の API 識別子 (例: `https://my-go-api.example.com`) に置き換えてください。

> [!TIP]
>
> **セキュリティ**: `.env` ファイルは絶対にバージョン管理にコミットしないでください。`.gitignore` ファイルに `.env` を追加してください。

**3. API の権限を定義する**

権限 (スコープ) を使うと、リソースへのアクセス方法を定義できます。たとえば、マネージャーには `read` アクセスを、管理者には `write` アクセスを付与できます。

1. API の設定で、**Permissions** タブをクリックします
2. 次の権限を作成します。

| Permission | Description |
| - | - |
| `read:messages` | API からメッセージを読み取る |

> [!NOTE]
>
> このチュートリアルでは、スコープが設定されたエンドポイントを保護するために `read:messages` スコープを使用します。アプリケーションの要件に応じて、追加の権限を定義できます。

**4. 設定ローダーを作成**

環境変数を読み込んで検証するための設定パッケージを作成します。

```go internal/config/auth.go lines theme={null}
package config

import (
    "fmt"
    "os"
)

type AuthConfig struct {
    Domain   string
    Audience string
}

func LoadAuthConfig() (*AuthConfig, error) {
    domain := os.Getenv("AUTH0_DOMAIN")
    if domain == "" {
        return nil, fmt.Errorf("AUTH0_DOMAIN environment variable required")
    }

    audience := os.Getenv("AUTH0_AUDIENCE")
    if audience == "" {
        return nil, fmt.Errorf("AUTH0_AUDIENCE environment variable required")
    }

    return &AuthConfig{
        Domain:   domain,
        Audience: audience,
    }, nil
}
```

**このコードでできること:**

* 環境変数からAuth0のドメインとaudienceを読み込みます
* 起動時に、必要な設定がそろっていることを検証します
* アプリケーション全体で使える、型安全な設定用構造体を返します

**5. カスタムクレームとJWTバリデーターの作成**

カスタムクレームを使用すると、JWT からアプリケーション固有のデータを抽出して検証できます。バリデーターは、Auth0 を基準にトークンを検証する中核コンポーネントです。

> [tab] claims.go
>
> ```go internal/auth/claims.go lines theme={null}
> package auth
>
> import (
>     "context"
>     "fmt"
>     "strings"
> )
>
> // CustomClaims contains custom data we want to parse from the JWT.
> type CustomClaims struct {
>     Scope string `json:"scope"`
> }
>
> // Validate ensures the custom claims are properly formatted.
> func (c *CustomClaims) Validate(ctx context.Context) error {
>     if c.Scope == "" {
>         return nil
>     }
>
>     if strings.TrimSpace(c.Scope) != c.Scope {
>         return fmt.Errorf("scope claim has invalid whitespace")
>     }
>
>     if strings.Contains(c.Scope, "  ") {
>         return fmt.Errorf("scope claim contains double spaces")
>     }
>
>     return nil
> }
>
> // HasScope checks whether our claims have a specific scope.
> func (c *CustomClaims) HasScope(expectedScope string) bool {
>     if c.Scope == "" {
>         return false
>     }
>
>     scopes := strings.Split(c.Scope, " ")
>     for _, scope := range scopes {
>         if scope == expectedScope {
>             return true
>         }
>     }
>     return false
> }
> ```

> [tab] validator.go
>
> ```go internal/auth/validator.go lines theme={null}
> package auth
>
> import (
>     "fmt"
>     "net/url"
>     "time"
>
>     "github.com/auth0/go-jwt-middleware/v3/jwks"
>     "github.com/auth0/go-jwt-middleware/v3/validator"
> )
>
> func NewValidator(domain, audience string) (*validator.Validator, error) {
>     // Construct issuer URL (must include trailing slash)
>     issuerURL, err := url.Parse("https://" + domain + "/")
>     if err != nil {
>         return nil, fmt.Errorf("failed to parse issuer URL: %w", err)
>     }
>
>     // Initialize JWKS provider using v3 options pattern
>     provider, err := jwks.NewCachingProvider(
>         jwks.WithIssuerURL(issuerURL),
>         jwks.WithCacheTTL(5*time.Minute),
>     )
>     if err != nil {
>         return nil, fmt.Errorf("failed to create JWKS provider: %w", err)
>     }
>
>     // Create validator using v3 options pattern
>     jwtValidator, err := validator.New(
>         validator.WithKeyFunc(provider.KeyFunc),
>         validator.WithAlgorithm(validator.RS256),
>         validator.WithIssuer(issuerURL.String()),
>         validator.WithAudience(audience),
>         validator.WithCustomClaims(func() validator.CustomClaims {
>             return &CustomClaims{}
>         }),
>         validator.WithAllowedClockSkew(30*time.Second),
>     )
>     if err != nil {
>         return nil, fmt.Errorf("failed to create validator: %w", err)
>     }
>
>     return jwtValidator, nil
> }
> ```

**重要なポイント:**

* `Validate` メソッドは、JWT の解析後にミドルウェアによって自動的に呼び出されます
* `HasScope` は、スペース区切りのスコープを解析し、権限ベースのアクセス制御に使用します
* バリデーターは JWKS のキャッシュ (TTL は 5 分) を使用し、30 秒のクロックスキューを許容します
* RS256 アルゴリズムは、[algorithm confusion attacks](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/) を防ぐために明示的に設定されています

**6. HTTPミドルウェアとハンドラーの作成**

HTTP リクエストのバリデーターをラップするミドルウェアです。ハンドラーでは、public、private、permission-scoped の 3 つの保護レベルを示しています。

> [tab] middleware.go
>
> ```go internal/auth/middleware.go lines theme={null}
> package auth
>
> import (
>     "log/slog"
>     "net/http"
>
>     jwtmiddleware "github.com/auth0/go-jwt-middleware/v3"
>     "github.com/auth0/go-jwt-middleware/v3/validator"
> )
>
> func NewMiddleware(jwtValidator *validator.Validator) (*jwtmiddleware.JWTMiddleware, error) {
>     return jwtmiddleware.New(
>         jwtmiddleware.WithValidator(jwtValidator),
>         jwtmiddleware.WithValidateOnOptions(false),
>         jwtmiddleware.WithErrorHandler(func(w http.ResponseWriter, r *http.Request, err error) {
>             slog.Error("JWT validation failed", "error", err, "path", r.URL.Path)
>             w.Header().Set("Content-Type", "application/json")
>             w.WriteHeader(http.StatusUnauthorized)
>             w.Write([]byte(`{"message":"Failed to validate JWT."}`))
>         }),
>     )
> }
> ```

> [tab] api.go
>
> ```go internal/handlers/api.go expandable lines theme={null}
> package handlers
>
> import (
>     "encoding/json"
>     "net/http"
>
>     "github.com/yourorg/myapi/internal/auth"
>     jwtmiddleware "github.com/auth0/go-jwt-middleware/v3"
>     "github.com/auth0/go-jwt-middleware/v3/validator"
> )
>
> // PublicHandler - 認証不要
> func PublicHandler(w http.ResponseWriter, r *http.Request) {
>     response := map[string]string{
>         "message": "Hello from a public endpoint! You don't need to be authenticated to see this.",
>     }
>     w.Header().Set("Content-Type", "application/json")
>     json.NewEncoder(w).Encode(response)
> }
>
> // PrivateHandler - 有効な JWT が必要
> func PrivateHandler(w http.ResponseWriter, r *http.Request) {
>     response := map[string]string{
>         "message": "Hello from a private endpoint! You need to be authenticated to see this.",
>     }
>     w.Header().Set("Content-Type", "application/json")
>     json.NewEncoder(w).Encode(response)
> }
>
> // ScopedHandler - 'read:messages' 権限が必要
> func ScopedHandler(w http.ResponseWriter, r *http.Request) {
>     claims, err := jwtmiddleware.GetClaims[*validator.ValidatedClaims](r.Context())
>     if err != nil {
>         w.Header().Set("Content-Type", "application/json")
>         w.WriteHeader(http.StatusUnauthorized)
>         w.Write([]byte(`{"message":"Unauthorized."}`))
>         return
>     }
>
>     customClaims, ok := claims.CustomClaims.(*auth.CustomClaims)
>     if !ok || !customClaims.HasScope("read:messages") {
>         w.Header().Set("Content-Type", "application/json")
>         w.WriteHeader(http.StatusForbidden)
>         w.Write([]byte(`{"message":"Insufficient scope."}`))
>         return
>     }
>
>     response := map[string]string{
>         "message": "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.",
>     }
>     w.Header().Set("Content-Type", "application/json")
>     json.NewEncoder(w).Encode(response)
> }
> ```

**保護レベル:**

* **Public** (`/api/public`) — 認証不要
* **Private** (`/api/private`) — 有効な JWT が必要
* **Scoped** (`/api/private-scoped`) — 有効な JWT と `read:messages` 権限が必要

**7. メインサーバーを作成**

本番運用向けのタイムアウト設定と適切なシャットダウン処理を備え、メインのエントリポイントですべてを統合します：

```go cmd/server/main.go expandable lines theme={null}
package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"

    "github.com/yourorg/myapi/internal/auth"
    "github.com/yourorg/myapi/internal/config"
    "github.com/yourorg/myapi/internal/handlers"
    "github.com/joho/godotenv"
)

func main() {
    // .envファイルから環境変数を読み込む
    if err := godotenv.Load(); err != nil {
        log.Println("No .env file found, using environment variables")
    }

    // Auth0の設定を読み込む
    cfg, err := config.LoadAuthConfig()
    if err != nil {
        log.Fatalf("Failed to load config: %v", err)
    }

    // JWTバリデーターを作成する
    jwtValidator, err := auth.NewValidator(cfg.Domain, cfg.Audience)
    if err != nil {
        log.Fatalf("Failed to create validator: %v", err)
    }

    // HTTPミドルウェアを作成する
    middleware, err := auth.NewMiddleware(jwtValidator)
    if err != nil {
        log.Fatalf("Failed to create middleware: %v", err)
    }

    // ルートを設定する
    mux := http.NewServeMux()
    mux.HandleFunc("/api/public", handlers.PublicHandler)
    mux.Handle("/api/private", middleware.CheckJWT(http.HandlerFunc(handlers.PrivateHandler)))
    mux.Handle("/api/private-scoped", middleware.CheckJWT(http.HandlerFunc(handlers.ScopedHandler)))

    // 本番環境向けタイムアウトを設定してサーバーを構成する
    srv := &http.Server{
        Addr:         ":8080",
        Handler:      mux,
        ReadTimeout:  15 * time.Second,
        WriteTimeout: 15 * time.Second,
        IdleTimeout:  60 * time.Second,
    }

    // ゴルーチンでサーバーを起動する
    go func() {
        log.Println("Server starting on :8080")
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("Server failed: %v", err)
        }
    }()

    // グレースフルシャットダウン
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, os.Interrupt)
    <-quit

    log.Println("Shutting down server...")
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    if err := srv.Shutdown(ctx); err != nil {
        log.Fatalf("Server forced to shutdown: %v", err)
    }

    log.Println("Server exited")
}
```

> [accordion] プロジェクト構成
>
> ```
> myapi/
> ├── cmd/
> │   └── server/
> │       └── main.go              # アプリケーションのエントリ ポイント
> ├── internal/
> │   ├── auth/
> │   │   ├── claims.go            # カスタム JWT クレーム
> │   │   ├── middleware.go         # JWT ミドルウェア
> │   │   └── validator.go         # JWT バリデーター
> │   ├── config/
> │   │   └── auth.go              # 設定の読み込み
> │   └── handlers/
> │       └── api.go               # HTTP ハンドラー（公開用、非公開用、スコープが設定されたもの）
> ├── .env                         # 環境変数（コミット対象外）
> ├── .gitignore
> ├── go.mod
> └── go.sum
> ```

**8. APIの実行とテスト**

開発サーバーを起動します。

```shellscript theme={null}
go run cmd/server/main.go
```

次のように表示されます: `Server starting on :8080`

公開エンドポイント (認証は不要) をテストします:

```bash theme={null}
curl http://localhost:8080/api/public
```

以下が表示されます:

```json theme={null}
{
  "message": "Hello from a public endpoint! You don't need to be authenticated to see this."
}
```

トークンを使わずにプライベートエンドポイントをテストします (失敗するはずです) :

```bash theme={null}
curl http://localhost:8080/api/private
```

401 Unauthorized エラーが表示されます:

```json theme={null}
{
  "message": "Failed to validate JWT."
}
```

有効なトークンでテストするには、[Auth0 Dashboard](https://manage.auth0.com/#/apis) で API を開き、**Test** タブをクリックしてアクセストークンをコピーします。次に、以下を実行します。

```bash theme={null}
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     http://localhost:8080/api/private
```

スコープが設定されたエンドポイントをテストします (`read:messages` 権限が必要です) :

```bash theme={null}
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     http://localhost:8080/api/private-scoped
```

> [!TIP]
>
> **チェックポイント**
>
> これで、保護された Go API が用意できたはずです。この API は次のことを行います。
>
> 1. 認証なしでパブリックなエンドポイントへのリクエストを受け付ける
> 2. 有効なトークンがない場合、保護されたエンドポイントへのリクエストを拒否する
> 3. JWT トークンを Auth0 ドメインと audience に対して検証する
> 4. スコープを使用して、権限ベースのアクセス制御を適用する

***

## API の呼び出し

保護された API は、`Authorization` ヘッダーに Bearer トークンとしてアクセストークンを渡すことで、どのアプリケーションからでも呼び出せます。

> [accordion] クライアントコードの例
>
> ```bash cURL theme={null}
> curl --request GET \
>   --url http://localhost:8080/api/private \
>   --header 'authorization: Bearer YOUR_ACCESS_TOKEN'
> ```
>
> ```go Go theme={null}
> package main
>
> import (
>     "fmt"
>     "net/http"
>     "io"
> )
>
> func main() {
>     url := "http://localhost:8080/api/private"
>
>     req, _ := http.NewRequest("GET", url, nil)
>     req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN")
>
>     res, _ := http.DefaultClient.Do(req)
>     defer res.Body.Close()
>
>     body, _ := io.ReadAll(res.Body)
>
>     fmt.Println(res)
>     fmt.Println(string(body))
> }
> ```
>
> ```javascript Node.js theme={null}
> const axios = require("axios").default;
>
> const options = {
>   method: 'GET',
>   url: 'http://localhost:8080/api/private',
>   headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN'}
> };
>
> axios.request(options).then(function (response) {
>   console.log(response.data);
> }).catch(function (error) {
>   console.error(error);
> });
> ```
>
> ```python Python theme={null}
> import http.client
>
> conn = http.client.HTTPConnection("localhost", 8080)
> headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN" }
>
> conn.request("GET", "/api/private", headers=headers)
>
> res = conn.getresponse()
> data = res.read()
>
> print(data.decode("utf-8"))
> ```

> [accordion] アクセストークンの取得
>
> > [tab] シングルページまたはモバイルアプリ
> >
> > シングルページアプリケーションまたはモバイル/ネイティブアプリケーションから API を呼び出す場合は、認可フローが完了するとアクセストークンを取得できます。トークンの取得方法や API の呼び出し方法は、開発しているアプリケーションの種類や使用しているフレームワークによって異なります。
> >
> > > [card] [シングルページアプリケーション](/docs/docs/ja-jp/quickstart/spa)
> > >
> > > React、Vue、Angular の Quickstart とサンプル
> >
> > > [card] [モバイル / ネイティブアプリケーション](/docs/docs/ja-jp/quickstart/native)
> > >
> > > iOS、Android、React Native の Quickstart
>
> > [tab] Machine-to-Machine (M2M)
> >
> > コマンドラインツールや、ユーザーが資格情報を入力しない別のサービスから API を呼び出す場合は、[OAuth クライアント認証情報フロー](/docs/docs/ja-jp/api/authentication#client-credentials) を使用する必要があります。
> >
> > **1. M2M アプリケーションの登録**
> >
> > Auth0 Dashboard で [Machine to Machine Application](https://manage.auth0.com/#/applications) を登録します。
> >
> > **2. 資格情報の取得**
> >
> > [アプリケーション設定](/docs/docs/ja-jp/get-started/applications/application-settings) から **Client ID** と **Client Secret** をコピーします。
> >
> > **3. アクセストークンのリクエスト**
> >
> > クライアント認証情報フローを使用してアクセストークンを取得します。
> >
> > ```bash theme={null}
> > curl --request POST \
> >   --url 'https://YOUR_AUTH0_DOMAIN/oauth/token' \
> >   --header 'content-type: application/x-www-form-urlencoded' \
> >   --data grant_type=client_credentials \
> >   --data 'client_id=YOUR_CLIENT_ID' \
> >   --data client_secret=YOUR_CLIENT_SECRET \
> >   --data audience=YOUR_API_IDENTIFIER
> > ```
> >
> > > [!WARNING]
> > >
> > > **トークンの再利用**: Auth0 では、発行された Machine to Machine アクセストークンの数に基づいて課金されます。アプリケーションがアクセストークンを取得したら、リクエストするトークン数を最小限に抑えるため、有効期限が切れるまでそのトークンを使い続けてください。

***

## 高度な使用方法

> [accordion] DPoP（Proof-of-Possession）セキュリティ
>
> RFC 9449 で定義されている \*\*DPoP (Demonstrating Proof-of-Possession) \*\* は、暗号学的なキー バインディングによってトークンの盗難を防ぎ、セキュリティを強化します。
>
> ```go internal/auth/middleware.go theme={null}
> func NewMiddleware(jwtValidator *validator.Validator) *jwtmiddleware.JWTMiddleware {
>     return jwtmiddleware.New(
>         jwtmiddleware.WithValidator(jwtValidator),
>         jwtmiddleware.WithDPoPMode(jwtmiddleware.DPoPRequired),
>         jwtmiddleware.WithLogger(slog.Default()),
>     )
> }
> ```
>
> **DPoP モード:**
>
> * `DPoPAllowed`  (default) — Bearer と DPoP の両方のトークンを受け入れる
>
> * `DPoPRequired` — DPoP トークンのみを受け入れ、Bearer は拒否する
>
> * `DPoPDisabled` — Bearer トークンのみを受け入れ、DPoP は拒否する
>
> > [!NOTE]
> >
> > DPoP は、金融 API、医療 API、高セキュリティが求められるエンタープライズ アプリケーションに推奨されます。詳しくは [DPoP documentation](https://github.com/auth0/go-jwt-middleware#dpop-support) をご覧ください。

> [accordion] CORS の設定
>
> Web アプリケーションからのリクエストを許可するには、CORS を有効にします。シンプルなミドルウェア、または [rs/cors](https://github.com/rs/cors) のようなライブラリを使用できます。
>
> ```bash theme={null}
> go get github.com/rs/cors
> ```
>
> ```go cmd/server/main.go theme={null}
> import "github.com/rs/cors"
>
> // mux を CORS ミドルウェアでラップする
> handler := cors.New(cors.Options{
>     AllowedOrigins:   []string{"http://localhost:3000"},
>     AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE"},
>     AllowedHeaders:   []string{"Authorization", "Content-Type"},
>     AllowCredentials: true,
> }).Handler(mux)
>
> srv := &http.Server{
>     Addr:    ":8080",
>     Handler: handler,
> }
> ```
>
> 本番環境では、ワイルドカードではなく正確なオリジンを指定してください。

> [accordion] slog を使用した構造化ログ
>
> トークンのバリデーションをデバッグするために、詳細なログを有効にします。
>
> ```go internal/auth/middleware.go theme={null}
> middleware := jwtmiddleware.New(
>     jwtmiddleware.WithValidator(jwtValidator),
>     jwtmiddleware.WithLogger(slog.Default()),
> )
> ```
>
> 起動時の確認を追加します。
>
> ```go cmd/server/main.go theme={null}
> log.Printf("Validator configured:")
> log.Printf("  Issuer: https://%s/", cfg.Domain)
> log.Printf("  Audience: %s", cfg.Audience)
> log.Printf("  Algorithm: RS256")
> ```

***

## トラブルシューティング

> [accordion] よくある問題と解決策
>
> ### "Failed to validate JWT" または 401 Unauthorized
>
> **問題:** API がアクセストークンを見つけられないか、検証できません。
>
> **解決策:**
>
> 1. `Authorization` ヘッダーが含まれていることを確認してください: `Authorization: Bearer YOUR_TOKEN`
> 2. トークンの前に `Bearer` が付いていることを確認してください
> 3. トークンの有効期限が切れていないことを確認してください
> 4. **アクセストークン**を使用しており、ID トークンではないことを確認してください
>
> ### "aud claim mismatch"
>
> **問題:** トークンの audience が API と一致していません。
>
> **解決策:** `AUTH0_AUDIENCE` が Auth0 Dashboard の API 識別子と完全に一致していることを確認してください。audience の末尾にスラッシュを付けてはいけません。
>
> ```bash theme={null}
> # 正しい
> AUTH0_AUDIENCE=https://my-go-api.example.com
>
> # 誤り（末尾にスラッシュあり）
> AUTH0_AUDIENCE=https://my-go-api.example.com/
> ```
>
> クライアントアプリケーション側でも、正しい audience パラメーターを指定してトークンをリクエストする必要があります。
>
> ### "unexpected signing method"
>
> **問題:** トークンのアルゴリズムがバリデーターの設定と一致していません。
>
> **解決策:**
>
> 1. Auth0 はデフォルトで RS256 (非対称) を使用します
> 2. バリデーターで `validator.RS256` を指定していることを確認してください
> 3. 明示的に設定している場合を除き、Auth0 のトークンに `validator.HS256` は使用しないでください
>
> ### JWKS endpoint に接続できない
>
> **問題:** JWKS キャッシュプロバイダーが Auth0 の公開鍵エンドポイントに到達できません。
>
> **解決策:**
>
> 1. Auth0 へのネットワーク接続を確認してください (firewall/プロキシ設定)
> 2. JWKS endpoint を手動でテストしてください: `curl https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json`
> 3. Auth0 のリージョン (us/eu/au) が正しいことを確認してください
>
> ### importパスが間違っている
>
> **問題:** `cannot find package "github.com/auth0/go-jwt-middleware/v3/..."`
>
> **解決策:** すべての import で `/v3` 接尾辞を使用していることを確認してください:
>
> ```go theme={null}
> // 正しい
> import "github.com/auth0/go-jwt-middleware/v3/validator"
>
> // 誤り
> import "github.com/auth0/go-jwt-middleware/validator"
> ```
>
> ### クロックスキュー / トークン期限切れエラー
>
> **問題:** サーバーの時刻がずれているため、有効なトークンが期限切れに見えてしまいます。
>
> **解決策:** バリデーターにはすでに 30 秒のクロックスキュー許容値が含まれています。さらに必要な場合は、次のように調整してください:
>
> ```go theme={null}
> validator.WithAllowedClockSkew(60*time.Second)
> ```
>
> ### クレームの取得に失敗する
>
> **問題:** ジェネリクス使用時に `Failed to retrieve claims` が発生します。
>
> **解決策:** 正しい型パラメーターを使用していることを確認してください:
>
> ```go theme={null}
> claims, err := jwtmiddleware.GetClaims[*validator.ValidatedClaims](r.Context())
> ```

***

## 次のステップ

保護されたAPIの準備ができたら、次の項目も確認してみましょう。

* **[ロールベースのアクセス制御](/docs/docs/ja-jp/manage-users/access-control/rbac)** — きめ細かな権限を実装する
* **[アクセストークンのベストプラクティス](/docs/docs/ja-jp/secure/tokens/access-tokens)** — トークンのセキュリティについて学ぶ
* **[APIを監視する](/docs/docs/ja-jp/deploy-monitor/logs)** — ログと監視を設定する
* **[本番環境準備チェック](/docs/docs/ja-jp/deploy-monitor/pre-deployment-checks/production-checks-best-practices)** — ローンチ前のセキュリティレビュー

***

## リソース

* **[go-jwt-middleware GitHub](https://github.com/auth0/go-jwt-middleware)** — ソースコード、サンプル、DPoP のサポート
* **[Go API Sample](https://github.com/auth0-samples/auth0-golang-api-samples)** — 完全に動作するサンプル
* **[Auth0 Community](https://community.auth0.com/)** — Auth0 Community でサポートを受ける
