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

# Go アプリケーションにログイン機能を追加する

> このガイドでは、go-auth0 SDK を使用して Go の Web アプリケーションにユーザーログインを追加する方法を説明します。

> [!NOTE]
>
> **前提条件:** 始める前に、以下がインストールされていることを確認してください。
>
> * **[Go](https://go.dev/doc/install)** 1.25 以降
> * バージョン管理用の **[Git](https://git-scm.com/downloads)**
>
> インストールの確認: `go version`

## はじめに

このクイックスタートでは、Go の Web アプリケーションに Auth0 認証を追加する方法を説明します。[go-auth0](https://github.com/auth0/go-auth0) SDK と Go の標準 `net/http` ライブラリを使用して、ログイン、ログアウト、ユーザープロファイル機能を備えたサーバーサイドアプリを構築します。

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

Go アプリケーション用に新しいディレクトリを作成し、モジュールを初期化します。

```shellscript theme={null}
mkdir myapp && cd myapp
go mod init myapp
```

必要な依存関係をインストールします:

```shellscript theme={null}
go get github.com/auth0/go-auth0/v2
go get github.com/gorilla/sessions
go get github.com/joho/godotenv
```

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

```shellscript theme={null}
mkdir templates
touch .env auth.go handlers.go main.go templates/home.html templates/user.html
```

> [accordion] 想定される go.mod を確認
>
> ```go go.mod theme={null}
> module myapp
>
> go 1.25
>
> require (
>     github.com/auth0/go-auth0/v2 v2.10.0
>     github.com/gorilla/sessions v1.4.0
>     github.com/joho/godotenv v1.5.1
> )
> ```

**2. Auth0アプリケーションを設定する**

Auth0 のサービスを利用するには、Auth0 Dashboard で設定済みのアプリケーションが必要です。Auth0 アプリケーションでは、プロジェクトの認証を設定します。

アプリケーションの **設定** タブから、次の情報を取得する必要があります。

* **Domain**
* **Client ID**
* **Client Secret**

![アプリのダッシュボード](https://cdn2.auth0.com/docs/1.14550.0/media/articles/dashboard/client_settings.png)

Auth0 アプリケーションを設定する方法は 3 つあります。Quick Setup ツールを使用する方法 (推奨) 、CLI コマンドを実行する方法、または Auth0 Dashboard で手動設定する方法です。

> [tab] Quick Setup（推奨）
>
> Auth0 App を作成し、正しい設定値があらかじめ入力された `.env` ファイルをコピーします。

> [tab] CLI
>
> プロジェクトのルートディレクトリで次のコマンドを実行して、Auth0 アプリケーションを作成します。
>
> ```shellscript Mac theme={null}
> # Auth0 CLI をインストールします（まだインストールしていない場合）
> brew tap auth0/auth0-cli && brew install auth0
>
> # Auth0 アプリを設定し、.env ファイルを生成します
> auth0 qs setup --app --type regular --framework vanilla-go --port 3000 --name "My Go App"
> ```
>
> ```powershell Windows theme={null}
> # Auth0 CLI をインストールします（まだインストールしていない場合）
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Auth0 アプリを設定し、.env ファイルを生成します
> auth0 qs setup --app --type regular --framework vanilla-go --port 3000 --name "My Go App"
> ```
>
> 作成後、**Domain**、**Client ID**、**Client Secret** の値をコピーし、`.env` ファイルを作成します。
>
> > [!NOTE]
> >
> > このコマンドでは次のことが行われます。
> >
> > 1. 認証済みかどうかを確認します (必要に応じてログインを求められます)
> > 2. `http://localhost:3000` 用に設定された Auth0 の従来型Webアプリケーションを作成します
> > 3. Auth0 のドメイン、クライアント ID、クライアントシークレットを含む `.env` ファイルを生成します

> [tab] Dashboard
>
> 1. [Auth0 Dashboard](https://manage.auth0.com/dashboard/) にアクセスします
> 2. **アプリケーション** > **アプリケーション** > **Create Application** をクリックします
> 3. ポップアップでアプリの名前を入力し、アプリの種類として `従来型Webアプリケーション` を選択して **Create** をクリックします
> 4. Application Details ページで **設定** タブに切り替えます
> 5. **Domain**、**Client ID**、**Client Secret** の値を確認します
>
> ### callback URL を設定する
>
> callback URL は、ユーザーの認証完了後に Auth0 がリダイレクトするアプリケーション内の URL です。設定していない場合、ログイン後にユーザーはアプリケーションへ戻れません。
>
> **Allowed Callback URLs** に次を設定します。
>
> ```
> http://localhost:3000/callback
> ```
>
> ### ログアウト URL を設定する
>
> ログアウト URL は、ユーザーのログアウト後に Auth0 が戻ることのできるアプリケーション内の URL です。設定していない場合、ユーザーはアプリケーションからログアウトできず、エラーが表示されます。
>
> **Allowed Logout URLs** に次を設定します。
>
> ```
> http://localhost:3000
> ```
>
> ### 環境ファイルを作成する
>
> dashboard の値を使って、プロジェクトのルートディレクトリに `.env` ファイルを作成します。
>
> ```shellscript .env theme={null}
> AUTH0_DOMAIN=YOUR_AUTH0_DOMAIN
> AUTH0_CLIENT_ID=YOUR_AUTH0_CLIENT_ID
> AUTH0_CLIENT_SECRET=YOUR_AUTH0_CLIENT_SECRET
> AUTH0_CALLBACK_URL=http://localhost:3000/callback
> SESSION_SECRET=a-long-random-secret-key-for-cookie-encryption
> ```
>
> > [!WARNING]
> >
> > `YOUR_AUTH0_DOMAIN`、`YOUR_AUTH0_CLIENT_ID`、`YOUR_AUTH0_CLIENT_SECRET` は、アプリケーションの **設定** タブにある実際の値に置き換えてください。

> [!TIP]
>
> `.env` ファイルが存在することを確認します: `cat .env` (Mac/Linux) または `type .env` (Windows)

**3. Auth0 のクライアントを作成する**

`auth.go` ファイルを作成します。これは `go-auth0` の認証用クライアントをラップし、認可 URL を構築するためのヘルパーを提供します。

```go auth.go lines theme={null}
package main

import (
    "context"
    "fmt"
    "net/url"
    "os"

    "github.com/auth0/go-auth0/v2/authentication"
)

// Authenticator は go-auth0 認証クライアントをラップします。
type Authenticator struct {
    *authentication.Authentication
    Domain      string
    ClientID    string
    CallbackURL string
}

// NewAuthenticator は新しい Authenticator を作成して設定します。
func NewAuthenticator() (*Authenticator, error) {
    domain := os.Getenv("AUTH0_DOMAIN")
    clientID := os.Getenv("AUTH0_CLIENT_ID")
    clientSecret := os.Getenv("AUTH0_CLIENT_SECRET")
    callbackURL := os.Getenv("AUTH0_CALLBACK_URL")

    authClient, err := authentication.New(
        context.Background(),
        domain,
        authentication.WithClientID(clientID),
        authentication.WithClientSecret(clientSecret),
    )
    if err != nil {
        return nil, fmt.Errorf("failed to initialize authentication client: %w", err)
    }

    return &Authenticator{
        Authentication: authClient,
        Domain:         domain,
        ClientID:       clientID,
        CallbackURL:    callbackURL,
    }, nil
}

// AuthorizationURL はユーザーを Auth0 の Universal Login ページへ
// リダイレクトするための /authorize URL を構築します。
func (a *Authenticator) AuthorizationURL(state string) string {
    u, _ := url.Parse("https://" + a.Domain + "/authorize")
    params := url.Values{
        "response_type": {"code"},
        "client_id":     {a.ClientID},
        "redirect_uri":  {a.CallbackURL},
        "scope":         {"openid profile email"},
        "state":         {state},
    }
    u.RawQuery = params.Encode()
    return u.String()
}
```

**このコードで行うこと:**

* テナントのドメイン、クライアント ID、クライアントシークレットを使って、`go-auth0` の認証クライアントを初期化します
* 必要な OAuth 2.0 パラメーターを含む `/authorize` リダイレクト URL を構築する `AuthorizationURL` ヘルパーを提供します

**4. ルートハンドラーを作成**

ログイン、コールバック、ユーザープロファイル、ログアウト用のハンドラーを含む`handlers.go`ファイルを作成します。

```go handlers.go expandable lines theme={null}
package main

import (
    "crypto/rand"
    "encoding/base64"
    "encoding/gob"
    "net/http"
    "net/url"
    "os"

    "github.com/auth0/go-auth0/v2/authentication/oauth"
    "github.com/gorilla/sessions"
)

var store *sessions.CookieStore

func init() {
    gob.Register(map[string]interface{}{})
}

func initSessionStore() {
    store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_SECRET")))
    store.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   86400,
        HttpOnly: true,
        Secure:   false, // 本番環境では true に設定してください（HTTPS が必要です）
        SameSite: http.SameSiteLaxMode,
    }
}

// HomeHandler はホームページをレンダリングするか、すでにログイン済みの場合は /user にリダイレクトします。
func HomeHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "auth-session")
    if session.Values["profile"] != nil {
        http.Redirect(w, r, "/user", http.StatusSeeOther)
        return
    }
    if err := templates.ExecuteTemplate(w, "home.html", nil); err != nil {
        http.Error(w, "Internal error", http.StatusInternalServerError)
    }
}

// LoginHandler はユーザーを Auth0 の Universal Login ページにリダイレクトします。
func LoginHandler(auth *Authenticator) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        state, err := generateRandomState()
        if err != nil {
            http.Error(w, "Internal error", http.StatusInternalServerError)
            return
        }

        session, _ := store.Get(r, "auth-session")
        session.Values["state"] = state
        if err := session.Save(r, w); err != nil {
            http.Error(w, "Internal error", http.StatusInternalServerError)
            return
        }

        http.Redirect(w, r, auth.AuthorizationURL(state), http.StatusTemporaryRedirect)
    }
}

// CallbackHandler は認証後に Auth0 から返されるコールバックを処理します。
func CallbackHandler(auth *Authenticator) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        session, _ := store.Get(r, "auth-session")

        // CSRF 攻撃を防ぐために state パラメータを検証します。
        if r.URL.Query().Get("state") != session.Values["state"] {
            http.Error(w, "Invalid state parameter", http.StatusBadRequest)
            return
        }

        // 認可コードをトークンと交換します。
        tokenSet, err := auth.OAuth.LoginWithAuthCode(r.Context(), oauth.LoginWithAuthCodeRequest{
            Code:        r.URL.Query().Get("code"),
            RedirectURI: auth.CallbackURL,
        }, oauth.IDTokenValidationOptions{})
        if err != nil {
            http.Error(w, "Failed to exchange authorization code for token", http.StatusUnauthorized)
            return
        }

        // ユーザーのプロファイル情報を取得します。
        userInfo, err := auth.UserInfo(r.Context(), tokenSet.AccessToken)
        if err != nil {
            http.Error(w, "Failed to get user info", http.StatusInternalServerError)
            return
        }

        session.Values["access_token"] = tokenSet.AccessToken
        session.Values["profile"] = map[string]interface{}{
            "nickname": userInfo.Nickname,
            "name":     userInfo.Name,
            "picture":  userInfo.Picture,
            "email":    userInfo.Email,
        }
        if err := session.Save(r, w); err != nil {
            http.Error(w, "Internal error", http.StatusInternalServerError)
            return
        }

        http.Redirect(w, r, "/user", http.StatusTemporaryRedirect)
    }
}

// UserHandler は認証済みユーザーのプロファイルを表示します。
func UserHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "auth-session")
    profile, ok := session.Values["profile"].(map[string]interface{})
    if !ok {
        http.Redirect(w, r, "/", http.StatusSeeOther)
        return
    }

    if err := templates.ExecuteTemplate(w, "user.html", profile); err != nil {
        http.Error(w, "Internal error", http.StatusInternalServerError)
    }
}

// LogoutHandler はセッションをクリアし、Auth0 のログアウトエンドポイントにリダイレクトします。
func LogoutHandler(auth *Authenticator) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        session, _ := store.Get(r, "auth-session")
        session.Options.MaxAge = -1
        session.Save(r, w)

        logoutURL, _ := url.Parse("https://" + auth.Domain + "/v2/logout")
        scheme := "http"
        if r.TLS != nil {
            scheme = "https"
        }

        returnTo, _ := url.Parse(scheme + "://" + r.Host)
        params := url.Values{}
        params.Add("returnTo", returnTo.String())
        params.Add("client_id", auth.ClientID)
        logoutURL.RawQuery = params.Encode()

        http.Redirect(w, r, logoutURL.String(), http.StatusTemporaryRedirect)
    }
}

func generateRandomState() (string, error) {
    b := make([]byte, 32)
    _, err := rand.Read(b)
    if err != nil {
        return "", err
    }
    return base64.RawURLEncoding.EncodeToString(b), nil
}
```

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

* **LoginHandler** は、CSRF 保護のためにランダムな state parameter を生成し、Auth0 の Universal Login にリダイレクトします
* **CallbackHandler** は、`go-auth0` を使用して authorization code を token に交換し、その後 `UserInfo` を呼び出してユーザーのプロファイルを取得します
* **LogoutHandler** は、セッションをクリアし、Auth0 の `/v2/logout` endpoint にリダイレクトします
* **UserHandler** は、セッションからプロファイルを取得し、template をレンダリングします

**5. HTMLテンプレートを作成**

> [tab] home.html
>
> ```html templates/home.html expandable lines theme={null}
> <!DOCTYPE html>
> <html>
> <head>
>     <meta charset="UTF-8">
>     <meta name="viewport" content="width=device-width, initial-scale=1.0">
>     <title>Auth0 Go Web App</title>
>     <style>
>         * { margin: 0; padding: 0; box-sizing: border-box; }
>         body {
>             font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
>             background: #0a0a0a;
>             color: #e2e8f0;
>             min-height: 100vh;
>             display: flex;
>             align-items: center;
>             justify-content: center;
>         }
>         .container {
>             text-align: center;
>             padding: 3rem;
>             background: #1a1a2e;
>             border-radius: 16px;
>             box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
>             max-width: 440px;
>             width: 90%;
>         }
>         .logo {
>             width: 48px;
>             height: 48px;
>             margin: 0 auto 1.5rem;
>             background: linear-gradient(135deg, #635bff, #00d4aa);
>             border-radius: 12px;
>         }
>         h1 {
>             font-size: 2rem;
>             font-weight: 700;
>             margin-bottom: 0.5rem;
>             color: #f8fafc;
>         }
>         p {
>             color: #94a3b8;
>             font-size: 1.05rem;
>             margin-bottom: 2rem;
>             line-height: 1.6;
>         }
>         .btn {
>             display: inline-block;
>             padding: 0.85rem 2.5rem;
>             background: linear-gradient(135deg, #635bff, #4f46e5);
>             color: #fff;
>             text-decoration: none;
>             border-radius: 8px;
>             font-size: 1rem;
>             font-weight: 600;
>             transition: transform 0.2s, box-shadow 0.2s;
>             box-shadow: 0 4px 14px rgba(99, 91, 255, 0.4);
>         }
>         .btn:hover {
>             transform: translateY(-2px);
>             box-shadow: 0 6px 20px rgba(99, 91, 255, 0.6);
>         }
>         .footer {
>             margin-top: 2rem;
>             font-size: 0.85rem;
>             color: #475569;
>         }
>         .footer a { color: #635bff; text-decoration: none; }
>     </style>
> </head>
> <body>
>     <div class="container">
>         <div class="logo"></div>
>         <h1>Go + Auth0</h1>
>         <p>Secure authentication for your Go web application, powered by Auth0.</p>
>         <a href="/login" class="btn">Sign In</a>
>         <div class="footer">
>             Protected by <a href="https://auth0.com">Auth0</a>
>         </div>
>     </div>
> </body>
> </html>
> ```

> [tab] user.html
>
> ```html templates/user.html expandable lines theme={null}
> <!DOCTYPE html>
> <html>
> <head>
>     <meta charset="UTF-8">
>     <meta name="viewport" content="width=device-width, initial-scale=1.0">
>     <title>Profile</title>
>     <style>
>         * { margin: 0; padding: 0; box-sizing: border-box; }
>         body {
>             font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
>             background: #0a0a0a;
>             color: #e2e8f0;
>             min-height: 100vh;
>             display: flex;
>             align-items: center;
>             justify-content: center;
>         }
>         .container {
>             text-align: center;
>             padding: 3rem;
>             background: #1a1a2e;
>             border-radius: 16px;
>             box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
>             max-width: 440px;
>             width: 90%;
>         }
>         .avatar {
>             display: block;
>             width: 96px;
>             height: 96px;
>             border-radius: 50%;
>             border: 3px solid #635bff;
>             margin: 0 auto 1.5rem;
>             object-fit: cover;
>             background: #2d2d5e;
>         }
>         .avatar[src=""], .avatar:not([src]) {
>             display: none;
>         }
>         .avatar-fallback {
>             width: 96px;
>             height: 96px;
>             border-radius: 50%;
>             border: 3px solid #635bff;
>             margin: 0 auto 1.5rem;
>             background: linear-gradient(135deg, #635bff, #4f46e5);
>             display: none;
>             align-items: center;
>             justify-content: center;
>             font-size: 2rem;
>             font-weight: 700;
>             color: #fff;
>         }
>         .badge {
>             display: inline-block;
>             padding: 0.3rem 0.75rem;
>             background: rgba(0, 212, 170, 0.15);
>             color: #00d4aa;
>             border-radius: 20px;
>             font-size: 0.8rem;
>             font-weight: 600;
>             margin-bottom: 1rem;
>         }
>         h2 {
>             font-size: 1.75rem;
>             font-weight: 700;
>             color: #f8fafc;
>             margin-bottom: 0.25rem;
>         }
>         .email {
>             color: #94a3b8;
>             font-size: 1rem;
>             margin-bottom: 2rem;
>         }
>         .info-card {
>             background: #0f0f23;
>             border-radius: 10px;
>             padding: 1.25rem;
>             margin-bottom: 1.5rem;
>             text-align: left;
>         }
>         .info-row {
>             display: flex;
>             justify-content: space-between;
>             padding: 0.5rem 0;
>             border-bottom: 1px solid #1e293b;
>         }
>         .info-row:last-child { border-bottom: none; }
>         .info-label { color: #64748b; font-size: 0.875rem; }
>         .info-value { color: #e2e8f0; font-size: 0.875rem; font-weight: 500; }
>         .btn-logout {
>             display: inline-block;
>             padding: 0.75rem 2rem;
>             background: transparent;
>             color: #f87171;
>             text-decoration: none;
>             border-radius: 8px;
>             font-size: 0.95rem;
>             font-weight: 600;
>             border: 1px solid #f87171;
>             transition: all 0.2s;
>         }
>         .btn-logout:hover {
>             background: #f87171;
>             color: #0a0a0a;
>         }
>     </style>
> </head>
> <body>
>     <div class="container">
>         <img class="avatar" src="{{ .picture }}" alt="{{ .name }}" onerror="this.style.display='none';document.getElementById('avatar-fallback').style.display='flex';" />
>         <div id="avatar-fallback" class="avatar-fallback">{{ if .nickname }}{{ slice .nickname 0 1 }}{{ else }}?{{ end }}</div>
>         <span class="badge">Authenticated</span>
>         <h2>{{ .nickname }}</h2>
>         <p class="email">{{ .email }}</p>
>         <div class="info-card">
>             <div class="info-row">
>                 <span class="info-label">Full Name</span>
>                 <span class="info-value">{{ .name }}</span>
>             </div>
>             <div class="info-row">
>                 <span class="info-label">Nickname</span>
>                 <span class="info-value">{{ .nickname }}</span>
>             </div>
>             <div class="info-row">
>                 <span class="info-label">Email</span>
>                 <span class="info-value">{{ .email }}</span>
>             </div>
>         </div>
>         <a href="/logout" class="btn-logout">Sign Out</a>
>     </div>
> </body>
> </html>
> ```

**6. メインサーバーを作成する**

`main.go` ですべてを組み合わせます:

```go main.go lines theme={null}
package main

import (
    "html/template"
    "log"
    "net/http"

    "github.com/joho/godotenv"
)

var templates *template.Template

func main() {
    // .env ファイルは省略可能です。Docker では、環境変数は --env-file フラグで渡されます。
    godotenv.Load()

    initSessionStore()

    auth, err := NewAuthenticator()
    if err != nil {
        log.Fatalf("Failed to initialize the authenticator: %v", err)
    }

    templates = template.Must(template.ParseGlob("templates/*.html"))

    mux := http.NewServeMux()
    mux.HandleFunc("/", HomeHandler)
    mux.HandleFunc("/login", LoginHandler(auth))
    mux.HandleFunc("/callback", CallbackHandler(auth))
    mux.HandleFunc("/user", UserHandler)
    mux.HandleFunc("/logout", LogoutHandler(auth))

    log.Print("Server listening on http://localhost:3000/")
    if err := http.ListenAndServe("0.0.0.0:3000", mux); err != nil {
        log.Fatalf("There was an error with the http server: %v", err)
    }
}
```

> [accordion] プロジェクト構成
>
> ```
> myapp/
> ├── main.go          # アプリケーションのエントリーポイントとルーティング
> ├── auth.go          # Auth0クライアントの設定と認可用URL
> ├── handlers.go      # HTTPハンドラー（login、callback、logout、profile）
> ├── templates/
> │   ├── home.html    # サインインリンクのあるホームページ
> │   └── user.html    # ユーザープロファイルページ
> ├── .env             # 環境変数（コミットしない）
> ├── go.mod
> └── go.sum
> ```

**7. アプリケーションを実行してテストする**

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

```shellscript theme={null}
go run .
```

次のように表示されます: `Server listening on http://localhost:3000/`

ブラウザーで [http://localhost:3000](http://localhost:3000) を開きます。**Sign In** をクリックすると、Auth0 の Universal Login ページにリダイレクトされます。認証後、アプリにリダイレクトされ、プロファイル情報が表示されます。

> [!NOTE]
>
> ポート 3000 がすでに使用されている場合は、新しいポートを使うように、`.env` ファイルの `AUTH0_CALLBACK_URL` と、Auth0 の Application Settings にある **Allowed Callback URLs** および **Allowed Logout URLs** を更新してください。

> [!TIP]
>
> **チェックポイント**
>
> これで、Auth0認証を備えた完全に機能する Go の Web アプリケーションが [localhost](http://localhost:3000/) で動作しているはずです。アプリでは次のことができます。
>
> 1. 認証のためにユーザーを Auth0 の Universal Login にリダイレクトする
> 2. `go-auth0` SDK を使用して認可コードをトークンに交換する
> 3. ユーザープロファイル情報を取得して表示する
> 4. セッションをクリーンアップしてログアウトできる

***

## 高度な使い方

> [accordion] ミドルウェアでルートを保護する
>
> 認証が必要なルートを保護するため、`IsAuthenticated` ミドルウェアを作成します。次のコードを `handlers.go` に追加します。
>
> ```go handlers.go theme={null}
> // IsAuthenticated は、ユーザーが
> // 認証済みかどうかを確認するミドルウェアです。
> func IsAuthenticated(next http.Handler) http.Handler {
>     return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
>         session, _ := store.Get(r, "auth-session")
>         if session.Values["profile"] == nil {
>             http.Redirect(w, r, "/", http.StatusSeeOther)
>             return
>         }
>         next.ServeHTTP(w, r)
>     })
> }
> ```
>
> 保護対象のルートには、`main.go` でこのミドルウェアを適用します。
>
> ```go main.go theme={null}
> mux.Handle("/user", IsAuthenticated(http.HandlerFunc(UserHandler)))
> ```

> [accordion] 保護されたAPIを呼び出す
>
> 認証後は、セッションに保存されたアクセストークンを使って保護された API を呼び出せます。
>
> ```go theme={null}
> func ApiHandler(w http.ResponseWriter, r *http.Request) {
>     session, _ := store.Get(r, "auth-session")
>     accessToken, ok := session.Values["access_token"].(string)
>     if !ok {
>         http.Error(w, "Unauthorized", http.StatusUnauthorized)
>         return
>     }
>
>     req, _ := http.NewRequest("GET", "https://your-api.example.com/api/private", nil)
>     req.Header.Add("Authorization", "Bearer "+accessToken)
>
>     res, err := http.DefaultClient.Do(req)
>     if err != nil {
>         http.Error(w, "API request failed", http.StatusInternalServerError)
>         return
>     }
>     defer res.Body.Close()
>
>     w.Header().Set("Content-Type", "application/json")
>     io.Copy(w, res.Body)
> }
> ```
>
> > [!NOTE]
> >
> > API 用のアクセストークンを要求するには、`auth.go` の認可 URL に `audience` パラメータを追加します。
> >
> > ```go theme={null}
> > params := url.Values{
> >     "response_type": {"code"},
> >     "client_id":     {a.ClientID},
> >     "redirect_uri":  {a.CallbackURL},
> >     "scope":         {"openid profile email"},
> >     "audience":      {"https://your-api.example.com"},
> >     "state":         {state},
> > }
> > ```

> [accordion] トークンを更新する
>
> アプリケーションでリフレッシュトークンを使用している場合は、`go-auth0` SDK を使ってリフレッシュトークンを新しいトークンセットに交換できます。
>
> ```go theme={null}
> newTokenSet, err := auth.OAuth.RefreshToken(r.Context(), oauth.RefreshTokenRequest{
>     RefreshToken: storedRefreshToken,
> })
> ```
>
> リフレッシュトークンを受け取るには、認可 URL のスコープに `offline_access` を追加します。
>
> ```go theme={null}
> "scope": {"openid profile email offline_access"},
> ```

***

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

> [accordion] よくある問題と解決策
>
> ### 「認可コードをトークンに交換できませんでした」
>
> **問題:** コールバック ハンドラーが認可コードを交換できません。
>
> **解決策:**
>
> 1. `.env` ファイル内の `AUTH0_CLIENT_SECRET` が正しいことを確認します
> 2. `AUTH0_CALLBACK_URL` が Auth0 のアプリケーション設定の **Allowed Callback URLs** と完全に一致していることを確認します
> 3. 認可コードの有効期限が切れていないことを確認します (コードは 1 回しか使用できず、有効期間も短くなっています)
>
> ### 「ユーザー情報を取得できませんでした」
>
> **問題:** `/userinfo` エンドポイントがエラーを返します。
>
> **解決策:**
>
> 1. 認可 URL に `openid` スコープが含まれていることを確認します
> 2. アクセストークンが有効で、有効期限切れになっていないことを確認します
> 3. Auth0 ドメインへのネットワーク接続を確認します
>
> ### 「無効な state パラメーター」
>
> **問題:** コールバック内の state パラメーターがセッションと一致しません。
>
> **解決策:**
>
> 1. ブラウザーで Cookie が有効になっていることを確認します
> 2. リクエスト間でセッションストアのシークレットが変更されていないことを確認します
> 3. ログインフロー中に複数のブラウザータブを使用していないことを確認します
>
> ### ユーザーがログアウトできない
>
> **問題:** ログアウトをクリックした後、ユーザーに Auth0 のエラーページが表示されます。
>
> **解決策:**
>
> 1. `http://localhost:3000` が Auth0 のアプリケーション設定の **Allowed Logout URLs** に含まれていることを確認します
> 2. `client_id` パラメーターがアプリケーションのクライアント IDと一致していることを確認します
> 3. `returnTo` URL が許可されているログアウト URL のいずれか 1 つと完全に一致していることを確認します
>
> ### セッションデータが保持されない
>
> **問題:** リクエスト間でユーザープロファイルデータが消えてしまいます。
>
> **解決策:**
>
> 1. データを保存する前に `gob.Register(map[string]interface{}{})` が呼び出されていることを確認します
> 2. セッションの値を変更した後に `session.Save(r, w)` が呼び出されていることを確認します
> 3. ブラウザーの設定によって Cookie がブロックされていないことを確認します

***

## 次のステップ

認証が機能するようになったら、次の内容も確認してみましょう。

* **[ユーザープロファイル](/docs/docs/ja-jp/manage-users/user-accounts/user-profiles)** — 認証後に利用できるユーザー情報について学ぶ
* **[他のアイデンティティプロバイダーを設定する](/docs/docs/ja-jp/authenticate/identity-providers)** — ソーシャルまたはエンタープライズのログインオプションを追加する
* **[多要素認証を有効にする](/docs/docs/ja-jp/secure/multi-factor-authentication)** — セキュリティをさらに強化する
* **[アクセストークンのベストプラクティス](/docs/docs/ja-jp/secure/tokens/access-tokens)** — トークンのセキュリティについて学ぶ
* **[本番環境チェックリスト](/docs/docs/ja-jp/deploy-monitor/pre-deployment-checks/how-to-run-production-checks)** — ローンチ前のセキュリティレビュー

***

## リソース

* **[go-auth0 GitHub](https://github.com/auth0/go-auth0)** — ソースコードとドキュメント
* **[Go Web App Sample](https://github.com/auth0-samples/auth0-golang-web-app/tree/master/01-Login-Quickstart)** — 完全に動作するサンプル
* **[Auth0 Community](https://community.auth0.com/)** — コミュニティでサポートを受ける
