auth0-java-mvc-common
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 Java MVC Common Integration
Auth0 Java MVC Common 集成
Add Auth0 authentication to Java Servlet web applications using . Provides for building authorize URLs and handling callbacks, with session-based authentication and support for Organizations and Multiple Custom Domains.
com.auth0:mvc-auth-commonsAuthenticationControllerAgent instruction: Before providing SDK setup instructions, fetch the latest release version by running:bashgh api repos/auth0/auth0-java-mvc-common/releases/latest --jq '.tag_name'Use the returned version in all dependency lines instead of any hardcoded version below. If the API call fails, use.1.12.0
使用为Java Servlet Web应用添加Auth0认证功能。提供用于构建授权URL和处理回调,支持会话式认证、Organizations及多自定义域名(Multiple Custom Domains)。
com.auth0:mvc-auth-commonsAuthenticationControllerAgent 指令: 在提供SDK安装说明前,请先运行以下命令获取最新版本:bashgh api repos/auth0/auth0-java-mvc-common/releases/latest --jq '.tag_name'将返回的版本号替换以下所有依赖配置中的硬编码版本。若API调用失败,则使用。1.12.0
Prerequisites
前提条件
- Java 8+ (Java 17+ recommended)
- Servlet container (Tomcat, Jetty, etc.) with javax.servlet 3+
- Maven 3.6+ or Gradle 7+
- Auth0 Regular Web Application configured
- If you don't have Auth0 set up yet, use the skill first
auth0-quickstart
- Java 8及以上版本(推荐Java 17+)
- 支持javax.servlet 3+的Servlet容器(如Tomcat、Jetty等)
- Maven 3.6+ 或 Gradle 7+
- 已配置Auth0常规Web应用(Regular Web Application)
- 若尚未搭建Auth0环境,请先使用技能
auth0-quickstart
When NOT to Use
不适用于以下场景
| Use Case | Recommended Skill |
|---|---|
| Spring Boot web applications with auto-configuration | Use Spring Boot + Okta starter for auto-configured Spring Boot login |
| Spring Boot REST APIs (stateless JWT) | Use |
| Single Page Applications | Use |
| Mobile applications | Use |
| Machine-to-machine API calls | Use Auth0 Management API SDK for server-to-server |
| 使用场景 | 推荐技能 |
|---|---|
| 带自动配置的Spring Boot Web应用 | 使用Spring Boot + Okta starter实现自动配置的Spring Boot登录 |
| Spring Boot REST API(无状态JWT) | 使用 |
| 单页应用(SPA) | 使用 |
| 移动应用 | 使用 |
| 机器对机器API调用 | 使用Auth0 Management API SDK实现服务器间认证 |
Quick Start Workflow
快速开始流程
Agent instruction: If the user's prompt already provides Auth0 credentials (domain, client ID, client secret), use them directly — skip the bootstrap script and credential questions. Only offer setup options when credentials are missing.
Agent 指令: 如果用户的提示中已提供Auth0凭证(域名、客户端ID、客户端密钥),请直接使用——跳过引导脚本和凭证询问步骤。仅当凭证缺失时才提供设置选项。
1. Install SDK
1. 安装SDK
Gradle (build.gradle):
groovy
implementation 'com.auth0:mvc-auth-commons:1.12.0'Maven (pom.xml):
xml
<dependency>
<groupId>com.auth0</groupId>
<artifactId>mvc-auth-commons</artifactId>
<version>1.12.0</version>
</dependency>Gradle(build.gradle):
groovy
implementation 'com.auth0:mvc-auth-commons:1.12.0'Maven(pom.xml):
xml
<dependency>
<groupId>com.auth0</groupId>
<artifactId>mvc-auth-commons</artifactId>
<version>1.12.0</version>
</dependency>2. Create Auth0 Application
2. 创建Auth0应用
You need a Regular Web Application (not SPA or Native) 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 application?
- Automated — I'll run Auth0 CLI scripts that create the application and write the values to your config automatically.
- Manual — You create the application yourself in the Auth0 Dashboard (or via
) and provide me the Domain, Client ID, and Client Secret.auth0 apps 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 configuration 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 application creation:
bash
undefined你需要在Auth0中创建一个常规Web应用(Regular Web Application),而非SPA或原生应用。
暂停操作——请先询问用户。请严格按照以下问题提问,等待用户回复后再继续:"你希望如何创建Auth0应用?
- 自动化——我将运行Auth0 CLI脚本创建应用,并自动将配置值写入你的配置文件。
- 手动——你自行在Auth0控制台(或通过
命令)创建应用,并提供域名、客户端ID和客户端密钥。auth0 apps create你更倾向于哪种方式?(1 = 自动化 / 2 = 手动)"在用户回复前,请勿进行任何后续设置步骤,不要默认选择手动方式。
若用户选择自动化,请遵循设置指南中的完整CLI脚本操作。自动化流程会自动写入配置信息——跳过下方步骤3,直接进入步骤4。
若用户选择手动,请遵循设置指南中的手动设置部分。完成后继续步骤3。
手动创建应用快速参考:
bash
undefinedUsing Auth0 CLI
使用Auth0 CLI
auth0 apps create
--name "My Java Web App"
--type regular
--callbacks http://localhost:3000/callback
--logout-urls http://localhost:3000
--name "My Java Web App"
--type regular
--callbacks http://localhost:3000/callback
--logout-urls http://localhost:3000
Or create manually in Auth0 Dashboard → Applications → Applications → Create Application → Regular Web Applicationsauth0 apps create
--name "My Java Web App"
--type regular
--callbacks http://localhost:3000/callback
--logout-urls http://localhost:3000
--name "My Java Web App"
--type regular
--callbacks http://localhost:3000/callback
--logout-urls http://localhost:3000
或手动在Auth0控制台创建:应用 → 应用 → 创建应用 → 常规Web应用3. Configure Credentials
3. 配置凭证
Store credentials as environment variables (never hardcode in source):
bash
export AUTH0_DOMAIN="your-tenant.auth0.com"
export AUTH0_CLIENT_ID="your-client-id"
export AUTH0_CLIENT_SECRET="your-client-secret"Or use a file (add to ):
.env.gitignoreproperties
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secretAgent instruction: Java does not auto-loadfiles..envonly reads OS-level environment variables. If you generate aSystem.getenv()file, you must also either: (1) add dotenv-java as a dependency and use.envinstead ofDotenv.load().get("AUTH0_DOMAIN"), or (2) instruct the user to runSystem.getenv()before starting the server. Do not generate code that uses both asource .envfile and.envwithout a loading mechanism — the values will beSystem.getenv().null
Important: Domain must NOT include . The library constructs the issuer URL automatically.
https://将凭证存储为环境变量(切勿硬编码到源码中):
bash
export AUTH0_DOMAIN="your-tenant.auth0.com"
export AUTH0_CLIENT_ID="your-client-id"
export AUTH0_CLIENT_SECRET="your-client-secret"或使用文件(需添加到):
.env.gitignoreproperties
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secretAgent 指令: Java不会自动加载文件。.env仅读取系统级环境变量。若生成System.getenv()文件,你必须同时执行以下操作之一:(1) 添加dotenv-java作为依赖,并使用.env替代Dotenv.load().get("AUTH0_DOMAIN");(2) 指导用户在启动服务器前运行System.getenv()。请勿生成同时使用source .env文件和.env但无加载机制的代码——否则值会为System.getenv()。null
重要提示: 域名不得包含。库会自动构造颁发者URL。
https://4. Initialize AuthenticationController
4. 初始化AuthenticationController
Create a singleton instance:
AuthenticationControllerjava
import com.auth0.AuthenticationController;
import com.auth0.jwk.JwkProviderBuilder;
import com.auth0.jwk.JwkProvider;
public class Auth0Config {
private static final AuthenticationController controller = createController();
private static AuthenticationController createController() {
String domain = System.getenv("AUTH0_DOMAIN");
String clientId = System.getenv("AUTH0_CLIENT_ID");
String clientSecret = System.getenv("AUTH0_CLIENT_SECRET");
JwkProvider jwkProvider = new JwkProviderBuilder(domain).build();
return AuthenticationController.newBuilder(domain, clientId, clientSecret)
.withJwkProvider(jwkProvider)
.build();
}
public static AuthenticationController getAuthController() {
return controller;
}
}创建单例实例:
AuthenticationControllerjava
import com.auth0.AuthenticationController;
import com.auth0.jwk.JwkProviderBuilder;
import com.auth0.jwk.JwkProvider;
public class Auth0Config {
private static final AuthenticationController controller = createController();
private static AuthenticationController createController() {
String domain = System.getenv("AUTH0_DOMAIN");
String clientId = System.getenv("AUTH0_CLIENT_ID");
String clientSecret = System.getenv("AUTH0_CLIENT_SECRET");
JwkProvider jwkProvider = new JwkProviderBuilder(domain).build();
return AuthenticationController.newBuilder(domain, clientId, clientSecret)
.withJwkProvider(jwkProvider)
.build();
}
public static AuthenticationController getAuthController() {
return controller;
}
}5. Create Login Servlet
5. 创建登录Servlet
java
import com.auth0.AuthenticationController;
import com.auth0.AuthorizeUrl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AuthenticationController controller = Auth0Config.getAuthController();
// Build callback URL — omit port for standard ports (80/443) to avoid
// mismatch with the URL registered in Auth0 Dashboard, especially behind proxies.
String scheme = request.getScheme();
int port = request.getServerPort();
String redirectUrl = scheme + "://" + request.getServerName()
+ ((port == 80 || port == 443) ? "" : ":" + port) + "/callback";
AuthorizeUrl authorizeUrl = controller.buildAuthorizeUrl(request, response, redirectUrl)
.withScope("openid profile email");
response.sendRedirect(authorizeUrl.build());
}
}java
import com.auth0.AuthenticationController;
import com.auth0.AuthorizeUrl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AuthenticationController controller = Auth0Config.getAuthController();
// 构建回调URL — 标准端口(80/443)省略端口号,避免与Auth0控制台中注册的URL不匹配,尤其是在代理环境下。
String scheme = request.getScheme();
int port = request.getServerPort();
String redirectUrl = scheme + "://" + request.getServerName()
+ ((port == 80 || port == 443) ? "" : ":" + port) + "/callback";
AuthorizeUrl authorizeUrl = controller.buildAuthorizeUrl(request, response, redirectUrl)
.withScope("openid profile email");
response.sendRedirect(authorizeUrl.build());
}
}6. Create Callback Servlet
6. 创建回调Servlet
java
import com.auth0.AuthenticationController;
import com.auth0.IdentityVerificationException;
import com.auth0.Tokens;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/callback"})
public class CallbackServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AuthenticationController controller = Auth0Config.getAuthController();
try {
Tokens tokens = controller.handle(request, response);
request.getSession().setAttribute("accessToken", tokens.getAccessToken());
request.getSession().setAttribute("idToken", tokens.getIdToken());
response.sendRedirect("/dashboard");
} catch (IdentityVerificationException e) {
response.sendRedirect("/login?error=" + e.getCode());
}
}
}java
import com.auth0.AuthenticationController;
import com.auth0.IdentityVerificationException;
import com.auth0.Tokens;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/callback"})
public class CallbackServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
AuthenticationController controller = Auth0Config.getAuthController();
try {
Tokens tokens = controller.handle(request, response);
request.getSession().setAttribute("accessToken", tokens.getAccessToken());
request.getSession().setAttribute("idToken", tokens.getIdToken());
response.sendRedirect("/dashboard");
} catch (IdentityVerificationException e) {
response.sendRedirect("/login?error=" + e.getCode());
}
}
}7. Protect Routes with Authentication Middleware (Servlet Filter)
7. 使用认证中间件保护路由(Servlet Filter)
java
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(urlPatterns = {"/dashboard/*", "/api/private/*"})
public class AuthenticationFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("idToken") == null) {
response.sendRedirect("/login");
return;
}
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}java
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(urlPatterns = {"/dashboard/*", "/api/private/*"})
public class AuthenticationFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("idToken") == null) {
response.sendRedirect("/login");
return;
}
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}8. Test Application
8. 测试应用
Agent instruction: After writing all code, verify the build succeeds:bash./gradlew buildor. If build fails, diagnose and fix. After 5-6 failed attempts, usemvn packageto get help.AskUserQuestion
- Start the application and navigate to
http://localhost:3000/login - You should be redirected to the Auth0 Universal Login page
- After login, the callback servlet handles the response and redirects to
/dashboard
Agent 指令: 写完所有代码后,验证构建是否成功:bash./gradlew build或。若构建失败,请排查并修复。若尝试5-6次仍失败,请使用mvn package寻求帮助。AskUserQuestion
- 启动应用并访问
http://localhost:3000/login - 你将被重定向到Auth0通用登录页面
- 登录后,回调Servlet会处理响应并将你重定向到
/dashboard
Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
Domain includes | Use |
| Client secret hardcoded in source | Use environment variables or |
| Created SPA or Native app instead of Regular Web | Must create Regular Web Application in Auth0 Dashboard |
| Callback URL mismatch | Callback URL in code must exactly match what's registered in Auth0 Dashboard |
Missing | Always include |
Not handling | Always catch this in the callback handler to show login errors |
Using | Regular web apps must use |
| Session not invalidated on logout | Call |
| 错误 | 修复方案 |
|---|---|
域名包含 | 仅使用 |
| 客户端密钥硬编码到源码中 | 使用环境变量或 |
| 创建了SPA或原生应用而非常规Web应用 | 必须在Auth0控制台创建常规Web应用 |
| 回调URL不匹配 | 代码中的回调URL必须与Auth0控制台中注册的URL完全一致 |
缺少 | 权限中必须包含 |
未处理 | 必须在回调处理器中捕获该异常以显示登录错误 |
使用 | 常规Web应用必须使用 |
| 登出时未使会话失效 | 重定向到Auth0登出页面之前,调用 |
Scope and Audience Configuration
权限与受众配置
See Integration Guide for requesting custom scopes, audience for API access tokens, and Organizations support.
如需请求自定义权限、API访问令牌的受众,以及Organizations支持,请查看集成指南。
Multiple Custom Domains (MCD)
多自定义域名(MCD)
Built-in support for routing users to the correct Auth0 domain via . See Integration Guide for configuration.
DomainResolver通过内置支持将用户路由到正确的Auth0域名。配置方法请查看集成指南。
DomainResolverRelated Skills
相关技能
- — Basic Auth0 setup and account creation
auth0-quickstart - — Spring Boot REST APIs with JWT Bearer token validation
auth0-springboot-api
- — Auth0基础设置与账户创建
auth0-quickstart - — 基于JWT Bearer令牌验证的Spring Boot REST API
auth0-springboot-api
Quick Reference
快速参考
Core Classes:
- — Main entry point, builds authorize URLs and handles callbacks
AuthenticationController - — Configures the controller via
AuthenticationController.BuildernewBuilder(domain, clientId, clientSecret) - — Fluent builder for
AuthorizeUrlURL parameters/authorize - — Access token, ID token, refresh token from callback
Tokens - — Authentication error with error code
IdentityVerificationException - — Interface for Multiple Custom Domain support
DomainResolver
Builder Methods ():
AuthorizeUrl- — Set requested scopes
.withScope("openid profile email") - — Request API access token
.withAudience("https://my-api") - — Lock to specific Organization
.withOrganization("org_xxx") - — Accept Organization invitation
.withInvitation("invite_xxx") - — Skip to specific connection
.withConnection("google-oauth2") - — Add custom authorize parameter
.withParameter("key", "value")
Token Access ():
Tokens- — Access token string
tokens.getAccessToken() - — ID token (JWT) string
tokens.getIdToken() - — Refresh token (if
tokens.getRefreshToken()scope requested)offline_access - — Token expiration in seconds
tokens.getExpiresIn() - — Token type (usually "Bearer")
tokens.getType() - — Auth0 domain that issued the tokens
tokens.getDomain() - — Token issuer URL
tokens.getIssuer()
核心类:
- — 主入口,用于构建授权URL和处理回调
AuthenticationController - — 通过
AuthenticationController.Builder配置控制器newBuilder(domain, clientId, clientSecret) - —
AuthorizeUrlURL参数的流式构建器/authorize - — 回调返回的访问令牌、ID令牌、刷新令牌
Tokens - — 带错误码的认证异常
IdentityVerificationException - — 多自定义域名支持的接口
DomainResolver
AuthorizeUrl- — 设置请求的权限
.withScope("openid profile email") - — 请求API访问令牌
.withAudience("https://my-api") - — 锁定到特定Organizations
.withOrganization("org_xxx") - — 接受Organizations邀请
.withInvitation("invite_xxx") - — 直接跳转到指定连接
.withConnection("google-oauth2") - — 添加自定义授权参数
.withParameter("key", "value")
Tokens- — 访问令牌字符串
tokens.getAccessToken() - — ID令牌(JWT)字符串
tokens.getIdToken() - — 刷新令牌(若请求了
tokens.getRefreshToken()权限)offline_access - — 令牌过期时间(秒)
tokens.getExpiresIn() - — 令牌类型(通常为"Bearer")
tokens.getType() - — 颁发令牌的Auth0域名
tokens.getDomain() - — 令牌颁发者URL
tokens.getIssuer()
Detailed Documentation
详细文档
- Setup Guide — Auth0 CLI automation, environment configuration, secret management
- Integration Guide — Organizations, MCD, custom scopes, logout, error handling, advanced patterns
- API Reference — Complete configuration options, builder methods, claims reference, testing checklist
- 设置指南 — Auth0 CLI自动化、环境配置、密钥管理
- 集成指南 — Organizations、MCD、自定义权限、登出、错误处理、高级模式
- API参考 — 完整配置选项、构建器方法、声明参考、测试清单