DavKit integration and storage providers
Register a DavResourceProvider to expose your application’s documents to desktop Office. DavKit handles WebDAV discovery, locking and HTTP conditions; the provider maps document paths, checks application permissions and reads or replaces the bytes.
These examples use Java 17 and DavKit 1.0.11.
Add the starter
dependencies {
implementation("com.tucanoo.davkit:davkit-spring-boot-starter:1.0.11")
}The starter brings in the matching davkit-server dependency from Maven Central. Keep all DavKit components on the same version. Supply a valid licence key; you can request one through the evaluation form.
davkit:
enabled: true
path: /webdav
license-key: ${DAVKIT_LICENSE_KEY}
logging:
level:
com.tucanoo.davkit: INFOSet davkit.enabled through Spring Boot external configuration before auto-configuration runs. For a custom configuration loader, use an EnvironmentPostProcessor to load settings before the application context refresh.
Implement a provider
This complete provider serves one existing document at /webdav/documents/Report.docx. It keeps bytes in memory and lets only the stored owner subject read or write. Use it to test the SPI in a development host; saves disappear when that host restarts. For persistent storage, use the public JPA demo provider as a starting point, replacing its unrestricted demo permissions with your own access rules.
package example.davkit;
import com.tucanoo.davkit.spi.*;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
public final class SingleDocumentProvider implements DavResourceProvider {
private final String key;
private final String filename;
private final String ownerSubject;
private final Instant created = Instant.now();
private volatile Snapshot current;
private record Snapshot(byte[] bytes, long version, Instant modified) {}
public SingleDocumentProvider(String key, String filename,
String ownerSubject, byte[] initialBytes) {
this.key = Objects.requireNonNull(key);
this.filename = Objects.requireNonNull(filename);
this.ownerSubject = Objects.requireNonNull(ownerSubject);
this.current = new Snapshot(initialBytes.clone(), 1, created);
}
@Override
public String mountPoint() { return "documents"; }
@Override
public Optional<DavResource> resolve(DavPath path, DavContext ctx) {
if (!path.remainderFor(mountPoint()).equals(java.util.List.of(filename))) {
return Optional.empty();
}
return Optional.of(describe(current, path, ctx));
}
@Override
public DavContent read(DavResource resource, DavContext ctx) {
requireOwner(ctx);
Snapshot snapshot = resource.attribute("snapshot", Snapshot.class)
.orElseThrow();
return DavContent.of(snapshot.bytes());
}
@Override
public DavResource write(DavResource resource, DavWriteRequest request,
DavContext ctx) throws IOException {
requireOwner(ctx);
byte[] replacement;
try (InputStream in = request.content().open()) {
replacement = in.readAllBytes();
}
synchronized (this) {
if (!resource.etag().equals(Long.toString(current.version()))) {
throw new DavPreconditionFailedException("document changed");
}
current = new Snapshot(replacement, current.version() + 1, Instant.now());
return describe(current, resource.path(), ctx);
}
}
private void requireOwner(DavContext ctx) {
if (!ownerSubject.equals(ctx.principal().id())) {
throw new DavAccessDeniedException("access denied");
}
}
private DavResource describe(Snapshot snapshot, DavPath path, DavContext ctx) {
DavPermissions permissions = ownerSubject.equals(ctx.principal().id())
? DavPermissions.READ_WRITE : DavPermissions.NONE;
return new DavResource(
key, path, filename, false, null,
snapshot.bytes().length, Long.toString(snapshot.version()),
snapshot.modified(), Optional.of(created), permissions,
Map.of("snapshot", snapshot));
}
}Save the class as src/main/java/example/davkit/SingleDocumentProvider.java. Use a package beneath your Boot application’s component-scan package, and update the example.davkit package declaration in both the provider and configuration class below. The file below must be a real Office document; user:42 illustrates the identity label your host uses for its owner.
package example.davkit;
import com.tucanoo.davkit.spi.DavResourceProvider;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DocumentDavConfiguration {
@Bean
DavResourceProvider documents() throws IOException {
return new SingleDocumentProvider("document:123", "Report.docx",
"user:42", Files.readAllBytes(Path.of("Report.docx")));
}
}The owner subject is application data. Use the same identity namespace when signing links and checking document permissions. The sample returns NONE for another subject; DavKit rejects document access with 403.
Return current metadata
A DavResource is a metadata snapshot. Its constructor takes these fields, in order:
| Field | What to return |
|---|---|
key | Stable document identity used for locking and audit. Keep it when the name, path or content changes. |
path | The decoded DavPath passed to resolution, below the DavKit endpoint. |
displayName | The filename Office displays. |
collection | false for a document. DavKit supplies the root and provider mount collections. |
contentType | The MIME type, or null to derive it from the extension. |
contentLength | Byte count, or -1 when unknown; unknown length disables Range support. |
etag | A strong content validator that changes on every content change. DavKit quotes it in HTTP headers. |
lastModified | Required modification time. |
created | An Optional<Instant>; empty is valid. |
permissions | The current principal’s effective read and write permissions, and permission to unlock another user’s lock. |
attributes | Optional provider-private request data. Never retain an open session, connection or stream here. |
The sample keeps document:123 as its key and increments its ETag on each save. It stores an immutable byte snapshot in attributes, so a GET streams the same bytes described by that request’s metadata.
A write must either replace the whole document or leave the old bytes intact. The sample reads the incoming body before changing shared state, then checks and replaces the version under one monitor. Two writes based on the same ETag cannot both succeed. A stale write throws DavPreconditionFailedException, which DavKit returns as HTTP 412. The returned resource has the new ETag, length and modification time.
DavWriteRequest contains the incoming content, optional ifMatch, current lock and optional declaredContentType. DavKit has already checked the HTTP condition and lock before calling write. Your storage transaction must still detect changes committed after resolution; with a database, compare the resolved ETag and retain optimistic locking through flush/commit. Bound buffering for large files or use a storage-specific atomic streaming replacement.
Sign links for the right subject
A signed URL is a bearer credential. Anyone who obtains it can use it within its scope until it expires. Issue it only after your application has checked access, take its subject from a trusted authenticated identity, and keep the URL out of logs and public pages. Office authenticates separately from the browser; the document URL does not carry the browser’s login session.
For signed-URL authentication, ctx.principal().id() is the signed subject. The DavPrincipal also carries the signed scope and expiry. DavKit does not reconstruct your application’s user, Grails user object or roles. If permissions depend on a user record, tenant or ACL, load that information in your provider using the subject and return the effective DavPermissions.
In a handler with the injected SignedUrls bean, use the authenticated user’s identifier and your configured public HTTPS origin. Authorise the document before rendering the link. The path returned by DavKit is already tokenised and percent-encoded; let your HTML template encode the final href attribute.
import com.tucanoo.davkit.auth.SignedUrls;
// signedUrls: injected bean; userId: trusted authenticated subject.
// publicOrigin: configured origin, such as https://app.example.com.
String path = signedUrls.path(userId, "documents/Report.docx");
String href = "ms-word:ofe|u|" + publicOrigin + path;The default signed-link validity is eight hours, configurable with davkit.signed-url.ttl. Allow enough time for the whole editing session, including LOCK refreshes and PUT/save-back. Expiry is checked on each request, so a document opened before expiry can fail to save afterwards.
Use path(subject, documentPath, Duration) to give one link a different validity period:
import java.time.Duration;
String path = signedUrls.path(userId, "documents/Report.docx",
Duration.ofMinutes(30));This leaves the configured default unchanged. Later two-argument calls still use davkit.signed-url.ttl.
Route Office requests
Deploy the application at the servlet container’s root context, with no context prefix such as /myapp. The WebDAV endpoint can still be /webdav. Office sends discovery requests to the origin’s /; an application under /myapp cannot receive those requests.
The starter warns at startup when the actual servlet context is non-root, including a container-assigned WAR context.
With Spring Security, give the DavKit servlet a separate chain without CSRF checks or form-login redirects; DavKit’s authentication filter protects its requests. Allow WebDAV methods in the host firewall. The public demo security configuration shows an explicit matcher for the non-MVC servlet. Check your reverse proxy preserves the public scheme, host and WebDAV methods.
The DavKit ready: startup summary is logged at INFO under com.tucanoo.davkit. It shows the endpoint, provider mounts, authentication, lock store and licence state. Licence failures are logged at ERROR: the application starts, but DavKit endpoints return 503 with the reason. The INFO setting above also shows WARN messages.
Use the API reference and demos
Download the 1.0.11 Javadoc archive, extract it and open index.html. It documents the supported public SPI and authentication helpers. The Spring Boot wrapper and demo and Grails wrapper and demo have public Apache 2.0 source.
Before deploying, exercise the complete path with a real Office file:
- Confirm root OPTIONS/PROPFIND discovery reaches the host without a browser-login redirect.
- Open the signed link in desktop Office, edit and save, then reload the document in your application.
- Check that save-back changes the stored bytes and ETag, that an unauthorised subject is refused, and that a stale storage version produces 412.
