You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jspwiki.apache.org by al...@apache.org on 2026/08/28 20:57:17 UTC

(jspwiki) 01/01: JSPWIKI-1288 see jira for details

This is an automated email from the ASF dual-hosted git repository.

spyhunter99 pushed a commit to branch bug/JSPWIKI-1288
in repository https://gitbox.apache.org/repos/asf/jspwiki.git

commit 0adf6eea4af129c6a3ab09e5d2acfce193e6f0ae
Author: Alex O'Ree <al...@apache.org>
AuthorDate: Fri Aug 28 16:56:49 2026 -0400

    JSPWIKI-1288 see jira for details
---
 .../apache/wiki/auth/PasswordResetTokenStore.java  | 171 +++++++++++++++++++++
 .../wiki/tasks/auth/SaveUserProfileTask.java       |  18 ++-
 .../src/main/resources/CoreResources.properties    |  11 ++
 .../src/main/resources/CoreResources_de.properties |   3 +
 .../src/main/resources/CoreResources_es.properties |   3 +
 .../src/main/resources/CoreResources_fi.properties |   3 +
 .../src/main/resources/CoreResources_fr.properties |   3 +
 .../src/main/resources/CoreResources_it.properties |   3 +
 .../src/main/resources/CoreResources_nl.properties |   3 +
 .../main/resources/CoreResources_pt_BR.properties  |   3 +
 .../src/main/resources/CoreResources_ru.properties |   3 +
 .../main/resources/CoreResources_zh_CN.properties  |   3 +
 .../main/resources/templates/default.properties    |   2 +
 .../main/resources/templates/default_de.properties |   2 +
 .../main/resources/templates/default_es.properties |   2 +
 .../main/resources/templates/default_fi.properties |   2 +
 .../main/resources/templates/default_fr.properties |   2 +
 .../main/resources/templates/default_it.properties |   2 +
 .../main/resources/templates/default_nl.properties |   2 +
 .../resources/templates/default_pt_BR.properties   |   2 +
 .../main/resources/templates/default_ru.properties |   2 +
 .../resources/templates/default_zh_CN.properties   |   2 +
 .../wiki/auth/PasswordResetTokenStoreTest.java     |  68 ++++++++
 jspwiki-war/src/main/webapp/LostPassword.jsp       | 122 +++++++++++----
 .../src/main/webapp/templates/210/LoginContent.jsp |   4 +
 .../main/webapp/templates/default/LoginContent.jsp |   6 +
 26 files changed, 411 insertions(+), 36 deletions(-)

diff --git a/jspwiki-main/src/main/java/org/apache/wiki/auth/PasswordResetTokenStore.java b/jspwiki-main/src/main/java/org/apache/wiki/auth/PasswordResetTokenStore.java
new file mode 100644
index 000000000..d9acf561d
--- /dev/null
+++ b/jspwiki-main/src/main/java/org/apache/wiki/auth/PasswordResetTokenStore.java
@@ -0,0 +1,171 @@
+/*
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+ */
+package org.apache.wiki.auth;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.LongSupplier;
+
+/**
+ * In-memory store of single-use, expiring password reset tokens, used by {@code LostPassword.jsp}.
+ * <p>
+ * A password reset is a two-step operation: a cryptographically random token is issued and mailed to the
+ * account owner ({@link #issue(String)}), and the stored credential is only changed when that token is
+ * presented back ({@link #redeem(String)}). Only a SHA-256 hash of the token is kept server-side, tokens
+ * expire after {@link #TOKEN_TTL_MS}, are removed on first use, and at most one token per account may be
+ * outstanding at a time (which also acts as a simple per-account throttle). The store itself is bounded
+ * to {@link #MAX_PENDING} entries as a global backstop.
+ * <p>
+ * Note: the store is per-JVM. On a multi-node deployment a token must be redeemed on the node that
+ * issued it.
+ *
+ * @since 2.12.4
+ */
+public final class PasswordResetTokenStore {
+
+    /** How long an issued token stays valid: 30 minutes. */
+    public static final long TOKEN_TTL_MS = 30L * 60L * 1000L;
+
+    /** Upper bound on simultaneously outstanding tokens. */
+    static final int MAX_PENDING = 1_000;
+
+    private static final SecureRandom RANDOM = new SecureRandom();
+    private static final PasswordResetTokenStore INSTANCE = new PasswordResetTokenStore( System::currentTimeMillis );
+
+    private final Map< String, PendingReset > pending = new ConcurrentHashMap<>();
+    private final LongSupplier clock;
+
+    /** Package-private for tests, which supply their own clock. */
+    PasswordResetTokenStore( final LongSupplier clock ) {
+        this.clock = clock;
+    }
+
+    /**
+     * Returns the shared store instance.
+     *
+     * @return the shared {@link PasswordResetTokenStore}.
+     */
+    public static PasswordResetTokenStore getInstance() {
+        return INSTANCE;
+    }
+
+    /**
+     * Issues a new reset token for the given login name. The raw token is returned exactly once, for
+     * inclusion in the reset e-mail; only its SHA-256 hash is retained. If a non-expired token is already
+     * outstanding for the account, or the store is full, no token is issued.
+     *
+     * @param loginName the login name the token is bound to.
+     * @return the raw token, or {@code null} if issuance was throttled.
+     */
+    public synchronized String issue( final String loginName ) {
+        final long now = clock.getAsLong();
+        purgeExpired( now );
+        if( loginName == null || loginName.isEmpty() || pending.size() >= MAX_PENDING ) {
+            return null;
+        }
+        for( final PendingReset reset : pending.values() ) {
+            if( reset.loginName.equals( loginName ) ) {
+                return null; // one outstanding token per account
+            }
+        }
+        final byte[] raw = new byte[ 32 ];
+        RANDOM.nextBytes( raw );
+        final String token = toHex( raw );
+        pending.put( toHex( sha256( token ) ), new PendingReset( loginName, now + TOKEN_TTL_MS ) );
+        return token;
+    }
+
+    /**
+     * Redeems a token: if it matches a stored, non-expired token hash, the token is removed (single use)
+     * and the login name it was issued for is returned. Comparison of the hashed values is constant-time.
+     *
+     * @param token the raw token as received from the user.
+     * @return the login name the token was bound to, or {@code null} if the token is unknown, already
+     *         used or expired.
+     */
+    public synchronized String redeem( final String token ) {
+        final long now = clock.getAsLong();
+        purgeExpired( now );
+        if( token == null || token.isEmpty() ) {
+            return null;
+        }
+        final byte[] candidate = sha256( token );
+        String matchedKey = null;
+        // Scan every entry and compare via MessageDigest.isEqual, so neither the position of a match nor
+        // a partial prefix match shows up as a timing difference.
+        for( final String key : pending.keySet() ) {
+            if( MessageDigest.isEqual( candidate, fromHex( key ) ) && matchedKey == null ) {
+                matchedKey = key;
+            }
+        }
+        if( matchedKey == null ) {
+            return null;
+        }
+        final PendingReset reset = pending.remove( matchedKey ); // remove-on-use: replay gets null
+        return reset != null && reset.expiry >= now ? reset.loginName : null;
+    }
+
+    private void purgeExpired( final long now ) {
+        for( final Iterator< PendingReset > it = pending.values().iterator(); it.hasNext(); ) {
+            if( it.next().expiry < now ) {
+                it.remove();
+            }
+        }
+    }
+
+    private static byte[] sha256( final String value ) {
+        try {
+            return MessageDigest.getInstance( "SHA-256" ).digest( value.getBytes( StandardCharsets.UTF_8 ) );
+        } catch( final NoSuchAlgorithmException e ) {
+            throw new IllegalStateException( "JVM without SHA-256 support", e );
+        }
+    }
+
+    private static String toHex( final byte[] bytes ) {
+        final StringBuilder sb = new StringBuilder( bytes.length * 2 );
+        for( final byte b : bytes ) {
+            sb.append( Character.forDigit( ( b >> 4 ) & 0x0F, 16 ) ).append( Character.forDigit( b & 0x0F, 16 ) );
+        }
+        return sb.toString();
+    }
+
+    private static byte[] fromHex( final String hex ) {
+        final byte[] bytes = new byte[ hex.length() / 2 ];
+        for( int i = 0; i < bytes.length; i++ ) {
+            bytes[ i ] = ( byte )( ( Character.digit( hex.charAt( 2 * i ), 16 ) << 4 ) + Character.digit( hex.charAt( 2 * i + 1 ), 16 ) );
+        }
+        return bytes;
+    }
+
+    private static final class PendingReset {
+        final String loginName;
+        final long expiry;
+
+        PendingReset( final String loginName, final long expiry ) {
+            this.loginName = loginName;
+            this.expiry = expiry;
+        }
+    }
+
+}
diff --git a/jspwiki-main/src/main/java/org/apache/wiki/tasks/auth/SaveUserProfileTask.java b/jspwiki-main/src/main/java/org/apache/wiki/tasks/auth/SaveUserProfileTask.java
index 6bf94833f..3acffe1b0 100644
--- a/jspwiki-main/src/main/java/org/apache/wiki/tasks/auth/SaveUserProfileTask.java
+++ b/jspwiki-main/src/main/java/org/apache/wiki/tasks/auth/SaveUserProfileTask.java
@@ -27,8 +27,8 @@ import org.apache.wiki.auth.UserManager;
 import org.apache.wiki.auth.user.UserProfile;
 import org.apache.wiki.i18n.InternationalizationManager;
 import org.apache.wiki.tasks.TasksManager;
-import org.apache.wiki.util.HttpUtil;
 import org.apache.wiki.util.MailUtil;
+import org.apache.wiki.util.TextUtil;
 import org.apache.wiki.workflow.Outcome;
 import org.apache.wiki.workflow.Task;
 import org.apache.wiki.workflow.WorkflowManager;
@@ -78,9 +78,19 @@ public class SaveUserProfileTask extends Task {
                 final String subject = i18n.get( InternationalizationManager.DEF_TEMPLATE, m_loc,
                                                  "notification.createUserProfile.accept.subject", app );
 
-                final String loginUrl = context.getEngine().getURL( ContextEnum.WIKI_LOGIN.getRequestContext(), null, null );
-
-                final String absoluteLoginUrl = HttpUtil.getAbsoluteUrl(context.getHttpRequest(), loginUrl);
+                String loginUrl = context.getEngine().getURL( ContextEnum.WIKI_LOGIN.getRequestContext(), null, null );
+
+                // Build the emailed link from configuration (jspwiki.baseURL), never from request
+                // headers (Host / X-Forwarded-*), which are attacker-controlled.
+                String base = TextUtil.getStringProperty( context.getEngine().getWikiProperties(), "jspwiki.baseURL", "" ).trim();
+                while( base.endsWith( "/" ) ) {
+                    base = base.substring( 0, base.length() - 1 );
+                }
+                final String contextPath = context.getEngine().getBaseURL();
+                if( !base.isEmpty() && !contextPath.isEmpty() && loginUrl.startsWith( contextPath ) ) {
+                    loginUrl = loginUrl.substring( contextPath.length() );
+                }
+                final String absoluteLoginUrl = base + loginUrl;
 
                 final String content = i18n.get( InternationalizationManager.DEF_TEMPLATE, m_loc,
                                                  "notification.createUserProfile.accept.content", app,
diff --git a/jspwiki-main/src/main/resources/CoreResources.properties b/jspwiki-main/src/main/resources/CoreResources.properties
index dc2b581c2..5eea91728 100644
--- a/jspwiki-main/src/main/resources/CoreResources.properties
+++ b/jspwiki-main/src/main/resources/CoreResources.properties
@@ -91,6 +91,17 @@ login.error.noaccess=It seems you don't have access to that. Sorry.
 lostpwd.newpassword.email=As requested, your new password for login "{0}" is "{1}" \
                     \n\nYou may log in at {2}.\n\n-- {3}
 lostpwd.newpassword.subject=New password for {0}
+
+# 0 = login name, 1 = reset token, 2 = URL, 3 = Application name (as signature)
+# This is text, not HTML.
+lostpwd.token.email=A password reset was requested for the login "{0}" on {3}.\
+                    \n\nYour single-use reset code is: {1}\
+                    \n\nEnter it in the password reset form at {2} within 30 minutes to receive \
+                    a new password by email. If you did not request this, you can safely ignore \
+                    this message: your password has not been changed.\n\n-- {3}
+lostpwd.token.subject=Password reset code for {0}
+lostpwd.tokenmailed=If the given address matches a known account, a single-use reset code has been \
+                    emailed to it. Enter the code below to complete the reset.
 lostpwd.nouser=No user or email "{0}" was found.
 lostpwd.nomail=Internal error: couldn't send the email!  Contact the site administrator, please.
 lostpwd.emailed=A new password has been emailed to the requested account.
diff --git a/jspwiki-main/src/main/resources/CoreResources_de.properties b/jspwiki-main/src/main/resources/CoreResources_de.properties
index c0ea9d361..646ab77db 100644
--- a/jspwiki-main/src/main/resources/CoreResources_de.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_de.properties
@@ -255,3 +255,6 @@ pwdcheck.tooshort=Passwort zu kurz, min={0}
 pwdcheck.toolong=Passwort zu lang, max={0}
 security.error.passwordReuseError=Dieses Passwort wurde bei den letzten {0} Passwort\u00e4nderungen verwendet und kann nicht wiederverwendet werden.
 pwdcheck.minchanged=Nicht gen\u00fcgend Zeichen ge\u00e4ndert, min={0}
+lostpwd.token.email=F\u00fcr den Login \u201e{0}\u201c wurde am {3} eine Passwortzur\u00fccksetzung angefordert.\n\nIhr einmalig verwendbarer Reset-Code lautet: {1}\n\nGeben Sie diesen innerhalb von 30 Minuten im Formular zur Passwortzur\u00fccksetzung unter {2} ein, um ein neues Passwort per E-Mail zu erhalten. Falls Sie dies nicht angefordert haben, k\u00f6nnen Sie diese Nachricht ignorieren: Ihr Passwort wurde nicht ge\u00e4ndert.\n\n-- {3}
+lostpwd.token.subject=Passwort-Reset-Code f\u00fcr {0}
+lostpwd.tokenmailed=Wenn die angegebene Adresse mit einem bekannten Konto \u00fcbereinstimmt, wurde ein einmalig verwendbarer Reset-Code per E-Mail an diese Adresse gesendet. Geben Sie den Code unten ein, um den Reset abzuschlie\u00dfen.
diff --git a/jspwiki-main/src/main/resources/CoreResources_es.properties b/jspwiki-main/src/main/resources/CoreResources_es.properties
index 9328a620d..3bfe5ecaf 100644
--- a/jspwiki-main/src/main/resources/CoreResources_es.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_es.properties
@@ -222,3 +222,6 @@ pwdcheck.tooshort=Contrase\u00f1a demasiado corta, min={0}
 pwdcheck.toolong=Contrase\u00f1a demasiado larga, m\u00e1ximo={0}
 security.error.passwordReuseError=Esta contrase\u00f1a se ha utilizado en los \u00faltimos {0} cambios de contrase\u00f1a y no se puede reutilizar.
 pwdcheck.minchanged=No se cambiaron suficientes caracteres, min={0}
+lostpwd.token.email=Se solicit\u00f3 un restablecimiento de contrase\u00f1a para el usuario "{0}" el d\u00eda {3}.\n\nSu c\u00f3digo de restablecimiento de un solo uso es: {1}\n\nIntrod\u00fazcalo en el formulario de restablecimiento de contrase\u00f1a en {2} en un plazo de 30 minutos para recibir una nueva contrase\u00f1a por correo electr\u00f3nico. Si no solicit\u00f3 este cambio, puede ignorar este mensaje: su contrase\u00f1a no ha sido modificada.\n\n-- {3}
+lostpwd.token.subject=C\u00f3digo de restablecimiento de contrase\u00f1a para {0}
+lostpwd.tokenmailed=Si la direcci\u00f3n proporcionada coincide con una cuenta conocida, se le ha enviado un c\u00f3digo de restablecimiento de un solo uso por correo electr\u00f3nico. Ingrese el c\u00f3digo a continuaci\u00f3n para completar el restablecimiento.
diff --git a/jspwiki-main/src/main/resources/CoreResources_fi.properties b/jspwiki-main/src/main/resources/CoreResources_fi.properties
index 341c54710..b69ce4ffd 100644
--- a/jspwiki-main/src/main/resources/CoreResources_fi.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_fi.properties
@@ -206,3 +206,6 @@ pwdcheck.tooshort=Salasana liian lyhyt, min={0}
 pwdcheck.toolong=Salasana liian pitk\u00e4, max={0}
 security.error.passwordReuseError=T\u00e4t\u00e4 salasanaa on k\u00e4ytetty viimeisimpien {0} salasanan vaihdon yhteydess\u00e4, eik\u00e4 sit\u00e4 voi k\u00e4ytt\u00e4\u00e4 uudelleen.
 pwdcheck.minchanged=Pas assez de caract\u00e8res modifi\u00e9s, min={0}
+lostpwd.token.email=Salasanan palautusta pyydettiin kirjautumistunnukselle "{0}" p\u00e4iv\u00e4m\u00e4\u00e4r\u00e4n\u00e4 {3}.\n\nKertak\u00e4ytt\u00f6inen palautuskoodisi on: {1}\n\nSy\u00f6t\u00e4 se salasanan palautuslomakkeeseen osoitteessa {2} 30 minuutin kuluessa saadaksesi uuden salasanan s\u00e4hk\u00f6postitse. Jos et pyyt\u00e4nyt t\u00e4t\u00e4, voit turvallisesti j\u00e4tt\u00e4\u00e4 t\u00e4m\u00e4n viestin huomiotta: salasanaasi ei ole vaihdettu.\n\n-- {3}
+lostpwd.token.subject=Salasanan palautuskoodi kohteelle {0}
+lostpwd.tokenmailed=Jos annettu osoite vastaa tunnettua tili\u00e4, kertak\u00e4ytt\u00f6inen nollauskoodi on l\u00e4hetetty siihen s\u00e4hk\u00f6postitse. Sy\u00f6t\u00e4 alla oleva koodi nollauksen suorittamiseksi loppuun.
diff --git a/jspwiki-main/src/main/resources/CoreResources_fr.properties b/jspwiki-main/src/main/resources/CoreResources_fr.properties
index 8dcad9d06..29030be4a 100644
--- a/jspwiki-main/src/main/resources/CoreResources_fr.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_fr.properties
@@ -256,3 +256,6 @@ pwdcheck.tooshort=Mot de passe trop court, min={0}
 pwdcheck.toolong=Mot de passe trop long, max={0}
 security.error.passwordReuseError=Ce mot de passe a \u00e9t\u00e9 utilis\u00e9 lors des {0} derni\u00e8res modifications de mot de passe et ne peut pas \u00eatre r\u00e9utilis\u00e9.
 pwdcheck.minchanged=Pas assez de caract\u00e8res modifi\u00e9s, min={0}
+lostpwd.token.email=Une r\u00e9initialisation du mot de passe a \u00e9t\u00e9 demand\u00e9e pour l'identifiant \u00ab\u00a0{0}\u00a0\u00bb sur {3}.\n\nVotre code de r\u00e9initialisation \u00e0 usage unique est\u00a0: {1}\n\nSaisissez-le dans le formulaire de r\u00e9initialisation de mot de passe \u00e0 l'adresse {2} dans les 30\u00a0minutes pour recevoir un nouveau mot de passe par courriel. Si vous n'avez pas fait cette demande, vous pouvez ignorer ce message\u00a0: votre mot de passe  [...]
+lostpwd.token.subject=Code de r\u00e9initialisation du mot de passe pour {0}
+lostpwd.tokenmailed=Si l'adresse indiqu\u00e9e correspond \u00e0 un compte connu, un code de r\u00e9initialisation \u00e0 usage unique lui a \u00e9t\u00e9 envoy\u00e9 par courriel. Saisissez ce code ci-dessous pour terminer la r\u00e9initialisation.
diff --git a/jspwiki-main/src/main/resources/CoreResources_it.properties b/jspwiki-main/src/main/resources/CoreResources_it.properties
index 9b8fdddb3..7790b3c9a 100644
--- a/jspwiki-main/src/main/resources/CoreResources_it.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_it.properties
@@ -243,3 +243,6 @@ pwdcheck.tooshort=Password troppo corta, min={0}
 pwdcheck.toolong=Password troppo lunga, max={0}
 security.error.passwordReuseError=Questa password \u00e8 stata utilizzata nelle ultime {0} modifiche della password e non pu\u00f2 essere riutilizzata.
 pwdcheck.minchanged=Non sono stati modificati abbastanza caratteri, min={0}
+lostpwd.token.email=\u00c8 stata richiesta la reimpostazione della password per l'account "{0}" su {3}.\n\nIl tuo codice di reimpostazione monouso \u00e8: {1}\n\nInseriscilo nel modulo di reimpostazione della password su {2} entro 30 minuti per ricevere una nuova password via email. Se non hai richiesto la reimpostazione della password, puoi tranquillamente ignorare questo messaggio: la tua password non \u00e8 stata modificata.\n\n-- {3}
+lostpwd.token.subject=Codice di reimpostazione della password per {0}
+lostpwd.tokenmailed=Se l'indirizzo fornito corrisponde a un account noto, \u00e8 stato inviato un codice di ripristino monouso tramite e-mail. Inserisci il codice qui sotto per completare il ripristino.
diff --git a/jspwiki-main/src/main/resources/CoreResources_nl.properties b/jspwiki-main/src/main/resources/CoreResources_nl.properties
index 7ad946793..3bfe27ab2 100644
--- a/jspwiki-main/src/main/resources/CoreResources_nl.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_nl.properties
@@ -241,3 +241,6 @@ pwdcheck.tooshort=Wachtwoord te kort, min={0}
 pwdcheck.toolong=Wachtwoord te lang, max={0}
 pwdcheck.minchanged=Er zijn niet genoeg tekens gewijzigd, min={0}
 security.error.passwordReuseError=Dit wachtwoord is gebruikt binnen de laatste {0} wachtwoordwijzigingen en kan niet opnieuw worden gebruikt.
+lostpwd.token.email=Er is een wachtwoordherstel aangevraagd voor de login "{0}" op {3}.\n\nUw eenmalige herstelcode is: {1}\n\nVoer deze code binnen 30 minuten in op het wachtwoordherstelformulier op {2} om een \u200b\u200bnieuw wachtwoord per e-mail te ontvangen. Als u dit niet hebt aangevraagd, kunt u dit bericht negeren: uw wachtwoord is niet gewijzigd.\n\n-- {3}
+lostpwd.token.subject=Wachtwoordherstelcode voor {0}
+lostpwd.tokenmailed=Als het opgegeven e-mailadres overeenkomt met een bekend account, is er een eenmalige resetcode naar dat account gemaild. Voer de code hieronder in om de reset te voltooien.
diff --git a/jspwiki-main/src/main/resources/CoreResources_pt_BR.properties b/jspwiki-main/src/main/resources/CoreResources_pt_BR.properties
index d45738eb4..dd477b0b9 100644
--- a/jspwiki-main/src/main/resources/CoreResources_pt_BR.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_pt_BR.properties
@@ -244,3 +244,6 @@ pwdcheck.tooshort=Senha muito curta, min={0}
 pwdcheck.toolong=Senha muito longa, m\u00e1ximo={0}
 security.error.passwordReuseError=Esta senha foi usada nas \u00faltimas {0} altera\u00e7\u00f5es de senha e n\u00e3o pode ser reutilizada.
 pwdcheck.minchanged=N\u00e3o foram alterados caracteres suficientes, min={0}
+lostpwd.token.email=Foi solicitada uma redefini\u00e7\u00e3o da palavra-passe para o login "{0}" em {3}.\n\nO seu c\u00f3digo de redefini\u00e7\u00e3o de utiliza\u00e7\u00e3o \u00fanica \u00e9: {1}\n\nIntroduza-o no formul\u00e1rio de redefini\u00e7\u00e3o de palavra-passe em {2} no prazo de 30 minutos para receber uma nova palavra-passe por e-mail. Se n\u00e3o o solicitou, pode ignorar esta mensagem: a sua palavra-passe n\u00e3o foi alterada.\n\n-- {3}
+lostpwd.token.subject=C\u00f3digo de redefini\u00e7\u00e3o da palavra-passe para {0}
+lostpwd.tokenmailed=Se o endere\u00e7o fornecido corresponder a uma conta conhecida, foi enviado um c\u00f3digo de reposi\u00e7\u00e3o de utiliza\u00e7\u00e3o \u00fanica para esse endere\u00e7o de e-mail. Introduza o c\u00f3digo abaixo para concluir a reposi\u00e7\u00e3o.
diff --git a/jspwiki-main/src/main/resources/CoreResources_ru.properties b/jspwiki-main/src/main/resources/CoreResources_ru.properties
index 0aae6cd86..a2412a07f 100644
--- a/jspwiki-main/src/main/resources/CoreResources_ru.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_ru.properties
@@ -249,3 +249,6 @@ pwdcheck.tooshort=\u041f\u0430\u0440\u043e\u043b\u044c \u0441\u043b\u0438\u0448\
 pwdcheck.toolong=\u041f\u0430\u0440\u043e\u043b\u044c \u0441\u043b\u0438\u0448\u043a\u043e\u043c \u0434\u043b\u0438\u043d\u043d\u044b\u0439, \u043c\u0430\u043a\u0441.={0}
 security.error.passwordReuseError=\u042d\u0442\u043e\u0442 \u043f\u0430\u0440\u043e\u043b\u044c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043b\u0441\u044f \u043f\u0440\u0438 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0445 {0} \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f\u0445 \u043f\u0430\u0440\u043e\u043b\u044f \u0438 \u043d\u0435 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u043 [...]
 pwdcheck.minchanged=\u041d\u0435\u0434\u043e\u0441\u0442\u0430\u0442\u043e\u0447\u043d\u043e \u0441\u0438\u043c\u0432\u043e\u043b\u043e\u0432 \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u043e, \u043c\u0438\u043d={0}
+lostpwd.token.email=\u0417\u0430\u043f\u0440\u043e\u0441 \u043d\u0430 \u0441\u0431\u0440\u043e\u0441 \u043f\u0430\u0440\u043e\u043b\u044f \u0431\u044b\u043b \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d \u0434\u043b\u044f \u0432\u0445\u043e\u0434\u0430 \u0432 \u0441\u0438\u0441\u0442\u0435\u043c\u0443 "{0}" \u043d\u0430 {3}.\n\n\u0412\u0430\u0448 \u043e\u0434\u043d\u043e\u0440\u0430\u0437\u043e\u0432\u044b\u0439 \u043a\u043e\u0434 \u0441\u0431\u0440\u043e\u0441\u0430: {1}\n\n\u0 [...]
+lostpwd.token.subject=\u041a\u043e\u0434 \u0441\u0431\u0440\u043e\u0441\u0430 \u043f\u0430\u0440\u043e\u043b\u044f \u0434\u043b\u044f {0}
+lostpwd.tokenmailed=\u0415\u0441\u043b\u0438 \u0443\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u0439 \u0430\u0434\u0440\u0435\u0441 \u0441\u043e\u0432\u043f\u0430\u0434\u0430\u0435\u0442 \u0441 \u0438\u0437\u0432\u0435\u0441\u0442\u043d\u044b\u043c \u0430\u043a\u043a\u0430\u0443\u043d\u0442\u043e\u043c, \u043d\u0430 \u043d\u0435\u0433\u043e \u0431\u044b\u043b \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d \u043e\u0434\u043d\u043e\u0440\u0430\u0437\u043e\u0432\u044b\u0439 \u043a\u0 [...]
diff --git a/jspwiki-main/src/main/resources/CoreResources_zh_CN.properties b/jspwiki-main/src/main/resources/CoreResources_zh_CN.properties
index a55d1497e..6a0aac256 100644
--- a/jspwiki-main/src/main/resources/CoreResources_zh_CN.properties
+++ b/jspwiki-main/src/main/resources/CoreResources_zh_CN.properties
@@ -248,3 +248,6 @@ pwdcheck.tooshort=\u5bc6\u7801\u8fc7\u77ed\uff0c\u6700\u5c0f\u503c\u4e3a{0}
 pwdcheck.toolong=\u5bc6\u7801\u8fc7\u957f\uff0c\u6700\u5927\u9650\u5236\u4e3a{0}
 security.error.passwordReuseError=\u6b64\u5bc6\u7801\u5df2\u5728\u6700\u8fd1 {0} \u6b21\u5bc6\u7801\u66f4\u6539\u4e2d\u4f7f\u7528\u8fc7\uff0c\u4e0d\u80fd\u518d\u6b21\u4f7f\u7528\u3002
 pwdcheck.minchanged=\u66f4\u6539\u7684\u5b57\u7b26\u6570\u4e0d\u8db3\uff0c\u6700\u5c0f\u503c\u4e3a0\u3002
+lostpwd.token.email=\u7528\u6237\u201c{0}\u201d\u4e8e{3}\u7533\u8bf7\u4e86\u5bc6\u7801\u91cd\u7f6e\u3002\n\n\u60a8\u7684\u4e00\u6b21\u6027\u91cd\u7f6e\u7801\u4e3a\uff1a{1}\n\n\u8bf7\u572830\u5206\u949f\u5185\u5c06\u6b64\u91cd\u7f6e\u7801\u8f93\u5165\u5230{2}\u7684\u5bc6\u7801\u91cd\u7f6e\u8868\u5355\u4e2d\uff0c\u5373\u53ef\u901a\u8fc7\u7535\u5b50\u90ae\u4ef6\u6536\u5230\u65b0\u5bc6\u7801\u3002\u5982\u679c\u60a8\u672a\u7533\u8bf7\u6b64\u91cd\u7f6e\uff0c\u5219\u53ef\u4ee5\u5ffd\u7565\u6b64 [...]
+lostpwd.token.subject={0} \u7684\u5bc6\u7801\u91cd\u7f6e\u7801
+lostpwd.tokenmailed=\u5982\u679c\u63d0\u4f9b\u7684\u5730\u5740\u4e0e\u5df2\u77e5\u5e10\u6237\u5339\u914d\uff0c\u7cfb\u7edf\u5df2\u5411\u8be5\u5e10\u6237\u53d1\u9001\u4e86\u4e00\u6b21\u6027\u91cd\u7f6e\u4ee3\u7801\u3002\u8bf7\u8f93\u5165\u4ee5\u4e0b\u4ee3\u7801\u5b8c\u6210\u91cd\u7f6e\u3002
diff --git a/jspwiki-main/src/main/resources/templates/default.properties b/jspwiki-main/src/main/resources/templates/default.properties
index 5d682a693..1fda03daf 100644
--- a/jspwiki-main/src/main/resources/templates/default.properties
+++ b/jspwiki-main/src/main/resources/templates/default.properties
@@ -279,6 +279,8 @@ login.lostpw.heading=Reset Password
 login.lostpw.help=Lost or forgot your password?  Enter the email address you used to register with here.
 login.lostpw.name=Account email
 login.lostpw.submit=Reset password !
+login.lostpw.token=Reset code
+login.lostpw.token.help=Already received a reset code by email? Enter it here to complete the reset.
 login.lostpw.reset.clickhere=Click here
 login.lostpw.reset.login={0} to log in once you retrieve your new password.
 
diff --git a/jspwiki-main/src/main/resources/templates/default_de.properties b/jspwiki-main/src/main/resources/templates/default_de.properties
index c08b09d94..0dba287e0 100644
--- a/jspwiki-main/src/main/resources/templates/default_de.properties
+++ b/jspwiki-main/src/main/resources/templates/default_de.properties
@@ -750,3 +750,5 @@ attach.add.maxUpload=Maximale Uploadgr\u00f6\u00dfe:
 notification.auditlog.subject=[0] Pr\u00fcfalarm
 notification.auditlog.content=Klasse: [0]\nEreignisname: [1]\nTypbeschreibung: [2]\nWann: [3]\nEreignisdetails: [4]\nHeader und Verbindungsdetails: [5]
 fav.greet.lastLogin=Letzter Login um {0} von {1}
+login.lostpw.token=Code zur\u00fccksetzen
+login.lostpw.token.help=Sie haben bereits einen Reset-Code per E-Mail erhalten? Geben Sie ihn hier ein, um den Reset abzuschlie\u00dfen.
diff --git a/jspwiki-main/src/main/resources/templates/default_es.properties b/jspwiki-main/src/main/resources/templates/default_es.properties
index 96d2e19e8..e5c09073a 100644
--- a/jspwiki-main/src/main/resources/templates/default_es.properties
+++ b/jspwiki-main/src/main/resources/templates/default_es.properties
@@ -709,3 +709,5 @@ javascript.preview.zone = Zona de previsualizaci\u00f3n
 notification.auditlog.subject=[0] Alerta de auditor\u00eda
 notification.auditlog.content=Clase: [0]\nNombre del evento: [1]\nDescripci\u00f3n del tipo: [2]\n\nCu\u00e1ndo: [3]\nDetalles del evento: [4]\nEncabezados y detalles de conexi\u00f3n: [5]
 fav.greet.lastLogin=\u00daltimo inicio de sesi\u00f3n a las {0} desde {1}
+login.lostpw.token=Restablecer c\u00f3digo
+login.lostpw.token.help=\u00bfYa recibiste un c\u00f3digo de reinicio por correo electr\u00f3nico? Introd\u00facelo aqu\u00ed para completar el reinicio.
diff --git a/jspwiki-main/src/main/resources/templates/default_fi.properties b/jspwiki-main/src/main/resources/templates/default_fi.properties
index 991425a0b..c58ecef2a 100644
--- a/jspwiki-main/src/main/resources/templates/default_fi.properties
+++ b/jspwiki-main/src/main/resources/templates/default_fi.properties
@@ -716,3 +716,5 @@ fav.productstatus.updateAvailable=Ohjelmistop\u00e4ivitys on saatavilla.
 fav.productstatus.unknown=Tuotep\u00e4ivitysten tarkistaminen ep\u00e4onnistui.
 fav.productstatus.updateToDate=Ohjelmisto on ajan tasalla.
 fav.greet.lastLogin=Viimeisin kirjautuminen klo {0} osoitteesta {1}
+login.lostpw.token=Nollaa koodi
+login.lostpw.token.help=Saitko jo nollauskoodin s\u00e4hk\u00f6postitse? Sy\u00f6t\u00e4 se t\u00e4h\u00e4n viimeistell\u00e4ksesi nollauksen.
diff --git a/jspwiki-main/src/main/resources/templates/default_fr.properties b/jspwiki-main/src/main/resources/templates/default_fr.properties
index aa21f9106..9d5aa94cd 100644
--- a/jspwiki-main/src/main/resources/templates/default_fr.properties
+++ b/jspwiki-main/src/main/resources/templates/default_fr.properties
@@ -756,3 +756,5 @@ fav.productstatus.updateAvailable=Une mise \u00e0 jour logicielle est disponible
 fav.productstatus.unknown=Impossible de v\u00e9rifier les mises \u00e0 jour du produit.
 fav.productstatus.updateToDate=Le logiciel est \u00e0 jour.
 fav.greet.lastLogin=Derni\u00e8re connexion \u00e0 {0} depuis {1}
+login.lostpw.token=R\u00e9initialiser le code
+login.lostpw.token.help=Vous avez d\u00e9j\u00e0 re\u00e7u un code de r\u00e9initialisation par courriel\u00a0? Saisissez-le ici pour terminer la r\u00e9initialisation.
diff --git a/jspwiki-main/src/main/resources/templates/default_it.properties b/jspwiki-main/src/main/resources/templates/default_it.properties
index 3d83350d9..60f766af3 100644
--- a/jspwiki-main/src/main/resources/templates/default_it.properties
+++ b/jspwiki-main/src/main/resources/templates/default_it.properties
@@ -746,3 +746,5 @@ fav.productstatus.updateAvailable=\u00c8 disponibile un aggiornamento software.
 fav.productstatus.unknown=Impossibile verificare la presenza di aggiornamenti del prodotto.
 fav.productstatus.updateToDate=Il software \u00e8 aggiornato.
 fav.greet.lastLogin=Ultimo accesso alle {0} da {1}
+login.lostpw.token=Reimposta il codice
+login.lostpw.token.help=Hai gi\u00e0 ricevuto un codice di ripristino via email? Inseriscilo qui per completare il ripristino.
diff --git a/jspwiki-main/src/main/resources/templates/default_nl.properties b/jspwiki-main/src/main/resources/templates/default_nl.properties
index 212d3b719..a28f2c3cc 100644
--- a/jspwiki-main/src/main/resources/templates/default_nl.properties
+++ b/jspwiki-main/src/main/resources/templates/default_nl.properties
@@ -745,3 +745,5 @@ fav.productstatus.updateAvailable=Er is een software-update beschikbaar.
 fav.productstatus.unknown=Er kan niet worden gecontroleerd op productupdates.
 fav.productstatus.updateToDate=De software is up-to-date.
 fav.greet.lastLogin=Laatste login om {0} vanaf {1}
+login.lostpw.token=Code opnieuw instellen
+login.lostpw.token.help=Heeft u al een resetcode per e-mail ontvangen? Voer deze hier in om de reset te voltooien.
diff --git a/jspwiki-main/src/main/resources/templates/default_pt_BR.properties b/jspwiki-main/src/main/resources/templates/default_pt_BR.properties
index 14efe764f..c7ecc16d9 100644
--- a/jspwiki-main/src/main/resources/templates/default_pt_BR.properties
+++ b/jspwiki-main/src/main/resources/templates/default_pt_BR.properties
@@ -691,3 +691,5 @@ fav.productstatus.updateAvailable=Uma atualiza\u00e7\u00e3o de software est\u00e
 fav.productstatus.unknown=N\u00e3o foi poss\u00edvel verificar se h\u00e1 atualiza\u00e7\u00f5es do produto.
 fav.productstatus.updateToDate=O software est\u00e1 atualizado.
 fav.greet.lastLogin=\u00daltimo login em {0} de {1}
+login.lostpw.token=Redefinir c\u00f3digo
+login.lostpw.token.help=J\u00e1 recebeu um c\u00f3digo de reposi\u00e7\u00e3o por e-mail? Insira-o aqui para concluir a reposi\u00e7\u00e3o.
diff --git a/jspwiki-main/src/main/resources/templates/default_ru.properties b/jspwiki-main/src/main/resources/templates/default_ru.properties
index 7b85c6faa..8c8477f3f 100644
--- a/jspwiki-main/src/main/resources/templates/default_ru.properties
+++ b/jspwiki-main/src/main/resources/templates/default_ru.properties
@@ -746,3 +746,5 @@ fav.productstatus.unknown=\u041d\u0435 \u0443\u0434\u0430\u043b\u043e\u0441\u044
 fav.productstatus.updateToDate=\u041f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u043d\u043e\u0435 \u043e\u0431\u0435\u0441\u043f\u0435\u0447\u0435\u043d\u0438\u0435 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u043e.
 fav.greet.lastLogin=\u041f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0439 \u0432\u0445\u043e\u0434 \u0432 {0} \u0438\u0437 {1}
 javascript.dialog.permission=\u0420\u0430\u0437\u0440\u0435\u0448\u0435\u043d\u0438\u0435 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u044b
+login.lostpw.token=\u0421\u0431\u0440\u043e\u0441\u0438\u0442\u044c \u043a\u043e\u0434
+login.lostpw.token.help=\u0423\u0436\u0435 \u043f\u043e\u043b\u0443\u0447\u0438\u043b\u0438 \u043a\u043e\u0434 \u0441\u0431\u0440\u043e\u0441\u0430 \u043f\u043e \u044d\u043b\u0435\u043a\u0442\u0440\u043e\u043d\u043d\u043e\u0439 \u043f\u043e\u0447\u0442\u0435? \u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0435\u0433\u043e \u0437\u0434\u0435\u0441\u044c, \u0447\u0442\u043e\u0431\u044b \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044c \u0441\u0431\u0440\u043e\u0441.
diff --git a/jspwiki-main/src/main/resources/templates/default_zh_CN.properties b/jspwiki-main/src/main/resources/templates/default_zh_CN.properties
index 14c5bded8..9565f3f8b 100644
--- a/jspwiki-main/src/main/resources/templates/default_zh_CN.properties
+++ b/jspwiki-main/src/main/resources/templates/default_zh_CN.properties
@@ -731,3 +731,5 @@ fav.productstatus.updateAvailable=\u8f6f\u4ef6\u66f4\u65b0\u53ef\u7528\u3002
 fav.productstatus.unknown=\u65e0\u6cd5\u68c0\u67e5\u4ea7\u54c1\u66f4\u65b0\u3002
 fav.productstatus.updateToDate=\u8f6f\u4ef6\u5df2\u66f4\u65b0\u81f3\u6700\u65b0\u7248\u672c\u3002
 fav.greet.lastLogin=\u4e0a\u6b21\u767b\u5f55\u65f6\u95f4\u4e3a {0}\uff0c\u6765\u81ea {1}
+login.lostpw.token=\u91cd\u7f6e\u5bc6\u7801
+login.lostpw.token.help=\u5df2\u7ecf\u901a\u8fc7\u7535\u5b50\u90ae\u4ef6\u6536\u5230\u91cd\u7f6e\u7801\u4e86\u5417\uff1f\u8bf7\u5728\u6b64\u5904\u8f93\u5165\u4ee5\u5b8c\u6210\u91cd\u7f6e\u3002
diff --git a/jspwiki-main/src/test/java/org/apache/wiki/auth/PasswordResetTokenStoreTest.java b/jspwiki-main/src/test/java/org/apache/wiki/auth/PasswordResetTokenStoreTest.java
new file mode 100644
index 000000000..06ed47cb3
--- /dev/null
+++ b/jspwiki-main/src/test/java/org/apache/wiki/auth/PasswordResetTokenStoreTest.java
@@ -0,0 +1,68 @@
+/*
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+ */
+package org.apache.wiki.auth;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class PasswordResetTokenStoreTest {
+
+    long now = 1_000_000L;
+    PasswordResetTokenStore store = new PasswordResetTokenStore( () -> now );
+
+    @Test
+    public void tokenRedeemsOnceOnly() {
+        final String token = store.issue( "alice" );
+        Assertions.assertNotNull( token, "token should be issued" );
+        Assertions.assertEquals( "alice", store.redeem( token ), "first redemption returns the login name" );
+        Assertions.assertNull( store.redeem( token ), "replaying a redeemed token must fail" );
+    }
+
+    @Test
+    public void tokenExpires() {
+        final String token = store.issue( "alice" );
+        now += PasswordResetTokenStore.TOKEN_TTL_MS + 1;
+        Assertions.assertNull( store.redeem( token ), "expired token must not redeem" );
+    }
+
+    @Test
+    public void unknownOrEmptyTokenRejected() {
+        store.issue( "alice" );
+        Assertions.assertNull( store.redeem( "deadbeef" ) );
+        Assertions.assertNull( store.redeem( "" ) );
+        Assertions.assertNull( store.redeem( null ) );
+    }
+
+    @Test
+    public void singleOutstandingTokenPerAccount() {
+        Assertions.assertNotNull( store.issue( "alice" ), "first issue succeeds" );
+        Assertions.assertNull( store.issue( "alice" ), "second issue while one is outstanding is throttled" );
+        now += PasswordResetTokenStore.TOKEN_TTL_MS + 1;
+        Assertions.assertNotNull( store.issue( "alice" ), "issue succeeds again after expiry" );
+    }
+
+    @Test
+    public void tokensAreBoundToTheirAccount() {
+        final String tokenA = store.issue( "alice" );
+        final String tokenB = store.issue( "bob" );
+        Assertions.assertEquals( "bob", store.redeem( tokenB ) );
+        Assertions.assertEquals( "alice", store.redeem( tokenA ) );
+    }
+
+}
diff --git a/jspwiki-war/src/main/webapp/LostPassword.jsp b/jspwiki-war/src/main/webapp/LostPassword.jsp
index a72dbcf7f..a49af3376 100644
--- a/jspwiki-war/src/main/webapp/LostPassword.jsp
+++ b/jspwiki-war/src/main/webapp/LostPassword.jsp
@@ -41,54 +41,102 @@
 
     String message = null;
 
-    public boolean resetPassword( Engine wiki, HttpServletRequest request, ResourceBundle rb ) {
-        // Reset pw for account name
+    /*
+     * Builds the login URL for the reset e-mails from configuration ("jspwiki.baseURL", the
+     * externally reachable base URL of the wiki including the context path), never from request
+     * headers (Host / X-Forwarded-*), which are attacker-controlled. If the property is not set,
+     * a server-relative URL is used.
+     */
+    private String buildLoginUrl( Engine wiki ) {
+        String loginUrl = wiki.getManager( URLConstructor.class ).makeURL( ContextEnum.PAGE_NONE.getRequestContext(), "Login.jsp", "" );
+        String base = TextUtil.getStringProperty( wiki.getWikiProperties(), "jspwiki.baseURL", "" ).trim();
+        if( base.isEmpty() ) {
+            return loginUrl;
+        }
+        while( base.endsWith( "/" ) ) {
+            base = base.substring( 0, base.length() - 1 );
+        }
+        String contextPath = wiki.getBaseURL();
+        if( !contextPath.isEmpty() && loginUrl.startsWith( contextPath ) ) {
+            loginUrl = loginUrl.substring( contextPath.length() );
+        }
+        return base + loginUrl;
+    }
+
+    /*
+     * Step 1 of the password reset: mail a single-use, expiring reset token to the account owner.
+     * Nothing is disclosed to the requester: the caller reports the same message whether or not
+     * the account exists, so this cannot be used as an account enumeration oracle, and the stored
+     * credential is not touched here.
+     */
+    public void requestResetToken( Engine wiki, HttpServletRequest request, ResourceBundle rb ) {
         String name = request.getParameter( "name" );
         UserDatabase userDatabase = wiki.getManager( UserManager.class ).getUserDatabase();
-        boolean success = false;
 
         try {
-            UserProfile profile = null;
-            /*
-             // This is disabled because it would otherwise be possible to DOS JSPWiki instances
-             // by requesting new passwords for all users.  See https://issues.apache.org/jira/browse/JSPWIKI-78
-             try {
-                 profile = userDatabase.find(name);
-             } catch (NoSuchPrincipalException e) {
-             // Try email as well
-             }
-            */
-            if( profile == null ) {
-                profile = userDatabase.findByEmail( name );
+            UserProfile profile = userDatabase.findByEmail( name );
+            String token = PasswordResetTokenStore.getInstance().issue( profile.getLoginName() );
+            if( token == null ) {
+                // A token is already outstanding for this account (or the store is full): throttled.
+                log.info( "Password reset token request throttled." );
+                return;
             }
 
-            String email = profile.getEmail();
+            Object[] args = { profile.getLoginName(), token, buildLoginUrl( wiki ), wiki.getApplicationName() };
+            Object[] args2 = { wiki.getApplicationName() };
+            MailUtil.sendMessage( wiki.getWikiProperties(),
+                                  profile.getEmail(),
+                                  MessageFormat.format( rb.getString( "lostpwd.token.subject" ), args2 ),
+                                  MessageFormat.format( rb.getString( "lostpwd.token.email" ), args ) );
+
+            log.info( "User " + profile.getLoginName() + " requested and received a password reset token." );
+        } catch( NoSuchPrincipalException e ) {
+            // Deliberately indistinguishable from success for the requester.
+            log.info( "Password reset requested for a non-existent account." );
+        } catch( Exception e ) {
+            log.error( "Tried to send a password reset token and got an exception: " + e );
+        }
+    }
+
+    /*
+     * Step 2 of the password reset: redeem the emailed token. Only here, with proof of control
+     * over the account mailbox, is the stored credential changed.
+     */
+    public boolean redeemResetToken( Engine wiki, HttpServletRequest request, ResourceBundle rb ) {
+        String token = request.getParameter( "resettoken" );
+        String loginName = PasswordResetTokenStore.getInstance().redeem( token == null ? null : token.trim() );
+        if( loginName == null ) {
+            message = rb.getString( "lostpwd.reset.unable" );
+            log.info( "Password reset attempted with an invalid, used or expired token." );
+            return false;
+        }
+
+        UserDatabase userDatabase = wiki.getManager( UserManager.class ).getUserDatabase();
+        boolean success = false;
+
+        try {
+            UserProfile profile = userDatabase.findByLoginName( loginName );
             String randomPassword = TextUtil.generateRandomPassword();
 
             // Try sending email first, as that is more likely to fail.
 
-            Object[] args = { profile.getLoginName(), randomPassword, request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort() +
-                             wiki.getManager( URLConstructor.class ).makeURL( ContextEnum.PAGE_NONE.getRequestContext(), "Login.jsp", "" ), wiki.getApplicationName() };
+            Object[] args = { profile.getLoginName(), randomPassword, buildLoginUrl( wiki ), wiki.getApplicationName() };
 
             String mailMessage = MessageFormat.format( rb.getString( "lostpwd.newpassword.email" ), args );
 
             Object[] args2 = { wiki.getApplicationName() };
-            MailUtil.sendMessage( wiki.getWikiProperties(), 
-            		              email, 
+            MailUtil.sendMessage( wiki.getWikiProperties(),
+            		              profile.getEmail(),
             		              MessageFormat.format( rb.getString( "lostpwd.newpassword.subject" ), args2 ),
                                   mailMessage );
 
-            log.info( "User " + email + " requested and received a new password." );
+            log.info( "User " + profile.getLoginName() + " redeemed a reset token and received a new password." );
 
             // Mail succeeded.  Now reset the password.
             // If this fails, we're kind of screwed, because we already emailed.
             profile.setPassword( randomPassword );
             userDatabase.save( profile );
             success = true;
-        } catch( NoSuchPrincipalException e ) {
-            Object[] args = { name };
-            message = MessageFormat.format( rb.getString( "lostpwd.nouser" ), args );
-            log.info( "Tried to reset password for non-existent user '" + name + "'" );
         } catch( SendFailedException e ) {
             message = rb.getString( "lostpwd.nomail" );
             log.error( "Tried to reset password and got SendFailedException: " + e );
@@ -122,14 +170,24 @@
 
     boolean done = false;
 
-    if( action != null && action.equals( "resetPassword" ) ) {
-        if( resetPassword( wiki, request, rb ) ) {
-            done = true;
-            wikiSession.addMessage( "resetpwok", rb.getString( "lostpwd.emailed" ) );
-            pageContext.setAttribute( "passwordreset", "done" );
+    // State changes only happen on POST: GET never mutates anything, and the
+    // CsrfProtectionFilter validates the anti-CSRF token on every POST.
+    if( "resetPassword".equals( action ) && "POST".equalsIgnoreCase( request.getMethod() ) ) {
+        String resetToken = request.getParameter( "resettoken" );
+        if( resetToken != null && !resetToken.trim().isEmpty() ) {
+            // Step 2: redeem the emailed token; only now is the stored credential changed.
+            if( redeemResetToken( wiki, request, rb ) ) {
+                done = true;
+                wikiSession.addMessage( "resetpwok", rb.getString( "lostpwd.emailed" ) );
+                pageContext.setAttribute( "passwordreset", "done" );
+            } else {
+                // Error
+                wikiSession.addMessage( "resetpw", message );
+            }
         } else {
-            // Error
-            wikiSession.addMessage( "resetpw", message );
+            // Step 1: always report the same outcome, whether or not the account exists.
+            requestResetToken( wiki, request, rb );
+            wikiSession.addMessage( "resetpwok", rb.getString( "lostpwd.tokenmailed" ) );
         }
     }
 
diff --git a/jspwiki-war/src/main/webapp/templates/210/LoginContent.jsp b/jspwiki-war/src/main/webapp/templates/210/LoginContent.jsp
index 6de00fa17..ed4dc0458 100644
--- a/jspwiki-war/src/main/webapp/templates/210/LoginContent.jsp
+++ b/jspwiki-war/src/main/webapp/templates/210/LoginContent.jsp
@@ -157,6 +157,10 @@
       <td><label for="name"><fmt:message key="login.lostpw.name"/></label></td>
       <td><input type="text" size="24" name="name" id="name" /></td>
     </tr>
+    <tr>
+      <td><label for="resettoken"><fmt:message key="login.lostpw.token"/></label></td>
+      <td><input type="text" size="24" name="resettoken" id="resettoken" /></td>
+    </tr>
     <tr>
       <td>&nbsp;</td>
       <td>
diff --git a/jspwiki-war/src/main/webapp/templates/default/LoginContent.jsp b/jspwiki-war/src/main/webapp/templates/default/LoginContent.jsp
index 4c64fa001..588fa7cd1 100644
--- a/jspwiki-war/src/main/webapp/templates/default/LoginContent.jsp
+++ b/jspwiki-war/src/main/webapp/templates/default/LoginContent.jsp
@@ -150,6 +150,12 @@
        placeholder="<fmt:message key='login.lostpw.name'/>"
               name="name" id="name" />
     </div>
+    <div class="form-group">
+      <p class="help-block"><fmt:message key="login.lostpw.token.help"/></p>
+      <input class="form-control" type="text" size="24"
+       placeholder="<fmt:message key='login.lostpw.token'/>"
+              name="resettoken" id="resettoken" />
+    </div>
     <div class="form-group">
       <input type="hidden" name="action" value="resetPassword"/>
       <input class="btn btn-success btn-block" type="submit" name="Submit" value="<fmt:message key='login.lostpw.submit'/>" />