r/JavaFX • • Sep 25 '26

Help Best way to store session tokens securely in Java/JavaFX (Windows DPAPI, macOS Keychain)?

Hey everyone,

I’m an experienced developer jumping into JavaFX for the first time. I'm building an app where I need to persist user session tokens securely without rolling my own plaintext file storage.

Ideally, I know that using the OS native credential stores (Windows DPAPI / Credential Manager, macOS Keychain, Linux Secret Service / Keyring). However, pure Java doesn't seem to have built-in APIs for these out of the box.

Is there an established, standard or library the community uses for this? Or does everyone just reach for JNA/JNI bindings like keytar / native wrappers?

Any recommendations or architectural patterns would be appreciated :D

10 Upvotes

7 comments sorted by

12

u/bichoFlyboy Sep 25 '26 • Heartwarming

JavaFx dev here. You're on the right track. There isn't really a single standard Java API that abstracts the native credential stores across Windows, macOS and Linux.

I'd model it behind a small "CredentialStore" abstraction and have platform-specific implementations backed by the OS facilities (Credential Manager/DPAPI, Keychain, Secret Service). JNA is a perfectly reasonable way of implementing those backends, and there are existing Java libraries/wrappers worth looking at before writing the bindings yourself.

One distinction I'd make, though: consider whether you actually need to persist the session/access token at all. Keeping short-lived access tokens in memory and only persisting a refresh token, if your UX requires sessions to survive application restarts, can considerably simplify the problem.

I wouldn't use "Preferences", a plaintext file, or invent an application-specific encryption scheme for this. If the secret has to survive restarts, let the OS credential store protect it.

So I'd start with:

"CredentialStore" > native OS credential store > token lifecycle on top of that.

That also keeps the authentication code independent of whichever native integration/library you eventually choose.

3

u/Siedlerchr Sep 25 '26

At JabRef we long searched for a good solution and have settled on java-keyring, https://github.com/javakeyring/java-keyring not perfect but works good enough.

2

u/jarrod_barkley Sep 25 '26

I believe the Foreign Function & Memory (FFM) API is the modern, simpler way to call native code, rather than JNA. But I’m no expert on that.

https://openjdk.org/jeps/454

3

u/theswissnightowl Sep 25 '26

I’d a similar problem in one of my apps and basically did what @bichoFlyboy suggested, just with a twist: I’m using FFM with Java 25 for Windows and macOS, on Linux I’m using `secret-tool` via sub process.

Works quite well

1

u/eliezerDeveloper Sep 25 '26

Use the native: java.util.prefs.Preferences;

1

u/eliezerDeveloper Sep 25 '26

Your data is persisted inside jvm. Good option natively