claude-skills/

Anthropic公式スキル・プラグインの日本語ディレクトリ

last sync 22h ago
スキルOfficialsecurity

🔐auth0-springboot-api

プラグイン
auth0
ライセンス
Apache-2.0

説明

次のような場合に使用: Spring Boot の API エンドポイントを、JWT Bearer トークンの検証、スコープベースの認可、または DPoP バインディングによって保護する場合。 アクセストークンを受け取る REST API に対して、`com.auth0:auth0-springboot-api` を統合します。

原文を表示

Use when protecting Spring Boot API endpoints with JWT Bearer token validation, scope-based authorization, or DPoP binding. Integrates com.auth0:auth0-springboot-api for REST APIs receiving access tokens.

ユースケース

  • JWT Bearer トークンを検証するとき
  • スコープベースの認可を行うとき
  • DPoP バインディングで保護するとき
  • REST API でアクセストークンを検証するとき

本文(日本語訳)

Auth0 Spring Boot API インテグレーション

com.auth0:auth0-springboot-api を使用して、JWT アクセストークン検証により Spring Boot API エンドポイントを保護します。 自動設定、スコープベースの認可、および組み込みの DPoP(RFC 9449)サポートを備えています。


Agent への指示: SDK のセットアップ手順を提供する前に、以下を実行して最新リリースバージョンを取得してください:

gh api repos/auth0/auth0-auth-java/releases/latest --jq '.tag_name'

取得したバージョンを、以下に記載されているハードコードされたバージョンの代わりに、すべての依存関係の記述に使用してください。 API 呼び出しが失敗した場合(例: リリースがまだ存在しない)は、1.0.0-beta.1 を使用してください。

前提条件

  • Java 17 以上、および Spring Boot 3.2 以上
  • Maven 3.6 以上、または Gradle 7 以上
  • Auth0 API の設定済み環境(Application ではなく、API リソースとして設定すること)
  • Auth0 をまだセットアップしていない場合は、先に auth0-quickstart スキルを使用してください

このスキルを使用しない場合

ユースケース 推奨スキル
サーバーサイドレンダリングの Web アプリケーション(セッションを使用する Spring MVC) ログイン UI を持つ Spring Boot Web アプリには auth0-java を使用
シングルページアプリケーション クライアントサイド認証には auth0-reactauth0-vue、または auth0-angular を使用
モバイルアプリケーション ネイティブモバイルには auth0-android または auth0-swift を使用
Spring を使用しない Java API 通常の Spring Security には auth0-spring-security-api を使用

クイックスタート ワークフロー

Agent への指示: ユーザーのプロンプトに Auth0 の認証情報(ドメイン、オーディエンス)が既に含まれている場合は、そのまま使用してください。ブートストラップスクリプトの実行や認証情報の確認は省略します。認証情報が不足している場合にのみ、セットアップの選択肢を提示してください。

1. SDK のインストール

Gradle(build.gradle):

implementation 'com.auth0:auth0-springboot-api:1.0.0-beta.1'

Maven(pom.xml):

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>auth0-springboot-api</artifactId>
    <version>1.0.0-beta.1</version>
</dependency>

2. Auth0 API の作成

Auth0 で API(Application ではなく)を作成する必要があります。

いったん停止 — 次に進む前にユーザーに確認してください。

以下の質問をそのまま聞き、回答を得るまで次のステップに進まないでください:

"Auth0 API リソースの作成方法を選択してください:

  1. 自動 — Auth0 CLI スクリプトを実行してリソースを作成し、値を application.yml に自動的に書き込みます。
  2. 手動 — Auth0 ダッシュボード(または auth0 apis create)で API を自分で作成し、ドメインとオーディエンスを提供してください。

どちらを希望しますか?(1 = 自動 / 2 = 手動)"

ユーザーが回答するまで、セットアップ手順には進まないでください。また、手動をデフォルトにしないでください。

自動を選択した場合、完全な CLI スクリプトについては セットアップガイド を参照してください。 自動パスでは application.yml が自動生成されます — 以下のステップ 3 をスキップして、ステップ 4 に直接進んでください。

手動を選択した場合セットアップガイド(手動セットアップのセクション)を参照し、ステップ 3 に進んでください。

手動 API 作成のクイックリファレンス:

# Auth0 CLI を使用する場合
auth0 apis create \
  --name "My Spring Boot API" \
  --identifier https://my-springboot-api

または、Auth0 ダッシュボード → Applications → APIs から手動で作成することもできます。

3. application.yml の設定

auth0:
  domain: "your-tenant.auth0.com"
  audience: "https://my-springboot-api"

重要: ドメインに https:// を含めないでください。ライブラリが発行者 URL を自動的に構築します。

または application.properties を使用することもできます:

auth0.domain=your-tenant.auth0.com
auth0.audience=https://my-springboot-api

4. Spring Security の設定

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain apiSecurity(
            HttpSecurity http,
            Auth0AuthenticationFilter authFilter
    ) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session ->
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public").permitAll()
                .requestMatchers("/api/protected").authenticated()
                .requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
                .anyRequest().authenticated())
            .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }
}

5. エンドポイントの保護

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/public")
    public ResponseEntity<Map<String, Object>> publicEndpoint() {
        return ResponseEntity.ok(Map.of("message", "Public endpoint - no token required"));
    }

    @GetMapping("/protected")
    public ResponseEntity<Map<String, Object>> protectedEndpoint(Authentication authentication) {
        Auth0AuthenticationToken token = (Auth0AuthenticationToken) authentication;
        return ResponseEntity.ok(Map.of(
            "user", authentication.getName(),
            "email", token.getClaim("email"),
            "scopes", token.getScopes()
        ));
    }
}

6. API のテスト

Agent への指示: すべてのコードを記述した後、ビルドが成功することを確認してください:

./gradlew bootRun

または ./mvnw spring-boot:run を実行します。ビルドが失敗した場合は原因を調査して修正してください。 5〜6 回試みても失敗する場合は、AskUserQuestion を使用してサポートを求めてください。

パブリックエンドポイントのテスト:

curl http://localhost:8080/api/public

保護されたエンドポイントのテスト(アクセストークンが必要):

curl http://localhost:8080/api/protected \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

テスト用トークンは、Client Credentials フロー、または Auth0 ダッシュボード → APIs → Test タブから取得できます。


よくあるミス

ミス 修正方法
ドメインに https:// が含まれている your-tenant.auth0.com 形式のみを使用し、スキームのプレフィックスを付けないでください
オーディエンスが API Identifier と一致しない Auth0 ダッシュボードで設定した API Identifier と完全に一致する必要があります
Auth0 で API の代わりに Application を作成した Auth0 ダッシュボード → Applications → APIs で API リソースを作成する必要があります
SecurityConfig に addFilterBefore がない Auth0AuthenticationFilterUsernamePasswordAuthenticationFilter の前に追加する必要があります
アクセストークンの代わりに ID トークンを使用している API 認証には ID トークンではなく アクセストークン を使用してください
scope クレームの形式が誤っている スコープは SCOPE_ プレフィックス付きの authority にマッピングされます。hasAuthority("SCOPE_read:data") の形式を使用してください
Spring Boot の環境変数バインディングの誤り プロパティ名内のアンダースコアに注意してください。Spring はダッシュを除去し、大文字・小文字を区別しません

スコープベースの認可

フィルターチェーン、@PreAuthorize、またはプログラムによるチェックを使用したスコープベースのアクセス制御の定義と適用については、インテグレーションガイド を参照してください。


DPoP サポート

RFC 9449 に基づく、組み込みの Proof-of-Possession トークンバインディングを提供します。 設定モード(DISABLED、ALLOWED、REQUIRED)については、インテグレーションガイド を参照してください。


関連スキル

  • auth0-quickstart — Auth0 の基本セットアップとアカウント作成
  • auth0-java — ログイン UI を持つ Spring Boot Web アプリ(Regular Web Application)

クイックリファレンス

設定プロパティ(application.yml):

  • auth0.domain — Auth0 テナントドメイン。https:// プレフィックスなし(必須)
  • auth0.audience — Auth0 API 設定の API Identifier(必須)
  • auth0.dpop-mode — DPoP モード: DISABLEDALLOWED(デフォルト)、REQUIRED
  • auth0.dpop-iat-offset-seconds — DPoP proof の時間ウィンドウ(デフォルト: 300)
  • auth0.dpop-iat-leeway-seconds — DPoP proof の時間リーウェイ(デフォルト: 30)

ユーザークレーム(Auth0AuthenticationToken 経由):

  • authentication.getName() — ユーザー ID(subject / sub クレーム)
  • token.getClaim("email") — 名前を指定して特定のクレームを取得
  • token.getClaims() — すべての JWT クレームを Map<String, Object> として取得
  • token.getScopes() — スコープを Set<String> として取得

主なユースケース:


詳細ドキュメント


参考リンク

原文(English)を表示

Auth0 Spring Boot API Integration

Protect Spring Boot API endpoints with JWT access token validation using com.auth0:auth0-springboot-api. Features auto-configuration, scope-based authorization, and built-in DPoP (RFC 9449) support.


Agent instruction: Before providing SDK setup instructions, fetch the latest release version by running:

gh api repos/auth0/auth0-auth-java/releases/latest --jq '.tag_name'

Use the returned version in all dependency lines instead of any hardcoded version below. If the API call fails (e.g., no releases yet), use 1.0.0-beta.1.

Prerequisites

  • Java 17+ and Spring Boot 3.2+
  • Maven 3.6+ or Gradle 7+
  • Auth0 API configured (not Application — must be API resource)
  • If you don't have Auth0 set up yet, use the auth0-quickstart skill first

When NOT to Use

Use Case Recommended Skill
Server-rendered web applications (Spring MVC with sessions) Use auth0-java for Spring Boot web apps with login UI
Single Page Applications Use auth0-react, auth0-vue, or auth0-angular for client-side auth
Mobile applications Use auth0-android or auth0-swift for native mobile
Non-Spring Java APIs Use auth0-spring-security-api for plain Spring Security

Quick Start Workflow

Agent instruction: If the user's prompt already provides Auth0 credentials (domain, audience), use them directly — skip the bootstrap script and credential questions. Only offer setup options when credentials are missing.

1. Install SDK

Gradle (build.gradle):

implementation 'com.auth0:auth0-springboot-api:1.0.0-beta.1'

Maven (pom.xml):

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>auth0-springboot-api</artifactId>
    <version>1.0.0-beta.1</version>
</dependency>

2. Create Auth0 API

You need an API (not Application) in Auth0.

STOP — ask the user before proceeding.

Ask exactly this question and wait for their answer before doing anything else:

"How would you like to create the Auth0 API resource?

  1. Automated — I'll run Auth0 CLI scripts that create the resource and write the values to your application.yml automatically.
  2. Manual — You create the API yourself in the Auth0 Dashboard (or via auth0 apis create) and provide me the Domain and Audience.

Which do you prefer? (1 = Automated / 2 = Manual)"

Do NOT proceed to any setup steps until the user has answered. Do NOT default to manual.

If the user chose Automated, follow the Setup Guide for complete CLI scripts. The automated path writes application.yml for you — skip Step 3 below and proceed directly to Step 4.

If the user chose Manual, follow the Setup Guide (Manual Setup section). Then continue with Step 3.

Quick reference for manual API creation:

# Using Auth0 CLI
auth0 apis create \
  --name "My Spring Boot API" \
  --identifier https://my-springboot-api

Or create manually in Auth0 Dashboard → Applications → APIs

3. Configure application.yml

auth0:
  domain: "your-tenant.auth0.com"
  audience: "https://my-springboot-api"

Important: Domain must NOT include https://. The library constructs the issuer URL automatically.

Or use application.properties:

auth0.domain=your-tenant.auth0.com
auth0.audience=https://my-springboot-api

4. Configure Spring Security

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain apiSecurity(
            HttpSecurity http,
            Auth0AuthenticationFilter authFilter
    ) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session ->
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public").permitAll()
                .requestMatchers("/api/protected").authenticated()
                .requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
                .anyRequest().authenticated())
            .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }
}

5. Protect Endpoints

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/public")
    public ResponseEntity<Map<String, Object>> publicEndpoint() {
        return ResponseEntity.ok(Map.of("message", "Public endpoint - no token required"));
    }

    @GetMapping("/protected")
    public ResponseEntity<Map<String, Object>> protectedEndpoint(Authentication authentication) {
        Auth0AuthenticationToken token = (Auth0AuthenticationToken) authentication;
        return ResponseEntity.ok(Map.of(
            "user", authentication.getName(),
            "email", token.getClaim("email"),
            "scopes", token.getScopes()
        ));
    }
}

6. Test API

Agent instruction: After writing all code, verify the build succeeds:

./gradlew bootRun

or ./mvnw spring-boot:run. If build fails, diagnose and fix. After 5-6 failed attempts, use AskUserQuestion to get help.

Test public endpoint:

curl http://localhost:8080/api/public

Test protected endpoint (requires access token):

curl http://localhost:8080/api/protected \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Get a test token via Client Credentials flow or Auth0 Dashboard → APIs → Test tab.


Common Mistakes

Mistake Fix
Domain includes https:// Use your-tenant.auth0.com format only — no scheme prefix
Audience doesn't match API Identifier Must exactly match the API Identifier set in Auth0 Dashboard
Created Application instead of API in Auth0 Must create API resource in Auth0 Dashboard → Applications → APIs
Missing addFilterBefore in SecurityConfig Auth0AuthenticationFilter must be added before UsernamePasswordAuthenticationFilter
Using ID token instead of access token Must use access token for API auth, not ID token
Checking scope claim in wrong format Scopes map to SCOPE_ prefixed authorities: use hasAuthority("SCOPE_read:data")
Spring Boot env var binding Use AUTH0_DOMAIN not AUTH0_DOMAIN with underscores inside property names; Spring removes dashes and is case-insensitive

Scope-Based Authorization

See Integration Guide for defining and enforcing scope-based access control via filter chain, @PreAuthorize, or programmatic checks.


DPoP Support

Built-in proof-of-possession token binding per RFC 9449. See Integration Guide for configuration modes (DISABLED, ALLOWED, REQUIRED).


Related Skills

  • auth0-quickstart — Basic Auth0 setup and account creation
  • auth0-java — Spring Boot web apps with login UI (Regular Web Application)

Quick Reference

Configuration Properties (application.yml):

  • auth0.domain — Auth0 tenant domain, no https:// prefix (required)
  • auth0.audience — API Identifier from Auth0 API settings (required)
  • auth0.dpop-mode — DPoP mode: DISABLED, ALLOWED (default), REQUIRED
  • auth0.dpop-iat-offset-seconds — DPoP proof time window (default: 300)
  • auth0.dpop-iat-leeway-seconds — DPoP proof time leeway (default: 30)

User Claims (via Auth0AuthenticationToken):

  • authentication.getName() — User ID (subject / sub claim)
  • token.getClaim("email") — Any specific claim by name
  • token.getClaims() — All JWT claims as Map<String, Object>
  • token.getScopes() — Scopes as Set<String>

Common Use Cases:

  • Protect routes → requestMatchers("/path").authenticated() (see Step 4)
  • Scope enforcement → hasAuthority("SCOPE_read:data") or @PreAuthorize (see Integration Guide)
  • DPoP token binding → Integration Guide
  • Complete API reference → API Reference

Detailed Documentation

  • Setup Guide — Auth0 CLI automation, environment configuration, secret management
  • Integration Guide — Scope policies, DPoP, controller patterns, error handling
  • API Reference — Complete configuration options, claims reference, testing checklist

References

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。