or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/maven-io-springfox--springfox-swagger-ui

Customized Swagger UI web interface packaged as a WebJar for Spring Boot applications using Springfox library

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/io.springfox/springfox-swagger-ui@3.0.x

To install, run

npx @tessl/cli install tessl/maven-io-springfox--springfox-swagger-ui@3.0.0

index.mddocs/

Springfox Swagger UI

Springfox Swagger UI provides a customized Swagger UI web interface packaged as a WebJar for Spring Boot applications. It automatically integrates with Springfox-generated API documentation, offering an interactive interface for API exploration and testing with Spring-specific enhancements including CSRF protection and OAuth2 support.

Package Information

  • Package Name: springfox-swagger-ui
  • Package Type: maven
  • Language: Java (packaging) + JavaScript/CSS/HTML (web assets)
  • Installation: Add Maven dependency in pom.xml or Gradle dependency in build.gradle

Maven:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

Gradle:

implementation 'io.springfox:springfox-swagger-ui:3.0.0'

Core Imports

Java (if needed for advanced configuration):

import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.UiConfiguration;

JavaScript (if extending the UI):

// Access global objects created by springfox.js
window.ui;          // SwaggerUIBundle instance
window.uiConfig;    // UI configuration
window.securityConfig; // Security configuration

Basic Usage

Standard Integration

For most Spring Boot applications with Springfox, simply add the dependency and the UI will be automatically available:

  1. Add the Maven/Gradle dependency
  2. Ensure you have Springfox configured in your application
  3. Access the UI at: http://localhost:8080/swagger-ui/index.html

Custom Base Path

Configure a custom base path in your application.properties:

springfox.documentation.swagger-ui.base-url=/custom-docs

Then access at: http://localhost:8080/custom-docs/swagger-ui/index.html

Architecture

Springfox Swagger UI consists of several key components:

  • WebJar Structure: Standard WebJar packaging under /META-INF/resources/webjars/springfox-swagger-ui/{version}/
  • Custom JavaScript: Enhanced Swagger UI initialization with Spring-specific configuration
  • CSRF Integration: Automatic CSRF token handling for Spring Security
  • Configuration Endpoints: RESTful endpoints for dynamic UI and security configuration
  • Asset Management: Custom fonts, CSS styling, and HTML templates

Capabilities

WebJar Integration

Access to packaged Swagger UI assets through standard WebJar URLs.

// WebJar base path
/webjars/springfox-swagger-ui/{version}/

// Main entry points
/webjars/springfox-swagger-ui/{version}/index.html
/webjars/springfox-swagger-ui/{version}/springfox.js
/webjars/springfox-swagger-ui/{version}/springfox.css

Configuration Endpoints

RESTful endpoints that provide dynamic configuration for the Swagger UI.

// Base endpoint (configurable via springfox.documentation.swagger-ui.base-url)
GET /swagger-resources

// Configuration endpoints
GET /swagger-resources/configuration/ui
GET /swagger-resources/configuration/security
GET /swagger-resources

Expected Response Types:

// UI Configuration Response
interface UiConfiguration {
  deepLinking: boolean;
  displayOperationId: boolean;
  defaultModelsExpandDepth: number;
  defaultModelExpandDepth: number;
  defaultModelRendering: string;
  displayRequestDuration: boolean;
  docExpansion: string;
  filter: boolean | string;
  maxDisplayedTags: number;
  operationsSorter: string;
  showExtensions: boolean;
  showCommonExtensions: boolean;
  tagSorter: string;
  supportedSubmitMethods: string[];
  validatorUrl: string;
  swaggerBaseUiUrl: string;
}

// Security Configuration Response
interface SecurityConfiguration {
  enableCsrfSupport: boolean;
  clientId: string;
  clientSecret: string;
  realm: string;
  appName: string;
  scopeSeparator: string;
  additionalQueryStringParams: Record<string, any>;
  useBasicAuthenticationWithAccessCodeGrant: boolean;
}

// Swagger Resources Response
interface SwaggerResource {
  name: string;
  url: string;
  swaggerVersion: string;
  location: string;
}

JavaScript API

Core JavaScript functionality for initializing and customizing the Swagger UI.

/**
 * Main initialization function that builds the Swagger UI system
 * @param baseUrl - Base URL for API endpoints
 * @returns Promise that resolves when UI is initialized
 */
async function buildSystemAsync(baseUrl: string): Promise<void>;

/**
 * Creates and configures the SwaggerUIBundle instance  
 * @param baseUrl - Base URL for API endpoints
 * @param resources - Array of swagger resources
 * @param configUI - UI configuration object
 * @param configSecurity - Security configuration object
 * @returns Configured SwaggerUIBundle instance
 */
function getUI(
  baseUrl: string,
  resources: SwaggerResource[],
  configUI: UiConfiguration,
  configSecurity: SecurityConfiguration
): SwaggerUIBundle;

/**
 * Extracts base URL from current window location
 * @returns Base URL string
 */
function getBaseURL(): string;

/**
 * Prepends base URL to resource URLs
 * @param baseUrl - Base URL to prepend
 * @param resources - Array of resources to modify
 * @returns Modified resources array
 */
function prependBaseUrl(baseUrl: string, resources: SwaggerResource[]): SwaggerResource[];

CSRF Protection

Automatic CSRF token handling for Spring Security integration.

/**
 * Adds CSRF header to all API requests if CSRF is enabled
 * This is the default export from the csrf module
 * @param baseUrl - Base URL for CSRF token retrieval
 * @returns Promise that resolves when CSRF support is configured
 */
export default async function patchRequestInterceptor(baseUrl: string): Promise<void>;

/**
 * Attempts to retrieve CSRF token using multiple strategies
 * @param baseUrl - Base URL for token endpoints
 * @returns Promise resolving to CSRF token info or undefined
 */
async function getCsrf(baseUrl: string): Promise<CsrfToken | undefined>;

/**
 * Retrieves CSRF token from HTML meta tags
 * @param baseUrl - Base URL for HTML page
 * @returns Promise resolving to CSRF token info or undefined
 */
async function getCsrfFromMeta(baseUrl: string): Promise<CsrfToken | undefined>;

/**
 * Retrieves CSRF token from dedicated endpoint
 * @param baseUrl - Base URL for CSRF endpoint
 * @returns Promise resolving to CSRF token info or undefined
 */
async function getCsrfFromEndpoint(baseUrl: string): Promise<CsrfToken | undefined>;

/**
 * Retrieves CSRF token from cookies
 * @returns CSRF token info or undefined
 */
function getCsrfFromCookie(): CsrfToken | undefined;

interface CsrfToken {
  headerName: string;
  token: string;
}

Global JavaScript Objects

Objects available in the browser after UI initialization.

// Global objects created after initialization
declare global {
  interface Window {
    /** Main Swagger UI instance */
    ui: SwaggerUIBundle;
    /** UI configuration object */
    uiConfig: UiConfiguration;
    /** Security configuration object */
    securityConfig: SecurityConfiguration;
  }
}

Custom Styling

CSS customizations and font integration for Spring-specific branding.

/* Main stylesheet */
/webjars/springfox-swagger-ui/{version}/springfox.css

/* Custom fonts included */
Titillium Web (regular, 600, 700)
Source Code Pro (300, 600)
Open Sans (regular, 700)

Build System Integration

Gradle configuration for customizing and building the WebJar.

// Key Gradle tasks available
task swaggerUiDownload    // Downloads official Swagger UI
task unzip                // Extracts Swagger UI distribution  
task npmBuild            // Builds custom JavaScript modules
task customizeSwaggerUi  // Applies Spring customizations
task jar                 // Packages as WebJar

Configuration Examples

Custom UI Configuration

Create a UiConfiguration bean to customize the Swagger UI:

@Configuration
public class SwaggerUiConfig {
    
    @Bean
    public UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
            .deepLinking(true)
            .displayOperationId(false)
            .defaultModelsExpandDepth(1)
            .defaultModelExpandDepth(1)
            .defaultModelRendering(ModelRendering.EXAMPLE)
            .displayRequestDuration(false)
            .docExpansion(DocExpansion.NONE)
            .filter(false)
            .maxDisplayedTags(null)
            .operationsSorter(OperationsSorter.ALPHA)
            .showExtensions(false)
            .tagsSorter(TagsSorter.ALPHA)
            .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
            .validatorUrl(null)
            .build();
    }
}

Custom Security Configuration

Create a SecurityConfiguration bean for OAuth2 setup:

@Configuration
public class SwaggerSecurityConfig {
    
    @Bean
    public SecurityConfiguration security() {
        return SecurityConfigurationBuilder.builder()
            .clientId("swagger-ui")
            .clientSecret("swagger-ui-secret")
            .realm("swagger-ui-realm")
            .appName("swagger-ui")
            .scopeSeparator(",")
            .additionalQueryStringParams(null)
            .useBasicAuthenticationWithAccessCodeGrant(false)
            .build();
    }
}

Enable CSRF Support

Enable CSRF protection in your security configuration:

@Bean
public SecurityConfiguration securityConfiguration() {
    return SecurityConfigurationBuilder.builder()
        .enableCsrfSupport(true)
        .build();
}

Error Handling

Common issues and troubleshooting:

Base URL Resolution Issues

If the UI cannot automatically determine the base URL, it will prompt the user. This commonly occurs with:

  • API Gateway configurations
  • Dynamic servlet registration
  • Proxy configurations

Solution: Manually configure the base URL or implement a custom base URL resolution strategy.

CSRF Token Retrieval Failures

The CSRF module attempts three strategies:

  1. HTML meta tags (_csrf_header, _csrf)
  2. /csrf endpoint
  3. XSRF-TOKEN cookie

Solution: Ensure your Spring Security configuration provides CSRF tokens through one of these methods.

Missing Configuration Endpoints

The UI expects these endpoints to be available:

  • /swagger-resources
  • /swagger-resources/configuration/ui
  • /swagger-resources/configuration/security

Solution: Verify that springfox-swagger-common is included and properly configured.

Types

SwaggerUIBundle Configuration

interface SwaggerUIBundleConfig {
  // Core configuration
  configUrl?: string | null;
  dom_id: string;
  dom_node?: HTMLElement | null;
  spec: object;
  url: string;
  urls: SwaggerResource[];
  
  // Plugin system
  layout: string;
  plugins: any[];
  presets: any[];
  
  // Display options
  deepLinking: boolean;
  displayOperationId: boolean;
  defaultModelsExpandDepth: number;
  defaultModelExpandDepth: number;
  defaultModelRendering: string;
  displayRequestDuration: boolean;
  docExpansion: string;
  filter: boolean | string;
  maxDisplayedTags: number | null;
  operationsSorter: string;
  showExtensions: boolean;
  showCommonExtensions: boolean;
  tagSorter: string;
  
  // Network configuration
  oauth2RedirectUrl: string;
  requestInterceptor: (request: any) => any;
  responseInterceptor: (response: any) => any;
  showMutatedRequest: boolean;
  supportedSubmitMethods: string[];
  validatorUrl: string | null;
  
  // Custom configuration
  custom: {
    enableCsrfSupport: boolean;
  };
}

OAuth Configuration

interface OAuthConfig {
  clientId: string;
  clientSecret: string;
  realm: string;
  appName: string;
  scopeSeparator: string;
  additionalQueryStringParams: Record<string, any>;
  useBasicAuthenticationWithAccessCodeGrant: boolean;
}