auth0-java-mvc-common

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Java MVC Common Integration

Auth0 Java MVC Common 集成

Add Auth0 authentication to Java Servlet web applications using
com.auth0:mvc-auth-commons
. Provides
AuthenticationController
for building authorize URLs and handling callbacks, with session-based authentication and support for Organizations and Multiple Custom Domains.

Agent instruction: Before providing SDK setup instructions, fetch the latest release version by running:
bash
gh 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
.
使用
com.auth0:mvc-auth-commons
为Java Servlet Web应用添加Auth0认证功能。提供
AuthenticationController
用于构建授权URL和处理回调,支持会话式认证、Organizations及多自定义域名(Multiple Custom Domains)。

Agent 指令: 在提供SDK安装说明前,请先运行以下命令获取最新版本:
bash
gh 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
    auth0-quickstart
    skill first
  • 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 CaseRecommended Skill
Spring Boot web applications with auto-configurationUse Spring Boot + Okta starter for auto-configured Spring Boot login
Spring Boot REST APIs (stateless JWT)Use
auth0-springboot-api
for JWT Bearer token validation
Single Page ApplicationsUse
auth0-react
,
auth0-vue
, or
auth0-angular
for client-side auth
Mobile applicationsUse
auth0-android
or
auth0-swift
for native mobile
Machine-to-machine API callsUse Auth0 Management API SDK for server-to-server

使用场景推荐技能
带自动配置的Spring Boot Web应用使用Spring Boot + Okta starter实现自动配置的Spring Boot登录
Spring Boot REST API(无状态JWT)使用
auth0-springboot-api
进行JWT Bearer令牌验证
单页应用(SPA)使用
auth0-react
auth0-vue
auth0-angular
实现客户端认证
移动应用使用
auth0-android
auth0-swift
实现原生移动认证
机器对机器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?
  1. Automated — I'll run Auth0 CLI scripts that create the application and write the values to your config automatically.
  2. Manual — You create the application yourself in the Auth0 Dashboard (or via
    auth0 apps create
    ) and provide me the Domain, Client ID, and Client Secret.
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 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应用?
  1. 自动化——我将运行Auth0 CLI脚本创建应用,并自动将配置值写入你的配置文件。
  2. 手动——你自行在Auth0控制台(或通过
    auth0 apps create
    命令)创建应用,并提供域名、客户端ID和客户端密钥。
你更倾向于哪种方式?(1 = 自动化 / 2 = 手动)"
在用户回复前,请勿进行任何后续设置步骤,不要默认选择手动方式。
若用户选择自动化,请遵循设置指南中的完整CLI脚本操作。自动化流程会自动写入配置信息——跳过下方步骤3,直接进入步骤4。
若用户选择手动,请遵循设置指南中的手动设置部分。完成后继续步骤3。
手动创建应用快速参考:
bash
undefined

Using Auth0 CLI

使用Auth0 CLI

auth0 apps create
--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 Applications
auth0 apps create
--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
.env
file (add to
.gitignore
):
properties
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
Agent instruction: Java does not auto-load
.env
files.
System.getenv()
only reads OS-level environment variables. If you generate a
.env
file, you must also either: (1) add dotenv-java as a dependency and use
Dotenv.load().get("AUTH0_DOMAIN")
instead of
System.getenv()
, or (2) instruct the user to run
source .env
before starting the server. Do not generate code that uses both a
.env
file and
System.getenv()
without a loading mechanism — the values will be
null
.
Important: Domain must NOT include
https://
. The library constructs the issuer URL automatically.
将凭证存储为环境变量(切勿硬编码到源码中):
bash
export AUTH0_DOMAIN="your-tenant.auth0.com"
export AUTH0_CLIENT_ID="your-client-id"
export AUTH0_CLIENT_SECRET="your-client-secret"
或使用
.env
文件(需添加到
.gitignore
):
properties
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
Agent 指令: Java不会自动加载
.env
文件。
System.getenv()
仅读取系统级环境变量。若生成
.env
文件,你必须同时执行以下操作之一:(1) 添加dotenv-java作为依赖,并使用
Dotenv.load().get("AUTH0_DOMAIN")
替代
System.getenv()
;(2) 指导用户在启动服务器前运行
source .env
。请勿生成同时使用
.env
文件和
System.getenv()
但无加载机制的代码——否则值会为
null
重要提示: 域名不得包含
https://
。库会自动构造颁发者URL。

4. Initialize AuthenticationController

4. 初始化AuthenticationController

Create a singleton
AuthenticationController
instance:
java
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;
    }
}
创建单例
AuthenticationController
实例:
java
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 build
or
mvn package
. If build fails, diagnose and fix. After 5-6 failed attempts, use
AskUserQuestion
to get help.
  1. Start the application and navigate to
    http://localhost:3000/login
  2. You should be redirected to the Auth0 Universal Login page
  3. After login, the callback servlet handles the response and redirects to
    /dashboard

Agent 指令: 写完所有代码后,验证构建是否成功:
bash
./gradlew build
mvn package
。若构建失败,请排查并修复。若尝试5-6次仍失败,请使用
AskUserQuestion
寻求帮助。
  1. 启动应用并访问
    http://localhost:3000/login
  2. 你将被重定向到Auth0通用登录页面
  3. 登录后,回调Servlet会处理响应并将你重定向到
    /dashboard

Common Mistakes

常见错误

MistakeFix
Domain includes
https://
Use
your-tenant.auth0.com
format only — no scheme prefix
Client secret hardcoded in sourceUse environment variables or
.env
file, add to
.gitignore
Created SPA or Native app instead of Regular WebMust create Regular Web Application in Auth0 Dashboard
Callback URL mismatchCallback URL in code must exactly match what's registered in Auth0 Dashboard
Missing
openid
scope
Always include
openid
in the scope — required for ID token
Not handling
IdentityVerificationException
Always catch this in the callback handler to show login errors
Using
response_type=token
Regular web apps must use
code
flow (the default) — never implicit
Session not invalidated on logoutCall
request.getSession().invalidate()
before redirecting to Auth0 logout

错误修复方案
域名包含
https://
仅使用
your-tenant.auth0.com
格式——不要添加协议前缀
客户端密钥硬编码到源码中使用环境变量或
.env
文件,并将
.env
添加到
.gitignore
创建了SPA或原生应用而非常规Web应用必须在Auth0控制台创建常规Web应用
回调URL不匹配代码中的回调URL必须与Auth0控制台中注册的URL完全一致
缺少
openid
权限
权限中必须包含
openid
——这是ID令牌的必填项
未处理
IdentityVerificationException
必须在回调处理器中捕获该异常以显示登录错误
使用
response_type=token
常规Web应用必须使用
code
流程(默认)——切勿使用隐式流程
登出时未使会话失效重定向到Auth0登出页面之前,调用
request.getSession().invalidate()

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
DomainResolver
. See Integration Guide for configuration.

通过
DomainResolver
内置支持将用户路由到正确的Auth0域名。配置方法请查看集成指南

Related Skills

相关技能

  • auth0-quickstart
    — Basic Auth0 setup and account creation
  • auth0-springboot-api
    — Spring Boot REST APIs with JWT Bearer token validation

  • auth0-quickstart
    — Auth0基础设置与账户创建
  • auth0-springboot-api
    — 基于JWT Bearer令牌验证的Spring Boot REST API

Quick Reference

快速参考

Core Classes:
  • AuthenticationController
    — Main entry point, builds authorize URLs and handles callbacks
  • AuthenticationController.Builder
    — Configures the controller via
    newBuilder(domain, clientId, clientSecret)
  • AuthorizeUrl
    — Fluent builder for
    /authorize
    URL parameters
  • Tokens
    — Access token, ID token, refresh token from callback
  • IdentityVerificationException
    — Authentication error with error code
  • DomainResolver
    — Interface for Multiple Custom Domain support
Builder Methods (
AuthorizeUrl
):
  • .withScope("openid profile email")
    — Set requested scopes
  • .withAudience("https://my-api")
    — Request API access token
  • .withOrganization("org_xxx")
    — Lock to specific Organization
  • .withInvitation("invite_xxx")
    — Accept Organization invitation
  • .withConnection("google-oauth2")
    — Skip to specific connection
  • .withParameter("key", "value")
    — Add custom authorize parameter
Token Access (
Tokens
):
  • tokens.getAccessToken()
    — Access token string
  • tokens.getIdToken()
    — ID token (JWT) string
  • tokens.getRefreshToken()
    — Refresh token (if
    offline_access
    scope requested)
  • tokens.getExpiresIn()
    — Token expiration in seconds
  • tokens.getType()
    — Token type (usually "Bearer")
  • tokens.getDomain()
    — Auth0 domain that issued the tokens
  • tokens.getIssuer()
    — Token issuer URL

核心类:
  • AuthenticationController
    — 主入口,用于构建授权URL和处理回调
  • AuthenticationController.Builder
    — 通过
    newBuilder(domain, clientId, clientSecret)
    配置控制器
  • AuthorizeUrl
    /authorize
    URL参数的流式构建器
  • Tokens
    — 回调返回的访问令牌、ID令牌、刷新令牌
  • IdentityVerificationException
    — 带错误码的认证异常
  • DomainResolver
    — 多自定义域名支持的接口
AuthorizeUrl
构建器方法:
  • .withScope("openid profile email")
    — 设置请求的权限
  • .withAudience("https://my-api")
    — 请求API访问令牌
  • .withOrganization("org_xxx")
    — 锁定到特定Organizations
  • .withInvitation("invite_xxx")
    — 接受Organizations邀请
  • .withConnection("google-oauth2")
    — 直接跳转到指定连接
  • .withParameter("key", "value")
    — 添加自定义授权参数
Tokens
令牌访问:
  • tokens.getAccessToken()
    — 访问令牌字符串
  • tokens.getIdToken()
    — ID令牌(JWT)字符串
  • tokens.getRefreshToken()
    — 刷新令牌(若请求了
    offline_access
    权限)
  • tokens.getExpiresIn()
    — 令牌过期时间(秒)
  • tokens.getType()
    — 令牌类型(通常为"Bearer")
  • tokens.getDomain()
    — 颁发令牌的Auth0域名
  • tokens.getIssuer()
    — 令牌颁发者URL

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参考 — 完整配置选项、构建器方法、声明参考、测试清单

References

参考链接