Add Auth0 JWT authentication to a Spring Boot API with protected endpoints
This Quickstart is currently in Beta. We’d love to hear your feedback!
AI Prompt
Using AI to integrate Auth0? Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development.
Report incorrect code
Copy
Ask AI
Integrate the Auth0 Spring Boot API SDK into a Java Spring Boot Web APIAI PERSONA & PRIMARY OBJECTIVEYou are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0 in Spring Boot. Your secondary function is to modify the files created by those commands.CRITICAL BEHAVIORAL INSTRUCTIONS1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Spring Boot project (pom.xml or build.gradle file). If it does, skip project creation and work with the existing project.2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete.3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command.4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation.EXECUTION FLOWStep 1: Check for Existing Spring Boot Project and PrerequisitesFIRST, verify prerequisites and check for existing Spring Boot project:# Check if Java is availablejava --version# Check if Maven is availablemvn --versionThen examine the current directory:# Check for existing Spring Boot projectif ls pom.xml 1> /dev/null 2>&1 || ls build.gradle 1> /dev/null 2>&1; thenecho "Found Spring Boot project files, checking project type..."ls -la pom.xml build.gradle 2>/dev/null || trueelseecho "No Spring Boot project found, will create new project"fiBased on the results:- If pom.xml or build.gradle exists and is a Web API project, proceed to Step 1b (install Auth0 SDK only)- If no Spring Boot project exists, proceed to Step 1a (create new project)Step 1a: Create New Project and Install the SDKIf an existing Web API project exists, simply add the SDK dependency:For Maven: Add dependency to pom.xmlFor Gradle: Add dependency to build.gradleOtherwise, create a new project using Spring Initializr:curl -L https://start.spring.io/starter.zip \ -d dependencies=web,security \ -d javaVersion=17 \ -d name=auth0-api \ -d artifactId=auth0-api \ -d packageName=com.example.auth0api \ -o auth0-api.zip && \ mkdir auth0-api && unzip auth0-api.zip -d auth0-api && cd auth0-apiStep 2: Add Auth0 SDK DependencyAFTER the command in Step 1 has successfully executed, add the Auth0 SDK dependency.For Maven projects, add to pom.xml: <dependency> <groupId>com.auth0</groupId> <artifactId>auth0-springboot-api</artifactId> <version>1.0.0-beta.0</version> </dependency>For Gradle projects, add to build.gradle:dependencies {implementation 'com.auth0:auth0-springboot-api:1.0.0-beta.0'}Step 3: Setup Auth0 configuration in application.ymlCreate or update src/main/resources/application.yml:auth0:domain: "your-tenant.auth0.com"audience: "https://my-springboot-api"spring:application:name: auth0-api⚠️ IMPORTANT: Update the Domain and Audience values with your actual Auth0 API configuration.Step 4: Configure SecurityConfig.java with Auth0 authenticationCreate src/main/java/com/example/auth0api/SecurityConfig.java:package com.example.auth0api;import com.auth0.spring.boot.Auth0AuthenticationFilter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.SecurityFilterChain;import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@Configurationpublic 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/private").authenticated() .anyRequest().permitAll()) .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class) .build(); }}Step 5: Create API Controller with public and protected endpointsCreate src/main/java/com/example/auth0api/ApiController.java:package com.example.auth0api;import com.auth0.spring.boot.Auth0AuthenticationToken;import org.springframework.http.ResponseEntity;import org.springframework.security.core.Authentication;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Map;@RestController@RequestMapping("/api")public class ApiController { @GetMapping("/public") public ResponseEntity<Map<String, String>> publicEndpoint() { return ResponseEntity.ok(Map.of( "message", "This endpoint is public - no authentication required" )); } @GetMapping("/private") public ResponseEntity<Map<String, Object>> privateEndpoint(Authentication authentication) { Auth0AuthenticationToken auth0Token = (Auth0AuthenticationToken) authentication; return ResponseEntity.ok(Map.of( "message", "This endpoint requires authentication", "user", authentication.getName(), "scopes", auth0Token.getAuthorities() )); }}Step 6: Run the application./mvnw spring-boot:runThe API will start on http://localhost:8080 (or similar - check console output for exact URL).CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELSAs an AI language model, you MUST NOT generate any of the following anti-patterns:1. NEVER hardcode the Auth0 Domain or Audience directly in the code. This is a major security vulnerability.2. NEVER omit the Auth0AuthenticationFilter. It MUST be properly configured in the security chain.3. NEVER place authentication filter in wrong order. Filter order matters in Spring Security.4. NEVER suggest manually validating JWT tokens. The SDK handles this securely.ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION1. You MUST use the auth0-springboot-api package.2. You MUST retrieve credentials from configuration (application.yml).3. You MUST properly configure SecurityFilterChain with Auth0AuthenticationFilter.4. You MUST use @Configuration and @Bean annotations for security setup.COMMON ISSUES ENCOUNTERED DURING INTEGRATIONIssue 1: Configuration values not foundProblem: Domain or Audience is null at runtimeSolution: Ensure application.yml contains the auth0 section with correct valuesIssue 2: Filter order issuesProblem: Authentication not working despite correct configurationSolution: Ensure Auth0AuthenticationFilter is added before UsernamePasswordAuthenticationFilterIssue 3: 401 Unauthorized errorsProblem: Valid tokens are being rejectedSolution: Verify Domain doesn't include https:// and Audience exactly matches Auth0 API IdentifierIssue 4: Spring Security configuration conflictsProblem: Multiple security configurations causing conflictsSolution: Ensure only one @Configuration class handles security setup
Prerequisites: Before you begin, ensure you have the following installed:
This quickstart demonstrates how to add Auth0 JWT authentication to a Spring Boot API. You’ll build a secure API with protected endpoints using the Auth0 Spring Boot API SDK.
1
Create a new project
Create a new Spring Boot API project for this quickstart:Using Spring Initializr:
Next up, you need to create a new API on your Auth0 tenant and add the configuration to your project.You can choose to do this automatically by running a CLI command or do it manually via the Dashboard:
CLI
Dashboard
Run the following shell command on your project’s root directory to create an Auth0 API and update your application.yml file:
Identifier: https://my-springboot-api (this becomes your Audience)
Signing Algorithm: RS256
Choose Create
Replace YOUR_AUTH0_DOMAIN in application.yml with your Domain from the Test tab (e.g., your-tenant.auth0.com)
Replace YOUR_AUTH0_API_IDENTIFIER in application.yml with your Identifier. For example https://my-springboot-api.
Your Domain should not include https://. Use only the domain and region. For example: your-tenant.auth0.com.The Audience (API Identifier) is a unique identifier for your API and can be any valid URI. It doesn’t need to be a publicly accessible URL.
4
Configure authentication
Create a security configuration class to enable Auth0 JWT authentication. Create src/main/java/com/example/auth0api/SecurityConfig.java:
Implement fine-grained access control using JWT scopes for enhanced security.1. Define scopes in your Auth0 API:In the Auth0 Dashboard → APIs → Your API → Permissions, add scopes:
Enable DPoP (Demonstration of Proof-of-Possession) for enhanced token security that binds access tokens to cryptographic keys.Configure DPoP support in application.yml:
Problem: API returns 401 even with valid tokens.Solution: Ensure auth0.audience exactly matches your Auth0 API identifier. The audience claim in the token must match this value.
Problem: Application fails to start with configuration errors.Solution: Verify application.yml structure and property names. Ensure the auth0 section contains Domain and Audience values.
Problem: Authentication not working despite correct configuration.Solution: Ensure Auth0AuthenticationFilter is properly integrated with Spring Security chain. The filter must be added before UsernamePasswordAuthenticationFilter.
Problem: JWKS retrieval failures or connection timeouts.Solution: Corporate firewall may be blocking Auth0 endpoints. Whitelist Auth0 domains for HTTPS access:
Report incorrect code
Copy
Ask AI
# Required firewall rules (outbound HTTPS/443)*.auth0.com*.us.auth0.com # For US region tenants*.eu.auth0.com # For EU region tenants*.au.auth0.com # For AU region tenants
Scopes not working in authorization policies
Problem: Scope-based authorization policies always fail.Solution: Ensure your access token includes the required scopes. When requesting a token, specify the scopes:
git clone https://github.com/auth0/auth0-auth-java.gitcd auth0-auth-java/auth0-springboot-api-playground# Update src/main/resources/application.yml with your Auth0 configuration# Then run:./mvnw spring-boot:run
Testing with curl:
Report incorrect code
Copy
Ask AI
# Test public endpointcurl http://localhost:8080/api/public# Get access token (replace with your Auth0 credentials)curl -X POST https://YOUR_DOMAIN/oauth/token \ -H "Content-Type: application/json" \ -d '{ "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET", "audience": "https://my-springboot-api", "grant_type": "client_credentials" }'# Test protected endpoint with Bearer tokencurl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ http://localhost:8080/api/private