Core Concepts
Servlet Integration
Soklet is not a Servlet Container - it has its own in-process HTTP server, its own approach to request and response constructs, and so forth. Soklet applications are intended to be "vanilla" Java applications, as opposed to a WAR file deployed onto a Java EE application server.
However, there is a large body of existing code that relies on the Servlet API. To support it, Soklet provides its own implementations of the following Servlet interfaces, which enable interoperability for many common use cases:
| Interface/helper | javax implementation | Jakarta implementation |
|---|---|---|
HttpServletRequest | Javadoc | Javadoc |
HttpServletResponse | Javadoc | Javadoc |
HttpSession | Javadoc | Javadoc |
HttpSessionContext | Javadoc | Not part of Jakarta Servlet |
ServletContext | Javadoc | Javadoc |
ServletInputStream | Javadoc | Javadoc |
ServletOutputStream | Javadoc | Javadoc |
ServletPrintWriter | Javadoc | Javadoc |
Support is available for both legacy javax.servlet and current jakarta.servlet specifications. Just like Soklet, these integrations have zero dependencies (not counting Soklet itself and the javax.servlet-api/jakarta.servlet-api spec JARs) - drop the appropriate JAR into your project and you're good to go.
Both adapters accept at most 1,000 nonempty query and form pairs combined, including repetitions; parameter access beyond that bound raises IllegalRequestException (normally HTTP 400). A configured filesystemResourceRoot must already exist and be a trusted, immutable directory. The adapter pins its real path, permits links only within it, and rejects escapes. getResourceAsStream returns null for missing, invalid, or directory resources. URLs returned by getResource may be opened later, so concurrent tree mutation remains outside the supported contract.
classpathResourceRoot uses slash-separated class-loader resource names. An empty prefix or / selects the classpath root; an ordinary prefix may have one leading /. Configured prefixes reject backslashes, NUL, .. segments, a remaining leading /, and a leading Windows drive qualifier. Invalid prefixes fail configuration with IllegalArgumentException. Resource lookup paths reject the same forms after their required leading /, returning null before class-loader access or directory-listing fallback. Use / separators on every platform, including Windows.
Installation
Both adapter artifacts are version 2.0.0 and require Soklet 4.0.0 or later. Adapter 2.x does not support Soklet 3.x. Soklet and the chosen Servlet API are provided dependencies of the adapter, so the application must supply them explicitly. Upgrade the adapter and core together, then follow the core migration guide. The examples below are for standalone applications that also supply the Servlet API themselves.
Maven
If you use javax.servlet:
<dependency>
<groupId>com.soklet</groupId>
<artifactId>soklet-servlet-javax</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.soklet</groupId>
<artifactId>soklet</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.soklet</groupId>
<artifactId>soklet-servlet-javax</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.soklet</groupId>
<artifactId>soklet</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
If you use jakarta.servlet:
<dependency>
<groupId>com.soklet</groupId>
<artifactId>soklet-servlet-jakarta</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.soklet</groupId>
<artifactId>soklet</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
</dependency>
<dependency>
<groupId>com.soklet</groupId>
<artifactId>soklet-servlet-jakarta</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.soklet</groupId>
<artifactId>soklet</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
</dependency>
Gradle
If you use javax.servlet:
repositories {
mavenCentral()
}
dependencies {
implementation 'com.soklet:soklet-servlet-javax:2.0.0'
implementation 'com.soklet:soklet:4.0.0'
implementation 'javax.servlet:javax.servlet-api:4.0.1'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.soklet:soklet-servlet-javax:2.0.0'
implementation 'com.soklet:soklet:4.0.0'
implementation 'javax.servlet:javax.servlet-api:4.0.1'
}
If you use jakarta.servlet:
repositories {
mavenCentral()
}
dependencies {
implementation 'com.soklet:soklet-servlet-jakarta:2.0.0'
implementation 'com.soklet:soklet:4.0.0'
implementation 'jakarta.servlet:jakarta.servlet-api:6.1.0'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'com.soklet:soklet-servlet-jakarta:2.0.0'
implementation 'com.soklet:soklet:4.0.0'
implementation 'jakarta.servlet:jakarta.servlet-api:6.1.0'
}
Request Parameters and Sessions
Query parameters use UTF-8, independently of the request-body charset. Automatic form decoding applies to POST bodies with application/x-www-form-urlencoded and uses the selected body charset. Set the encoding before reading parameters or the body. Malformed or unmappable bytes in parameter names or values raise IllegalRequestException; the default Soklet error marshaler returns HTTP 400. Valid encoded U+FFFD remains legal. All parameter accessors share one snapshot, including a retained decoding failure; subsequent calls rethrow that failure. Repeated values remain ordered, with query values before form values.
Concurrent setAttribute(name, sameValue) calls share an in-progress binding notification. An ordinary follower waits at most 200 milliseconds or until interrupted, then returns without another valueBound; it may return before the owner publishes the attribute. Interruption restores the thread's interrupt status. The owner remains responsible for publication and balanced unbinding. Completed listener failures propagate to the owner and followers that observe completion before returning, and listener reentry does not wait. Binding listeners should avoid waiting for work or locks that a concurrent setter may hold.
Both response conversions normalize empty 204, 205, and 304 buffers to absent bodies. A nonempty body returned from a resource method on these statuses remains invalid; ordinary empty 200 responses keep their byte-array representation.
Response Buffering and Streaming
The default local commit threshold is 1,024 bytes. It does not cap captured body size or flush network bytes.
Both adapters' SokletHttpServletResponse implementations capture the entire response body in memory. Writes through getWriter() or getOutputStream() accumulate locally. toMarshaledResponse() and toResponse() copy the captured body into a finite Soklet response; conversion does not send it. Delivery begins when the application hands that response to Soklet.
flushBuffer(), writer/output-stream flushes, and buffer-size commits update the adapter's local commitment state. They do not flush a network response or make bytes visible to the client early.isCommitted()reports this local state, not whether Soklet has sent response headers.- If the selected response charset has no encoder (for example,
ISO-2022-CN),getWriter()throwsUnsupportedEncodingExceptionwithout acquiring the writer or locking the output method. Before commitment, choose a supported encoding and retry, or use the raw output stream. Existing commitment is retained. setBufferSize(...)configures the local commit threshold. It is not a body-size or memory limit: the capture can keep growing after that threshold is reached. Memory use grows with the captured body, and conversion requires additional body copies. Bound generated response sizes and account for concurrent captures in your application's memory budget.- The response adapter has no
ResponseStream-backed mode. HTTP request-size limits and native streaming queue bounds do not cap its captured output.
Use these response adapters for finite responses small enough to capture in memory. For large known-length files, use File and Buffer Responses. For incremental exports, token delivery, or live feeds, use Streaming Responses; for event streams, see Server-Sent Events.
The standalone SokletServletOutputStream helper delegates to a supplied OutputStream. Using that helper with a different sink does not change SokletHttpServletResponse.getOutputStream() or connect the response adapter's status, headers, and commitment state to a native stream.
Usage
Servlet request header access preserves complete field occurrences, including comma-separated content and empty values. HttpServletRequest.getHeader(name) returns the first occurrence, while getHeaders(name) enumerates all occurrences in order. Core Request.getHeader(name) requires at most one occurrence and rejects repeats. Locale parsing continues to interpret the comma lists within Accept-Language fields.
For annotated Soklet routes, also apply the compiler/processor configuration to either build. The examples below use the javax names. For Jakarta, import jakarta.servlet.*/jakarta.servlet.http.* and the corresponding com.soklet.servlet.jakarta.* classes; use the Jakarta Javadocs in the table above rather than the javax links in the walkthrough.
A normal Servlet API integration looks like the following:
- Given a Soklet
Request, create both anHttpServletRequestand anHttpServletResponse. - Write whatever is needed to
HttpServletResponse - Convert the
HttpServletResponseto a SokletMarshaledResponse
@GET("/servlet-example")
public MarshaledResponse servletExample(Request request) throws IOException {
// Create an HttpServletRequest from the Soklet Request
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// Create an HttpServletResponse from the request
SokletHttpServletResponse httpServletResponse =
SokletHttpServletResponse.fromHttpServletRequest(httpServletRequest);
// Write some data to the response using Servlet APIs
Cookie cookie = new Cookie("name", "value");
cookie.setDomain("soklet.com");
cookie.setMaxAge(60);
cookie.setPath("/");
httpServletResponse.setStatus(200);
httpServletResponse.addHeader("test", "one");
httpServletResponse.addHeader("test", "two");
httpServletResponse.addCookie(cookie);
httpServletResponse.setCharacterEncoding("ISO-8859-1");
httpServletResponse.getWriter().print("test");
// Convert HttpServletResponse into a Soklet MarshaledResponse and return it
return httpServletResponse.toMarshaledResponse();
}
@GET("/servlet-example")
public MarshaledResponse servletExample(Request request) throws IOException {
// Create an HttpServletRequest from the Soklet Request
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// Create an HttpServletResponse from the request
SokletHttpServletResponse httpServletResponse =
SokletHttpServletResponse.fromHttpServletRequest(httpServletRequest);
// Write some data to the response using Servlet APIs
Cookie cookie = new Cookie("name", "value");
cookie.setDomain("soklet.com");
cookie.setMaxAge(60);
cookie.setPath("/");
httpServletResponse.setStatus(200);
httpServletResponse.addHeader("test", "one");
httpServletResponse.addHeader("test", "two");
httpServletResponse.addCookie(cookie);
httpServletResponse.setCharacterEncoding("ISO-8859-1");
httpServletResponse.getWriter().print("test");
// Convert HttpServletResponse into a Soklet MarshaledResponse and return it
return httpServletResponse.toMarshaledResponse();
}
Instantiation
Soklet's Servlet API types are final and prefer static factory methods to constructors.
Here's how to acquire an instance of each.
HttpServletRequest
Standard approach, uses defaults:
@GET("/servlet-example")
public MarshaledResponse servletExample(Request request) throws IOException {
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// ... rest of method elided ...
}
@GET("/servlet-example")
public MarshaledResponse servletExample(Request request) throws IOException {
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// ... rest of method elided ...
}
Custom approach:
@GET("/servlet-example")
public MarshaledResponse servletExample(Request request) throws IOException {
// Get references to some dependencies...
ServletContext servletContext = SokletServletContext.fromDefaults();
HttpSession httpSession = SokletHttpSession.fromServletContext(servletContext);
// ...and supply to the builder:
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.withRequest(request)
.port(1234)
.host("0.0.0.0")
.servletContext(servletContext)
.httpSession(httpSession)
// Controls whether `Forwarded`/`X-Forwarded-*` headers are trusted
// when resolving the effective origin
.forwardedHeaderTrustPolicy(TrustPolicy.TRUST_PROXY_ALLOWLIST)
// Provide a proxy allowlist when `TRUST_PROXY_ALLOWLIST` is selected
// (one is required for that policy)
.trustedProxyAddresses(Set.of(InetAddress.getByName("10.0.0.1")))
// Toggles whether the `Origin` header is used as a fallback
// when determining the effective origin
.allowOriginFallback(true)
.build();
// ... rest of method elided ...
}
@GET("/servlet-example")
public MarshaledResponse servletExample(Request request) throws IOException {
// Get references to some dependencies...
ServletContext servletContext = SokletServletContext.fromDefaults();
HttpSession httpSession = SokletHttpSession.fromServletContext(servletContext);
// ...and supply to the builder:
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.withRequest(request)
.port(1234)
.host("0.0.0.0")
.servletContext(servletContext)
.httpSession(httpSession)
// Controls whether `Forwarded`/`X-Forwarded-*` headers are trusted
// when resolving the effective origin
.forwardedHeaderTrustPolicy(TrustPolicy.TRUST_PROXY_ALLOWLIST)
// Provide a proxy allowlist when `TRUST_PROXY_ALLOWLIST` is selected
// (one is required for that policy)
.trustedProxyAddresses(Set.of(InetAddress.getByName("10.0.0.1")))
// Toggles whether the `Origin` header is used as a fallback
// when determining the effective origin
.allowOriginFallback(true)
.build();
// ... rest of method elided ...
}
HttpServletResponse
Standard approach, in which a ServletContext is shared by the request/response pair:
@GET("/servlet-example")
public MarshaledResponse responseExample(Request request) {
// Create an HttpServletRequest from the Soklet Request...
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// Then, create an HttpServletResponse from that request.
SokletHttpServletResponse httpServletResponse =
SokletHttpServletResponse.fromHttpServletRequest(httpServletRequest);
// ... rest of method elided ...
}
@GET("/servlet-example")
public MarshaledResponse responseExample(Request request) {
// Create an HttpServletRequest from the Soklet Request...
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// Then, create an HttpServletResponse from that request.
SokletHttpServletResponse httpServletResponse =
SokletHttpServletResponse.fromHttpServletRequest(httpServletRequest);
// ... rest of method elided ...
}
Alternatively, you can specify a regular Soklet Request in conjunction with a ServletContext to construct your HttpServletResponse:
Request request = ...;
ServletContext servletContext = SokletServletContext.fromDefaults();
// Combine a Soklet request with a ServletContext
HttpServletResponse response =
SokletHttpServletResponse.fromRequest(request, servletContext);
Request request = ...;
ServletContext servletContext = SokletServletContext.fromDefaults();
// Combine a Soklet request with a ServletContext
HttpServletResponse response =
SokletHttpServletResponse.fromRequest(request, servletContext);
...or specify an explicit request path (undecoded, no query string - matches semantics of Request::getRawPath) and combine with a ServletContext:
ServletContext servletContext = SokletServletContext.fromDefaults();
// Request path must always starts with "/"
HttpServletResponse response =
SokletHttpServletResponse.fromRawPath("/test/abc", servletContext);
ServletContext servletContext = SokletServletContext.fromDefaults();
// Request path must always starts with "/"
HttpServletResponse response =
SokletHttpServletResponse.fromRawPath("/test/abc", servletContext);
HttpSession
// Sessions need a context...
ServletContext servletContext = SokletServletContext.fromDefaults();
// ...so we get one and wire it in:
HttpSession httpSession = SokletHttpSession.fromServletContext(servletContext);
// Sessions need a context...
ServletContext servletContext = SokletServletContext.fromDefaults();
// ...so we get one and wire it in:
HttpSession httpSession = SokletHttpSession.fromServletContext(servletContext);
HttpSessionContext
Deprecation Warning
The Servlet spec has marked javax.servlet.http.HttpSessionContext as deprecated since Servlet API 2.1 with no replacement, so it's unlikely you will need to use this type - but it's available regardless.
This type is not available for jakarta.servlet integration.
HttpSessionContext httpSessionContext = SokletHttpSessionContext.fromDefaults();
HttpSessionContext httpSessionContext = SokletHttpSessionContext.fromDefaults();
ServletContext
Standard approach:
ServletContext servletContext = SokletServletContext.fromDefaults();
ServletContext servletContext = SokletServletContext.fromDefaults();
Builder approach with explicit java.io.Writer which acts as a sink for ServletContext::log(String) and ServletContext::log(String, Throwable) invocations:
try(FileWriter logWriter = new FileWriter("example.txt")) {
ServletContext servletContext =
SokletServletContext.builder()
// Writer sink for ServletContext::log(...)
.logWriter(logWriter)
// Filesystem resource root for getResource* lookups...
.filesystemResourceRoot(Paths.get("/var/www"))
// Alternatively, replace the preceding setter with:
// .classpathResourceRoot("/public")
// Choose one resource root; the last setter wins if both are called.
// Session timeout (per Servlet spec)
.sessionTimeout(30)
// Default request character encoding
.requestCharacterEncoding(StandardCharsets.UTF_8)
// Default response character encoding
.responseCharacterEncoding(StandardCharsets.UTF_8)
.build();
// Fire off a log event to be consumed by the writer
servletContext.log("Just a test");
}
try(FileWriter logWriter = new FileWriter("example.txt")) {
ServletContext servletContext =
SokletServletContext.builder()
// Writer sink for ServletContext::log(...)
.logWriter(logWriter)
// Filesystem resource root for getResource* lookups...
.filesystemResourceRoot(Paths.get("/var/www"))
// Alternatively, replace the preceding setter with:
// .classpathResourceRoot("/public")
// Choose one resource root; the last setter wins if both are called.
// Session timeout (per Servlet spec)
.sessionTimeout(30)
// Default request character encoding
.requestCharacterEncoding(StandardCharsets.UTF_8)
// Default response character encoding
.responseCharacterEncoding(StandardCharsets.UTF_8)
.build();
// Fire off a log event to be consumed by the writer
servletContext.log("Just a test");
}
ServletInputStream
try(InputStream inputStream = ...) {
ServletInputStream servletInputStream =
SokletServletInputStream.fromInputStream(inputStream);
// Work with servletInputStream
}
try(InputStream inputStream = ...) {
ServletInputStream servletInputStream =
SokletServletInputStream.fromInputStream(inputStream);
// Work with servletInputStream
}
ServletOutputStream
Standard approach:
try(OutputStream outputStream = ...) {
ServletOutputStream servletOutputStream =
SokletServletOutputStream.fromOutputStream(outputStream);
// Work with servletOutputStream
}
try(OutputStream outputStream = ...) {
ServletOutputStream servletOutputStream =
SokletServletOutputStream.fromOutputStream(outputStream);
// Work with servletOutputStream
}
With listeners:
try(OutputStream outputStream = ...) {
ServletOutputStream servletOutputStream =
SokletServletOutputStream.withOutputStream(outputStream)
.onWriteOccurred((stream, writtenByte) -> {
// Take action when a write occurred
})
.onWriteFinalized((stream) -> {
// Take action when the writes have been finalized (totally done)
})
.build();
// Work with servletOutputStream
}
try(OutputStream outputStream = ...) {
ServletOutputStream servletOutputStream =
SokletServletOutputStream.withOutputStream(outputStream)
.onWriteOccurred((stream, writtenByte) -> {
// Take action when a write occurred
})
.onWriteFinalized((stream) -> {
// Take action when the writes have been finalized (totally done)
})
.build();
// Work with servletOutputStream
}
ServletPrintWriter
Standard approach:
try(Writer writer = ...) {
SokletServletPrintWriter servletPrintWriter =
SokletServletPrintWriter.fromWriter(writer);
// Work with writer
}
try(Writer writer = ...) {
SokletServletPrintWriter servletPrintWriter =
SokletServletPrintWriter.fromWriter(writer);
// Work with writer
}
With listeners:
try(Writer writer = ...) {
SokletServletPrintWriter servletPrintWriter =
SokletServletPrintWriter.withWriter(writer)
.onWriteOccurred((printWriter, writerEvent) -> {
// Take action when a write occurred
})
.onWriteFinalized((printWriter) -> {
// Take action when the writes have been finalized (totally done)
})
.build();
// Work with servletPrintWriter
}
try(Writer writer = ...) {
SokletServletPrintWriter servletPrintWriter =
SokletServletPrintWriter.withWriter(writer)
.onWriteOccurred((printWriter, writerEvent) -> {
// Take action when a write occurred
})
.onWriteFinalized((printWriter) -> {
// Take action when the writes have been finalized (totally done)
})
.build();
// Work with servletPrintWriter
}
Real-World Example
Suppose you'd like to have your application function as a SAML Service Provider (SP), where you redirect to a SAML Identity Provider (IdP) to perform authentication and rely on it to POST back a cryptographically-signed assertion confirming the user is who she says she is.
You might prefer to use a library like OneLogin's SAML Java Toolkit instead of writing your own SP implementation. Because this library is designed specifically for the Servlet API, Soklet's Servlet integration is necessary to use it.
Here's how an integration might look. This example serves the SAML callback and the signed-in home page on the same HTTPS origin, https://my.example.website. Configure Saml2Settings with the assertion-consumer URL https://my.example.website/saml/process-assertion; OneLogin's login argument is a RelayState return URL, not that callback setting. The credential cookie stays host-only and uses Path=/, so requests to /home and other routes on that origin can carry it. Supply your application's assertion validation and token policies.
First, we need to be able to redirect to the IdP for login:
@GET("/saml/redirect-to-login")
public MarshaledResponse redirectToSamlLogin(Request request) throws Exception {
// Create an HttpServletRequest from the Soklet Request
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// Create an HttpServletResponse from the request
SokletHttpServletResponse httpServletResponse =
SokletHttpServletResponse.fromHttpServletRequest(httpServletRequest);
// Configure SAML Java Toolkit (details not shown)...
Saml2Settings settings = acquireSaml2Settings();
// ...and let it do its work on the HttpServletRequest/HttpServletResponse.
// Behind the scenes, the toolkit creates an AuthnRequest, signs it if
// configured in Saml2Settings, and sends an HTTP 302 redirect to the IdP.
Auth auth = new Auth(settings, httpServletRequest, httpServletResponse);
auth.login("https://my.example.website/home");
// Convert HttpServletResponse into a MarshaledResponse and return it.
// Any headers/cookies/body/etc. written to the HttpServletResponse
// are carried over into the Soklet marshaled-response representation
return httpServletResponse.toMarshaledResponse();
}
@GET("/saml/redirect-to-login")
public MarshaledResponse redirectToSamlLogin(Request request) throws Exception {
// Create an HttpServletRequest from the Soklet Request
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// Create an HttpServletResponse from the request
SokletHttpServletResponse httpServletResponse =
SokletHttpServletResponse.fromHttpServletRequest(httpServletRequest);
// Configure SAML Java Toolkit (details not shown)...
Saml2Settings settings = acquireSaml2Settings();
// ...and let it do its work on the HttpServletRequest/HttpServletResponse.
// Behind the scenes, the toolkit creates an AuthnRequest, signs it if
// configured in Saml2Settings, and sends an HTTP 302 redirect to the IdP.
Auth auth = new Auth(settings, httpServletRequest, httpServletResponse);
auth.login("https://my.example.website/home");
// Convert HttpServletResponse into a MarshaledResponse and return it.
// Any headers/cookies/body/etc. written to the HttpServletResponse
// are carried over into the Soklet marshaled-response representation
return httpServletResponse.toMarshaledResponse();
}
Next, we need a way to process the XML assertion sent back to us by the IdP after a successful login:
@POST("/saml/process-assertion")
public Response processSamlAssertion(
Request request,
MyExampleBackend myExampleBackend
) throws Exception {
// Create an HttpServletRequest from the Soklet Request
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// Create an HttpServletResponse from the request
SokletHttpServletResponse httpServletResponse =
SokletHttpServletResponse.fromHttpServletRequest(httpServletRequest);
// Configure SAML Java Toolkit (details not shown)...
Saml2Settings settings = acquireSaml2Settings();
// ...and let it do its work.
// Here, SAML Java Toolkit parses the assertion and ensures that
// the IdP's private key was used to sign it.
Auth auth = new Auth(settings, httpServletRequest, httpServletResponse);
auth.processResponse();
if (auth.isAuthenticated()) {
// Everything looks good...
// 1. Pull the user identifier out of the assertion
// 2. Use it to generate a JWT
// 3. Write the JWT to a cookie
// 4. Redirect the user somewhere meaningful
String jwt = myExampleBackend.jwtForNameId(auth.getNameId());
return Response.withRedirect(
RedirectType.HTTP_303_SEE_OTHER,
"https://my.example.website/home"
).cookies(List.of(
ResponseCookie.with("Access-Token", jwt)
.path("/")
.secure(true)
.httpOnly(true)
.sameSite(ResponseCookie.SameSite.LAX)
.build()
))
.build();
} else {
// Real systems should handle this more gracefully
throw new RuntimeException("The SAML assertion is invalid");
}
}
@POST("/saml/process-assertion")
public Response processSamlAssertion(
Request request,
MyExampleBackend myExampleBackend
) throws Exception {
// Create an HttpServletRequest from the Soklet Request
HttpServletRequest httpServletRequest =
SokletHttpServletRequest.fromRequest(request);
// Create an HttpServletResponse from the request
SokletHttpServletResponse httpServletResponse =
SokletHttpServletResponse.fromHttpServletRequest(httpServletRequest);
// Configure SAML Java Toolkit (details not shown)...
Saml2Settings settings = acquireSaml2Settings();
// ...and let it do its work.
// Here, SAML Java Toolkit parses the assertion and ensures that
// the IdP's private key was used to sign it.
Auth auth = new Auth(settings, httpServletRequest, httpServletResponse);
auth.processResponse();
if (auth.isAuthenticated()) {
// Everything looks good...
// 1. Pull the user identifier out of the assertion
// 2. Use it to generate a JWT
// 3. Write the JWT to a cookie
// 4. Redirect the user somewhere meaningful
String jwt = myExampleBackend.jwtForNameId(auth.getNameId());
return Response.withRedirect(
RedirectType.HTTP_303_SEE_OTHER,
"https://my.example.website/home"
).cookies(List.of(
ResponseCookie.with("Access-Token", jwt)
.path("/")
.secure(true)
.httpOnly(true)
.sameSite(ResponseCookie.SameSite.LAX)
.build()
))
.build();
} else {
// Real systems should handle this more gracefully
throw new RuntimeException("The SAML assertion is invalid");
}
}
The 303 redirect fetches the home page with GET after processing the assertion. The token cookie is set only after that validation succeeds; it does not provide correlation or replay protection for the earlier SAML exchange. If your API and frontend use different origins, design their authentication flow and cookie policy explicitly instead of copying this same-origin example unchanged.
Forwarded client address and port
Both adapters use Soklet's EffectiveClientIpResolver and the configured proxy trust policy. With TRUST_PROXY_ALLOWLIST, client selection walks the IP chain from right to left through trusted proxy hops. A forwarded port belongs to the selected client entry and is zero if that entry has no port. Unusable or untrusted forwarding falls back to the socket peer and its port. Only IP literals are used; this lookup performs no DNS resolution. IPv6 addresses use InetAddress.getHostAddress() formatting.

