interceptor

Version

Wraps an interceptor provided as Spring bean (refid) or as nested interceptor (child element) and delegates all calls.

Syntax

interceptor:
'$ref': <string>
abort:
- <flow>
accessControl:
- <rules>
accessLog: {}
acmeHttpChallenge: {}
adminApi: {}
adminConsole: {}
analyser: {}
apiDocs: {}
apiKey: {}
APIsJSON: {}
authHead2Body: {}
balancer: {}
basicAuthentication: {}
beautifier: {}
cache: {}
call: {}
chain:
- <flow>
choose:
- <choices>
clamav: {}
clusterNotification: {}
correlationId: {}
cors: {}
counter: <string>
destination: {}
dispatching: {}
echo: {}
exchangeStore: {}
flowInitiator: {}
for: {}
formValidation:
- <formValidation-field>
graphQLProtection: {}
greaser: {}
groovy: {}
headerFilter:
- <filterRules>
http2xml: {}
httpClient: {}
idempotency: {}
if: {}
index: {}
interceptor: {}
internalRouting: {}
javascript: {}
json2Xml: {}
jsonProtection: {}
jsonRPCProtection: {}
jwtAuth: {}
jwtSign: {}
kubernetesValidation: {}
limit: {}
llmGateway: {}
log: {}
logContext: {}
login: {}
mcpProtection: {}
membraneMCPServer: {}
ntlm: {}
oauth2authserver: {}
oauth2Client: {}
oauth2PermissionChecker: {}
oauth2Resource2: {}
openapiPublisher: {}
openapiValidator: {}
openTelemetry: {}
paddingHeader: {}
prometheus: {}
rateLimiter: {}
refid: <string>
regExReplacer: {}
replace: {}
request:
- <flow>
requireAuth: {}
response:
- <flow>
rest2Soap: {}
return: {}
reverseProxying: {}
rewriter:
- <rewriter-map>
ruleMatching: {}
sampleSoapService: {}
setBody: {}
setCookies:
- <cookie>
setHeader: {}
setProperty: {}
shadowing: {}
shutdown: {}
soap2Rest: {}
soapBody: {}
soapOperationExtractor: {}
soapStackTraceFilter: {}
sqlInjectionProtection: {}
sseDemoStream: {}
static: {}
statisticsCSV: {}
statisticsJDBC: {}
statisticsProvider: {}
stompClient: {}
tcp: {}
template: {}
throttle: {}
time: {}
tokenValidator: {}
transform: {}
userFeature: {}
validator: {}
webServer: {}
webServiceExplorer: {}
webSocket: {}
wsaEndpointRewriter: {}
wsdlPublisher: {}
wsdlRewriter: {}
xenAuthentication: {}
xml2Json: {}
xmlContentFilter: {}
xmlProtection: {}
interceptor:
  '$ref': <string>
  abort:
    - <flow>
  accessControl:
    - <rules>
  accessLog: {}
  acmeHttpChallenge: {}
  adminApi: {}
  adminConsole: {}
  analyser: {}
  apiDocs: {}
  apiKey: {}
  APIsJSON: {}
  authHead2Body: {}
  balancer: {}
  basicAuthentication: {}
  beautifier: {}
  cache: {}
  call: {}
  chain:
    - <flow>
  choose:
    - <choices>
  clamav: {}
  clusterNotification: {}
  correlationId: {}
  cors: {}
  counter: <string>
  destination: {}
  dispatching: {}
  echo: {}
  exchangeStore: {}
  flowInitiator: {}
  for: {}
  formValidation:
    - <formValidation-field>
  graphQLProtection: {}
  greaser: {}
  groovy: {}
  headerFilter:
    - <filterRules>
  http2xml: {}
  httpClient: {}
  idempotency: {}
  if: {}
  index: {}
  interceptor: {}
  internalRouting: {}
  javascript: {}
  json2Xml: {}
  jsonProtection: {}
  jsonRPCProtection: {}
  jwtAuth: {}
  jwtSign: {}
  kubernetesValidation: {}
  limit: {}
  llmGateway: {}
  log: {}
  logContext: {}
  login: {}
  mcpProtection: {}
  membraneMCPServer: {}
  ntlm: {}
  oauth2authserver: {}
  oauth2Client: {}
  oauth2PermissionChecker: {}
  oauth2Resource2: {}
  openapiPublisher: {}
  openapiValidator: {}
  openTelemetry: {}
  paddingHeader: {}
  prometheus: {}
  rateLimiter: {}
  refid: <string>
  regExReplacer: {}
  replace: {}
  request:
    - <flow>
  requireAuth: {}
  response:
    - <flow>
  rest2Soap: {}
  return: {}
  reverseProxying: {}
  rewriter:
    - <rewriter-map>
  ruleMatching: {}
  sampleSoapService: {}
  setBody: {}
  setCookies:
    - <cookie>
  setHeader: {}
  setProperty: {}
  shadowing: {}
  shutdown: {}
  soap2Rest: {}
  soapBody: {}
  soapOperationExtractor: {}
  soapStackTraceFilter: {}
  sqlInjectionProtection: {}
  sseDemoStream: {}
  static: {}
  statisticsCSV: {}
  statisticsJDBC: {}
  statisticsProvider: {}
  stompClient: {}
  tcp: {}
  template: {}
  throttle: {}
  time: {}
  tokenValidator: {}
  transform: {}
  userFeature: {}
  validator: {}
  webServer: {}
  webServiceExplorer: {}
  webSocket: {}
  wsaEndpointRewriter: {}
  wsdlPublisher: {}
  wsdlRewriter: {}
  xenAuthentication: {}
  xml2Json: {}
  xmlContentFilter: {}
  xmlProtection: {}

Sample

<spring:beans xmlns:spring="http://www.springframework.org/schema/beans" ...>
...
<spring:bean id="myInterceptor" class="com.predic8.MyInterceptor">
<spring:property name="myProperty" value="value"/>
</spring:bean>
</spring:beans><serviceProxy port="2000">
<interceptor refid="myInterceptor" />
</serviceProxy>
<spring:beans xmlns:spring="http://www.springframework.org/schema/beans" ...>
	...
  <spring:bean id="myInterceptor" class="com.predic8.MyInterceptor">
    <spring:property name="myProperty" value="value"/>
  </spring:bean>
</spring:beans><serviceProxy port="2000">
  <interceptor refid="myInterceptor" />
</serviceProxy>

Attributes

NameRequiredDefaultDescriptionExamples
$reffalse-Reference a component defined under components.-
refidfalse-Spring bean id of the referenced interceptor.myInterceptor

Child Structure

ElementCardinalityDescription
flow0..*
rules0..*
accessLog0..1Writes one access-log line per completed exchange through a Log4j appender. The line follows the Apache Common Log Format by default; add additionalPatternList entries to append your own SpEL-evaluated fields. Where the line is written and in which format is controlled by the Log4j configuration (log4j2.xml). Typically configured under global so it covers every API. See the examples under examples/logging/access.
acmeHttpChallenge0..1See the documentation of the <acme /> element for usage details.
adminApi0..1Provides a JSON-based Admin API (health, apis, calls, exchange details, suggestions, ws) backed by the ExchangeStore.
adminConsole0..1Displays up-to-date statistics, recent exchanges and, by default, allows live modification of Membrane's configuration.
analyser0..1Analyses XML bodies and stores extracted root element + SOAP operation metadata in Exchange properties (request/response).
apiDocs0..1Publishes an overview of all OpenAPI-enabled proxies and serves Swagger UI under /api-docs/ui/*.
apiKey0..1Validates an API key extracted from each request and resolves its scopes from the configured stores. On success it adds an ApiKeySecurityScheme carrying the scopes to the Exchange, which later plugins test with hasScope("..."). A missing key returns 401 and an invalid key 403 as Problem Details, unless required is false, in which case requests pass and scopes are attached only when a valid key is present.
APIsJSON0..1
authHead2Body0..1
balancer0..1Distributes requests across a set of backend nodes. Nodes are grouped into one or more clusters, and the configured dispatching strategy picks a node for each request, defaulting to round-robin. Failover is always on: the remaining nodes are added as fallback destinations, so a request retries the next node when one fails. When a sessionIdExtractor is configured, requests carrying a known session are pinned to the node that first served it (sticky sessions). On dispatch the chosen node is stored on the exchange and its statistics are updated when the response returns; if no node is available the request is answered with 503. Can only be used inside an api or serviceProxy. See the examples under examples/loadbalancing.
basicAuthentication0..1Requires HTTP Basic credentials (the Authorization: Basic header) on each request and verifies them against the configured users or user data provider. On success the request continues and an HTTP Basic security scheme carrying the username is attached to the exchange; the Authorization header is removed before the request is forwarded. A missing or invalid credential is rejected with 401 and a WWW-Authenticate challenge. See the examples under examples/security/basic-auth and the tutorial tutorials/security/30-Basic-Authentication.yaml.
beautifier0..1Pretty-prints the message body according to its Content-Type. JSON, JSON5, XML and plain text are reindented; any other content type is left unchanged. Runs in both the request and the response flow and is best-effort: an empty or unparseable body passes through untouched and the exchange never fails. See the tutorials under tutorials/json and tutorials/xml.
cache0..1Don't use, this does NOT implement valid HTTP caching.
call0..1Calls an external HTTP endpoint and merges its response into the current message. The endpoint's response body replaces the message body, and its headers are copied onto the message except Server, Content-Encoding and Transfer-Encoding. Runs in both the request and the response flow. The url may contain ${...} expressions that are evaluated against the exchange before each call; a URL without a template marker is used verbatim. On an unknown host or a failed call the exchange is aborted with a Problem Details response. See the examples and tutorials under examples/orchestration and tutorials/orchestration.
choices0..*
clamav0..1Delegates virus checks to an external Virus Scanner.
clusterNotification0..1Receives control messages to dynamically modify the configuration of a {@link LoadBalancingInterceptor}.
correlationId0..1Reads a correlation id from a request header (or generates one if absent), writes it back into that header and adds it to the SLF4J MDC logging context so it appears in every log line of the request. The MDC entry is removed again on the response (and on abort).
cors0..1Cross-Origin Resource Sharing (CORS) plugin that enables secure cross-origin HTTP requests.
counter0..1Returns a simple HTML page and counts how often it was requested (increments per request).
destination0..1Sets the destination URL for the exchange. This overrides any previous destination.
dispatching0..1This interceptor adds the destination specified in the target element to the list of destinations of the exchange object. It must be placed into the transport to make Service Proxies Work properly. It has to be placed after the ruleMatching interceptor. The ruleMatching interceptor looks up a service proxy for an incoming request and places it into the exchange object. The dispatching interceptor needs the service proxy to get information about the target.
echo0..1Returns the flow of plugins and copies the content of the request into a new response. The response has a status code of 200. Useful for testing.
exchangeStore0..1Adds the current state of HTTP requests and responses to an "exchange store".
flowInitiator0..1Initiates an OAuth2 login flow by redirecting to oauth2 (FlowContext).
for0..1Iterates over a collection and runs its nested flow once per element. The in expression is evaluated against the exchange and must yield a List; for each item the nested plugins run with the current item exposed as the exchange property it. Iteration happens only in the request flow and only when the expression yields a list; any other value passes through unchanged. If the expression fails to evaluate, the exchange is aborted with a Problem Details response. See the examples and tutorials under examples/orchestration and tutorials/orchestration.
formValidation0..*Using the formValidation interceptor you can validate the input of HTML forms.
graphQLProtection0..1Check GraphQL-over-HTTP requests, enforcing several limits and/or restrictions. This effectively helps to reduce the attack surface.
greaser0..1Randomly applies greasing strategies to request/response messages (rate 0..1) to stress-test parsers (e.g., JSON/XML).
groovy0..1Runs a Groovy script against the current exchange to read or modify messages and steer the flow. The script runs in the request, response, and abort flows. Its return value decides what happens next:
filterRules0..*
http2xml0..1
httpClient0..1The httpClient sends the request of an exchange to a Web Server using the HTTP protocol. Usually it will be globally used inside the transport. However, it is also possible to use it inside a proxy to give the proxy an individual configuration for its outgoing HTTP connection that is different from the global configuration in the transport.
idempotency0..1Prevents duplicate request processing based on a dynamic idempotency key.
if0..1if allows conditional execution of nested interceptors.
index0..1The index feature lists available proxys at a simple Web page. To use this feature just add a serviceProxy containing the index element. Of course you can protect the service proxy by using SSL or Username and Password.
interceptor0..1Wraps an interceptor provided as Spring bean (refid) or as nested interceptor (child element) and delegates all calls.
internalRouting0..1
javascript0..1Executes a Javascript. The script can access and manipulate data from the request and response. Use this or the Groovy plugin to extend the functions of Membrane by scripting. See the samples in examples/javascript.
json2Xml0..1Converts a JSON message body to XML. A body that is not JSON passes through unchanged. The result is UTF-8 encoded, begins with an XML prolog, and the Content-Type is set to application/xml. If the body is not valid JSON the exchange is aborted with a 500 Problem Details. See the examples under examples/message-transformation/json2xml and the tutorial tutorials/xml/10-JSON-to-XML.yaml.
jsonProtection0..1Enforces restrictions on JSON request bodies to protect against JSON-based attacks and resource exhaustion. Validates against configurable limits to prevent attacks such as:
jsonRPCProtection0..1Protects JSON-RPC endpoints by validating request structure, controlling batch usage, applying ordered allow/deny rules to method names, and optionally validating request parameters and responses against JSON Schema documents.
jwtAuth0..1Validates a JWT on requests (signature via JWKS, required exp/sub) and exposes claims in exchange properties ("jwt").
jwtSign0..1
kubernetesValidation0..1Kubernetes Integration is still experimental.
limit0..1Enforces a maximum body size, rejecting oversized messages with a Problem Details 400 response.
llmGateway0..1Gateway in front of an LLM provider's chat API (OpenAI, Anthropic/Claude, or Google Gemini). It can share a single provider API key among many clients, authenticate clients and enforce per-user token limits through a store, apply usage policies, and inject a system prompt; token usage is recorded when the response returns. Place it in the flow of an api whose target is the provider's API. Without a store the gateway is stateless and just forwards requests with the configured key and policies. See the tutorials under tutorials/ai/llm-gateway.
log0..1Logs request and response messages to the console or a log file, depending on the logging configuration. By default it writes the start line, headers, and body of each message, with sensitive header values masked. Set message to log the result of an expression instead of the full dump:
logContext0..1
login0..1The login interceptor can be used to restrict and secure end user access to an arbitrary web application.
mcpProtection0..1Protects an MCP endpoint by validating incoming JSON-RPC requests and restricting the MCP methods and tools that clients may use.
membraneMCPServer0..1MCP Server for Membrane. It allows querying Membrane's internal state and operation from an LLM Ask the LLM questions like: - What APIs are deployed? - Is the Membrane instance healthy? - Give me a summary about the requests
ntlm0..1Performs NTLM authentication when the upstream responds with WWW-Authenticate: NTLM by replaying the request with NTLM headers.
oauth2authserver0..1OAuth2/OIDC authorization server endpoints (auth/token/userinfo/revocation/.well-known) with session + consent/login UI.
oauth2Client0..1Obtains an OAuth2 access token using the client credentials flow and forwards the request with a Bearer token.
oauth2PermissionChecker0..1
oauth2Resource20..1Allows only authorized HTTP requests to pass through. Unauthorized requests get a redirect to the authorization server as response. This interceptor does Session Management and can thereby translate Session IDs to OAuth2/OIDC Access Tokens. Beyond regular OIDC-compliant authorization servers, this interceptor can also be used with Azure B2C.
openapiPublisher0..1Serves the OpenAPI documents declared on the enclosing api together with a Swagger UI, under the /api-docs path. /api-docs returns an overview of all documents: an HTML page when the client accepts HTML, otherwise a JSON list with each document's title, version, and links. /api-docs/{id} returns one document as YAML, rewritten so its server URLs point at the gateway, and /api-docs/ui/{id} opens the Swagger UI for that document. An unknown id returns 404; requests to other paths pass through unchanged. Can only be used inside an api. See the examples under examples/openapi and the tutorial tutorials/getting-started/80-OpenAPI.yaml.
openapiValidator0..1Validates requests and responses against the OpenAPI documents declared on the enclosing api (its openapi elements). Those documents are normally validated automatically before the flow runs; add this element to the flow to run validation at a specific point instead, for example after an authentication plugin so its result is available to security validation. What is checked is controlled per document by the openapi element's validateRequests, validateResponses, and validateSecurity options (or the matching x-membrane-validation extension in the document). A request matching no document is answered with 404, a request that violates its schema with a 4xx Problem Details, and an invalid response with 500. Can only be used inside an api. See the examples under examples/openapi and the tutorial tutorials/getting-started/90-OpenAPI-Validation.yaml.
openTelemetry0..1OpenTelemetry is an open observability standard for distributed tracing. It tracks a request as it travels across services by passing a traceparent header from hop to hop and collecting timing data (spans) in a central backend such as Jaeger or Zipkin. Membrane supports OpenTelemetry by creating one INTERNAL span per request: it extracts the incoming W3C trace context from request headers, opens the span, and injects the updated traceparent into the forwarded request so downstream services join the same trace. HTTP headers are recorded as http.header.* attributes, the response status as http.status_code, and for API proxies the OpenAPI title as openapi.title. The traceId and spanId are written into SLF4J MDC automatically so every log line carries them. Aborted exchanges are marked ERROR. Declare the plugin in global: to instrument all APIs at once. See tutorials/operation/40-OpenTelemetry.yaml for a runnable multi-hop example with Jaeger, and examples/monitoring-tracing/opentelemetry for screenshots.
paddingHeader0..1Adds an X-Padding header with random characters to pad message size (request/response).
prometheus0..1Prometheus is an open-source monitoring system that collects metrics by scraping HTTP endpoints at regular intervals. Deploy this element on a dedicated endpoint to expose Membrane's internal metrics in the Prometheus text exposition format (v0.0.4).
rateLimiter0..1The rateLimiter plugin limits the number of requests of a client in a period of time. As a default the client requests are grouped by client-Ip address and then counted. There are lots of possibilities to group the requests using the keyExpression. The requests can even be counted from different clients together.
regExReplacer0..1Runs a regular-expression-replacement on either the message body (default) or all header values.
replace0..1Replaces a JSON value at the configured JSONPath with a static string.
requireAuth0..1
rest2Soap0..1Converts REST requests into SOAP messages.
return0..1Stops processing the request and sends a response back to the client without calling the backend. If the exchange already holds a response, that response is sent; otherwise a new response is built from the request's body and Content-Type. Often paired with template to return a generated body. See the examples under examples/templating.
reverseProxying0..1Rewrites the scheme, hostname and port in the "Location" header in HTTP responses, as well as in the "Destination" header in HTTP requests. The rewriting reflects the different schemes, hostnames and ports used to access Membrane vs. the target HTTP server.
rewriter0..*Rewrites or redirects the path of incoming requests based on a mapping.
ruleMatching0..1Selects and assigns the matching proxy rule for incoming requests; optionally adds/extends X-Forwarded-* headers.
sampleSoapService0..1
setBody0..1Sets the body of the current HTTP message to a static string or a computed expression. SpEL template expressions are supported by default; Groovy, JsonPath, and XPath are also available. For conditional output or loops, use the template interceptor instead. See tutorials/getting-started/65-SetBody.yaml.
setCookies0..*Adds one or more Set-Cookie headers to the HTTP response for session handling, user preferences, or tracking purposes. Supports computing expiry, setting standard attributes like Domain and Path, and building a compliant cookie string. Useful for enriching responses with configurable cookies directly at gateway level without backend involvement.
setHeader0..1Sets an HTTP header field on the current message to a constant string or a computed value. SpEL template expressions are supported by default; Groovy, JsonPath, and XPath are also available. See tutorials/getting-started/60-SetHeader.yaml.
setProperty0..1
shadowing0..1Clones incoming requests and sends them asynchronously to one or more shadow targets (main exchange continues unchanged).
shutdown0..1Shutdown interceptor.
soap2Rest0..1Converts SOAP messages into REST requests.
soapBody0..1Renders a SOAP body for legacy integration. The Content-Type defaults to the type of the configured SOAP version (text/xml for 1.1, application/soap+xml for 1.2). Setting contentType explicitly overrides this, e.g. to add a charset.
soapOperationExtractor0..1
soapStackTraceFilter0..1The soapStackTraceFilter removes SOAP stack traces from message bodies.
sqlInjectionProtection0..1Detects SQL injection patterns in incoming requests and blocks them before they reach the backend. Inspects query parameters, the request path, form and JSON bodies (and optionally headers) against a set of detection rules transpiled from the OWASP Core Rule Set (CRS) REQUEST-942 SQL-injection rules.
sseDemoStream0..1
static0..1Sets the message body to static content. The body is either provided inline as text content or loaded from a file/URL. If pretty is enabled, the formatted result is cached and reused until the interceptor is (re)initialized.
statisticsCSV0..1Writes statistics (time, status code, hostname, URI, etc.) about exchanges passing through into a CSV file (one line per exchange).
statisticsJDBC0..1Writes statistics (time, status code, hostname, URI, etc.) about exchanges passing through into a database (one row per exchange).
statisticsProvider0..1Serves request statistics as JSON from a JDBC-backed store. Supports paging (offset/max) and sorting (sort/order) via query parameters.
stompClient0..1
tcp0..1Allow HTTP protocol upgrades to the TCP protocol. After the upgrade, the connection's data packets are simply forwarded and not inspected.
template0..1Renders the body content of a message from a template. The template can produce plain text, Json or XML. Variables in the template are substituted with values from the body, header, query parameters, etc. If the extension of a referenced template file is .xml it will use XMLTemplateEngine otherwise StreamingTemplateEngine. Have a look at the samples in examples/templating. When the contentType is a JSON variant (e.g., application/json), the engine automatically escapes all inserted values. For example, in the JSON templating example, executing curl "localhost:2000/?answer=20" returns { "answer" : "20" }. The quotes surrounding the value 20 are added by the auto-escaping mechanism to ensure the output remains a valid string. This feature significantly mitigates security risks by preventing inadvertent JSON injection attacks.
throttle0..1Throttles incoming traffic by delaying requests and/or capping how many are processed concurrently, to protect a backend from overload. With delay set, every request is held briefly before it continues. With maxThreads set, a request that arrives while the limit is already reached is rejected with 503 once no slot frees up. See the examples under examples/routing-traffic/throttle.
time0..1Measures the end-to-end processing time of the child interceptor flow and logs an aligned summary. If an OpenTelemetry parent Span is present on the {@link Exchange}, a child sub-span is created around the measured section so timing data is exported to OTel as well.
tokenValidator0..1
transform0..1Applies an XSLT stylesheet to the body of a request or response and replaces the body with the transformation result. Every string-valued Exchange property is passed to the stylesheet as an XSLT parameter of the same name; declare a matching xsl:param in the stylesheet to read it. Set such a property beforehand, e.g. with setProperty. See tutorials/xml/35-XSLT-Transformation-to-json.yaml.
userFeature0..1Handles features that are user-configured in proxies.xml .
validator0..1Validates request and response message bodies against a schema. The schema type is selected by the attribute you set: wsdl for SOAP messages, schema for XML against an XSD, jsonSchema for JSON or YAML, or schematron. Exactly one of them must be configured; inside a soapProxy the WSDL is taken from the proxy automatically. An empty body passes; an invalid body is rejected, either with a detailed error response or a generic one plus a log entry, depending on failureHandler. See the examples under examples/validation, examples/xml/xml-validation, and examples/web-services-soap/soap-wsdl-validation.
webServer0..1Serves static files based on the request's path.
webServiceExplorer0..1Serves an HTML “web service explorer”.
webSocket0..1Allow HTTP protocol upgrades to the WebSocket protocol. After the upgrade, the connection's data packets are simply forwarded and not inspected.
wsaEndpointRewriter0..1
wsdlPublisher0..1The wsdlPublisher serves WSDL files (and attached XML Schema Documents), if your backend service does not already do so.
wsdlRewriter0..1Rewrites SOAP endpoint addresses and XML Schema locations (XSD import and include) in WSDL and XSD documents returned by the backend, so they point at the gateway instead of the backend's own address. By default the gateway's protocol, host, and port from the incoming request are used; set the attributes below to force a specific address. Typically used inside a soapProxy, where the service path is taken from the proxy. See the tutorial tutorials/soap/30-WSDL-Rewriter.yaml.
xenAuthentication0..1
xml2Json0..1Converts an XML message body to JSON.
xmlContentFilter0..1The xmlContentFilter removes certain XML elements from message bodies. The elements are described using an XPath expression.
xmlProtection0..1Prohibits XML documents to be passed through that look like XML attacks on older parsers. Too many attributes, too long element names are such indications. DTD definitions will simply be removed.

Can be used in