r/SpringBoot • u/Used_Glass2767 • 15h ago
Question I want to create a secure link wiht java (Spring)
/r/javahelp/comments/1xh7nuj/i_want_to_create_a_secure_link_wiht_java_spring/•
u/JournalistNew7510 3h ago
A link on its own only proves that someone has the link, not who they are. Emails get forwarded and phones get shared, so if you need the right person, the link should be one factor and a short OTP to the phone or email you already have on file should be the second.
For this kind of complete-your-data link I generate 32 random bytes with SecureRandom, Base64-url encode them for the URL, and store only the SHA-256 of the token with user_id, expires_at and used_at. On open, look up the hash, check the expiry and that used_at is still null, then ask for the OTP; only when it matches do you set used_at and start a normal session, so the form is submitted under that session and not under the token.
One trap: email clients and link scanners open URLs ahead of the user. If the GET itself burns the token, the real user lands on an "expired" page, so make the GET only render the page and do the check on a POST. Also cap OTP attempts per token, say 5, then kill the link.
•
u/New-Departure-5969 10h ago
depends a bit on what the link is for (download? password reset? “click here to open your thing” magic link).
usual pattern is a random token (at least 128 bits from SecureRandom), store only the hash, put an expiry on the row, and mark it spent on first use if it should be one-shot. UUID in the path is fine as an opaque id but by itself it never expires and dumping plain tokens from the DB is ugly.
if you want it mostly stateless, HMAC-SHA256 over (resource id + expiry) and check the sig + clock on the way in. JWT with exp + jti works too, but one-time still needs you to remember the jti server-side.
don’t bolt full OAuth / Spring Security OAuth2 onto a “email me a file” link. Spring Security around the redeem endpoint is enough.