Customized Swagger UI web interface packaged as a WebJar for Spring Boot applications using Springfox library
npx @tessl/cli install tessl/maven-io-springfox--springfox-swagger-ui@3.0.0Springfox 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.
pom.xml or Gradle dependency in build.gradleMaven:
<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'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 configurationFor most Spring Boot applications with Springfox, simply add the dependency and the UI will be automatically available:
http://localhost:8080/swagger-ui/index.htmlConfigure a custom base path in your application.properties:
springfox.documentation.swagger-ui.base-url=/custom-docsThen access at: http://localhost:8080/custom-docs/swagger-ui/index.html
Springfox Swagger UI consists of several key components:
/META-INF/resources/webjars/springfox-swagger-ui/{version}/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.cssRESTful 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-resourcesExpected 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;
}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[];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;
}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;
}
}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)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 WebJarCreate 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();
}
}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 protection in your security configuration:
@Bean
public SecurityConfiguration securityConfiguration() {
return SecurityConfigurationBuilder.builder()
.enableCsrfSupport(true)
.build();
}Common issues and troubleshooting:
If the UI cannot automatically determine the base URL, it will prompt the user. This commonly occurs with:
Solution: Manually configure the base URL or implement a custom base URL resolution strategy.
The CSRF module attempts three strategies:
_csrf_header, _csrf)/csrf endpointXSRF-TOKEN cookieSolution: Ensure your Spring Security configuration provides CSRF tokens through one of these methods.
The UI expects these endpoints to be available:
/swagger-resources/swagger-resources/configuration/ui/swagger-resources/configuration/securitySolution: Verify that springfox-swagger-common is included and properly configured.
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;
};
}interface OAuthConfig {
clientId: string;
clientSecret: string;
realm: string;
appName: string;
scopeSeparator: string;
additionalQueryStringParams: Record<string, any>;
useBasicAuthenticationWithAccessCodeGrant: boolean;
}