auth0-springboot-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Spring Boot API Integration

Auth0 Spring Boot API集成

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:
bash
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
.
使用
com.auth0:auth0-springboot-api
通过JWT访问令牌验证保护Spring Boot API端点。具备自动配置、基于范围的授权以及内置DPoP(RFC 9449)支持功能。

Agent指令: 在提供SDK设置说明之前,先运行以下命令获取最新版本:
bash
gh api repos/auth0/auth0-auth-java/releases/latest --jq '.tag_name'
将返回的版本替换以下所有依赖行中的硬编码版本。如果API调用失败(例如暂无版本发布),则使用
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
  • Java 17+ 和 Spring Boot 3.2+
  • Maven 3.6+ 或 Gradle 7+
  • 已配置Auth0 API(注意:必须是API资源,而非应用程序)
  • 如果尚未设置Auth0,请先使用
    auth0-quickstart
    技能

When NOT to Use

不适用场景

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

使用场景推荐技能
服务端渲染的Web应用(带会话的Spring MVC)对带登录UI的Spring Boot Web应用使用
auth0-java
单页应用客户端认证使用
auth0-react
auth0-vue
auth0-angular
移动应用原生移动应用使用
auth0-android
auth0-swift
非Spring Java API纯Spring Security使用
auth0-spring-security-api

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.
Agent指令: 如果用户的提示已提供Auth0凭证(domain、audience),请直接使用——跳过引导脚本和凭证问题。仅当凭证缺失时提供设置选项。

1. Install SDK

1. 安装SDK

Gradle (build.gradle):
groovy
implementation 'com.auth0:auth0-springboot-api:1.0.0-beta.1'
Maven (pom.xml):
xml
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>auth0-springboot-api</artifactId>
    <version>1.0.0-beta.1</version>
</dependency>
Gradle(build.gradle):
groovy
implementation 'com.auth0:auth0-springboot-api:1.0.0-beta.1'
Maven(pom.xml):
xml
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>auth0-springboot-api</artifactId>
    <version>1.0.0-beta.1</version>
</dependency>

2. Create Auth0 API

2. 创建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:
bash
undefined
你需要在Auth0中创建一个API(而非应用程序)。
暂停——继续前请询问用户。
请准确询问以下问题,等待用户答复后再进行后续操作:
"你希望如何创建Auth0 API资源?
  1. 自动化——我将运行Auth0 CLI脚本创建资源,并自动将值写入你的application.yml。
  2. 手动——你自行在Auth0控制台(或通过
    auth0 apis create
    )创建API,然后提供Domain和Audience。
你偏好哪种方式?(1 = 自动化 / 2 = 手动)"
在用户答复前,请勿进行任何设置步骤。请勿默认选择手动方式。
如果用户选择自动化,请遵循设置指南中的完整CLI脚本。自动化流程会为你写入
application.yml
——跳过下方的步骤3,直接进入步骤4。
如果用户选择手动,请遵循设置指南(手动设置章节)。然后继续步骤3。
手动创建API的快速参考:
bash
undefined

Using Auth0 CLI

使用Auth0 CLI

auth0 apis create
--name "My Spring Boot API"
--identifier https://my-springboot-api

Or create manually in Auth0 Dashboard → Applications → APIs
auth0 apis create
--name "My Spring Boot API"
--identifier https://my-springboot-api

或在Auth0控制台 → 应用程序 → API中手动创建

3. Configure application.yml

3. 配置application.yml

yaml
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
:
properties
auth0.domain=your-tenant.auth0.com
auth0.audience=https://my-springboot-api
yaml
auth0:
  domain: "your-tenant.auth0.com"
  audience: "https://my-springboot-api"
重要提示: Domain不得包含
https://
。库会自动构造颁发者URL。
或使用
application.properties
properties
auth0.domain=your-tenant.auth0.com
auth0.audience=https://my-springboot-api

4. Configure Spring Security

4. 配置Spring Security

java
@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();
    }
}
java
@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

5. 保护端点

java
@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()
        ));
    }
}
java
@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

6. 测试API

Agent instruction: After writing all code, verify the build succeeds:
bash
./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:
bash
curl http://localhost:8080/api/public
Test protected endpoint (requires access token):
bash
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.

Agent指令: 编写完所有代码后,验证构建是否成功:
bash
./gradlew bootRun
./mvnw spring-boot:run
。如果构建失败,请诊断并修复。若尝试5-6次仍失败,请使用
AskUserQuestion
寻求帮助。
测试公开端点:
bash
curl http://localhost:8080/api/public
测试受保护端点(需要访问令牌):
bash
curl http://localhost:8080/api/protected \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
通过客户端凭证流或Auth0控制台 → API → 测试标签获取测试令牌。

Common Mistakes

常见错误

MistakeFix
Domain includes
https://
Use
your-tenant.auth0.com
format only — no scheme prefix
Audience doesn't match API IdentifierMust exactly match the API Identifier set in Auth0 Dashboard
Created Application instead of API in Auth0Must create API resource in Auth0 Dashboard → Applications → APIs
Missing
addFilterBefore
in SecurityConfig
Auth0AuthenticationFilter
must be added before
UsernamePasswordAuthenticationFilter
Using ID token instead of access tokenMust 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 bindingUse
AUTH0_DOMAIN
not
AUTH0_DOMAIN
with underscores inside property names; Spring removes dashes and is case-insensitive

错误修复方案
Domain包含
https://
仅使用
your-tenant.auth0.com
格式——不要添加协议前缀
Audience与API标识符不匹配必须与Auth0控制台中设置的API标识符完全一致
在Auth0中创建了应用程序而非API必须在Auth0控制台 → 应用程序 → API中创建API资源
SecurityConfig中缺少
addFilterBefore
Auth0AuthenticationFilter
必须添加在
UsernamePasswordAuthenticationFilter
之前
使用ID令牌而非访问令牌API认证必须使用访问令牌,而非ID令牌
错误格式检查
scope
声明
范围会映射为带
SCOPE_
前缀的权限:使用
hasAuthority("SCOPE_read:data")
Spring Boot环境变量绑定使用
AUTH0_DOMAIN
,属性名称内部不要使用下划线;Spring会移除连字符且不区分大小写

Scope-Based Authorization

基于范围的授权

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

请参阅集成指南,了解如何通过过滤器链、
@PreAuthorize
或程序化检查定义和实施基于范围的访问控制。

DPoP Support

DPoP支持

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

内置符合RFC 9449的持有证明令牌绑定功能。请参阅集成指南了解配置模式(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)

  • auth0-quickstart
    —— 基础Auth0设置和账户创建
  • auth0-java
    —— 带登录UI的Spring Boot Web应用(常规Web应用)

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

配置属性(
application.yml
):
  • auth0.domain
    —— Auth0租户域名,无
    https://
    前缀(必填)
  • auth0.audience
    —— Auth0 API设置中的API标识符(必填)
  • auth0.dpop-mode
    —— DPoP模式:
    DISABLED
    ALLOWED
    (默认)、
    REQUIRED
  • auth0.dpop-iat-offset-seconds
    —— DPoP证明时间窗口(默认:300)
  • auth0.dpop-iat-leeway-seconds
    —— DPoP证明时间容错(默认:30)
用户声明(通过
Auth0AuthenticationToken
):
  • authentication.getName()
    —— 用户ID(主体 /
    sub
    声明)
  • token.getClaim("email")
    —— 按名称获取特定声明
  • token.getClaims()
    —— 所有JWT声明,格式为
    Map<String, Object>
  • token.getScopes()
    —— 范围,格式为
    Set<String>
常见使用场景:
  • 保护路由 →
    requestMatchers("/path").authenticated()
    (见步骤4)
  • 范围强制 →
    hasAuthority("SCOPE_read:data")
    @PreAuthorize
    (见集成指南
  • DPoP令牌绑定 → 集成指南
  • 完整API参考 → API参考

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

  • 设置指南 —— Auth0 CLI自动化、环境配置、密钥管理
  • 集成指南 —— 范围策略、DPoP、控制器模式、错误处理
  • API参考 —— 完整配置选项、声明参考、测试清单

References

参考链接