auth0-springboot-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Spring Boot API Integration
Auth0 Spring Boot API集成
Protect Spring Boot API endpoints with JWT access token validation using . Features auto-configuration, scope-based authorization, and built-in DPoP (RFC 9449) support.
com.auth0:auth0-springboot-apiAgent instruction: Before providing SDK setup instructions, fetch the latest release version by running:bashgh 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
使用通过JWT访问令牌验证保护Spring Boot API端点。具备自动配置、基于范围的授权以及内置DPoP(RFC 9449)支持功能。
com.auth0:auth0-springboot-apiAgent指令: 在提供SDK设置说明之前,先运行以下命令获取最新版本:bashgh 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 skill first
auth0-quickstart
- Java 17+ 和 Spring Boot 3.2+
- Maven 3.6+ 或 Gradle 7+
- 已配置Auth0 API(注意:必须是API资源,而非应用程序)
- 如果尚未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用场景
| Use Case | Recommended Skill |
|---|---|
| Server-rendered web applications (Spring MVC with sessions) | Use |
| Single Page Applications | Use |
| Mobile applications | Use |
| Non-Spring Java APIs | Use |
| 使用场景 | 推荐技能 |
|---|---|
| 服务端渲染的Web应用(带会话的Spring MVC) | 对带登录UI的Spring Boot Web应用使用 |
| 单页应用 | 客户端认证使用 |
| 移动应用 | 原生移动应用使用 |
| 非Spring Java API | 纯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.
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?
- Automated — I'll run Auth0 CLI scripts that create the resource and write the values to your application.yml automatically.
- Manual — You create the API yourself in the Auth0 Dashboard (or via
) and provide me the Domain and Audience.auth0 apis createWhich 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 for you — skip Step 3 below and proceed directly to Step 4.
application.ymlIf 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资源?
- 自动化——我将运行Auth0 CLI脚本创建资源,并自动将值写入你的application.yml。
- 手动——你自行在Auth0控制台(或通过
)创建API,然后提供Domain和Audience。auth0 apis create你偏好哪种方式?(1 = 自动化 / 2 = 手动)"在用户答复前,请勿进行任何设置步骤。请勿默认选择手动方式。
如果用户选择自动化,请遵循设置指南中的完整CLI脚本。自动化流程会为你写入——跳过下方的步骤3,直接进入步骤4。
application.yml如果用户选择手动,请遵循设置指南(手动设置章节)。然后继续步骤3。
手动创建API的快速参考:
bash
undefinedUsing Auth0 CLI
使用Auth0 CLI
Or create manually in Auth0 Dashboard → Applications → APIs
或在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 . The library constructs the issuer URL automatically.
https://Or use :
application.propertiesproperties
auth0.domain=your-tenant.auth0.com
auth0.audience=https://my-springboot-apiyaml
auth0:
domain: "your-tenant.auth0.com"
audience: "https://my-springboot-api"重要提示: Domain不得包含。库会自动构造颁发者URL。
https://或使用:
application.propertiesproperties
auth0.domain=your-tenant.auth0.com
auth0.audience=https://my-springboot-api4. 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 bootRunor. If build fails, diagnose and fix. After 5-6 failed attempts, use./mvnw spring-boot:runto get help.AskUserQuestion
Test public endpoint:
bash
curl http://localhost:8080/api/publicTest 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或。如果构建失败,请诊断并修复。若尝试5-6次仍失败,请使用./mvnw spring-boot:run寻求帮助。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
常见错误
| Mistake | Fix |
|---|---|
Domain includes | Use |
| 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 | |
| Using ID token instead of access token | Must use access token for API auth, not ID token |
Checking | Scopes map to |
| Spring Boot env var binding | Use |
| 错误 | 修复方案 |
|---|---|
Domain包含 | 仅使用 |
| Audience与API标识符不匹配 | 必须与Auth0控制台中设置的API标识符完全一致 |
| 在Auth0中创建了应用程序而非API | 必须在Auth0控制台 → 应用程序 → API中创建API资源 |
SecurityConfig中缺少 | |
| 使用ID令牌而非访问令牌 | API认证必须使用访问令牌,而非ID令牌 |
错误格式检查 | 范围会映射为带 |
| Spring Boot环境变量绑定 | 使用 |
Scope-Based Authorization
基于范围的授权
See Integration Guide for defining and enforcing scope-based access control via filter chain, , or programmatic checks.
@PreAuthorize请参阅集成指南,了解如何通过过滤器链、或程序化检查定义和实施基于范围的访问控制。
@PreAuthorizeDPoP 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
相关技能
- — Basic Auth0 setup and account creation
auth0-quickstart - — Spring Boot web apps with login UI (Regular Web Application)
auth0-java
- —— 基础Auth0设置和账户创建
auth0-quickstart - —— 带登录UI的Spring Boot Web应用(常规Web应用)
auth0-java
Quick Reference
快速参考
Configuration Properties ():
application.yml- — Auth0 tenant domain, no
auth0.domainprefix (required)https:// - — API Identifier from Auth0 API settings (required)
auth0.audience - — DPoP mode:
auth0.dpop-mode,DISABLED(default),ALLOWEDREQUIRED - — DPoP proof time window (default: 300)
auth0.dpop-iat-offset-seconds - — DPoP proof time leeway (default: 30)
auth0.dpop-iat-leeway-seconds
User Claims (via ):
Auth0AuthenticationToken- — User ID (subject /
authentication.getName()claim)sub - — Any specific claim by name
token.getClaim("email") - — All JWT claims as
token.getClaims()Map<String, Object> - — Scopes as
token.getScopes()Set<String>
Common Use Cases:
- Protect routes → (see Step 4)
requestMatchers("/path").authenticated() - Scope enforcement → or
hasAuthority("SCOPE_read:data")(see Integration Guide)@PreAuthorize - DPoP token binding → Integration Guide
- Complete API reference → API Reference
配置属性():
application.yml- —— Auth0租户域名,无
auth0.domain前缀(必填)https:// - —— Auth0 API设置中的API标识符(必填)
auth0.audience - —— DPoP模式:
auth0.dpop-mode、DISABLED(默认)、ALLOWEDREQUIRED - —— DPoP证明时间窗口(默认:300)
auth0.dpop-iat-offset-seconds - —— DPoP证明时间容错(默认:30)
auth0.dpop-iat-leeway-seconds
用户声明(通过):
Auth0AuthenticationToken- —— 用户ID(主体 /
authentication.getName()声明)sub - —— 按名称获取特定声明
token.getClaim("email") - —— 所有JWT声明,格式为
token.getClaims()Map<String, Object> - —— 范围,格式为
token.getScopes()Set<String>
常见使用场景:
- 保护路由 → (见步骤4)
requestMatchers("/path").authenticated() - 范围强制 → 或
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参考 —— 完整配置选项、声明参考、测试清单