Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 119 ยท Spring Boot

Registration, Email Activation and Password Reset with Spring Security

Build the account lifecycle around Spring Security - registration with password hashing, activation tokens by email, resend, password reset and lockout after failed logins.

Spring Security answers "who is calling and what may they do?". It deliberately does not ship a sign-up page, a "verify your email" mail or a "forgot password" form. Every application with user accounts needs these flows, and getting them subtly wrong is how accounts get taken over: a reset token that never expires, a registration form that tells attackers which emails are registered, a login that can be guessed at a million times an hour.

This lesson walks through the whole account lifecycle: register, activate by email, resend the activation mail, reset a forgotten password, change a password, and lock an account after repeated failures. Spring and a mail server can't run in this page's editor, so the Spring code is read-only (but real), and each flow also comes as a plain-Java stand-in with an in-memory "database" and an "outbox" list instead of a mail server. The stand-ins use the JDK's PBKDF2 for hashing because the JDK has no BCrypt; in your application you use PasswordEncoder as shown in the Spring Security lesson.

The shape of the flows

flowchart LR
  A["Register<br/>email + password"] --> B["Account saved<br/>enabled = false"]
  B --> C["Email with<br/>activation link"]
  C --> D["Click link<br/>token checked"]
  D --> E["enabled = true<br/>can log in"]
  F["Forgot password"] --> G["Email with<br/>reset link"]
  G --> H["New password<br/>token consumed"]

Both flows prove control of an email address with a secret, single-use, expiring token.

Almost everything below follows from three rules:

  1. Prove email ownership with a random secret. Anyone can type any address into a form; only the owner can read the mail.
  2. Tokens are secrets, so treat them like passwords. Generate them with SecureRandom, store only a hash, give them an expiry, and make them single-use.
  3. Never reveal whether an account exists. Answer "if that address is registered, we sent an email" for known and unknown addresses alike.

The data model

Two tables are enough. The user needs an enabled flag (activation) and, for lockout, a failure counter and a lock timestamp. The token table can serve both activation and reset through a purpose:

Java
@Entity
@Table(name = "app_user")
public class AppUser {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true, length = 254)
    private String email;                      // store lower-case, enforce with the unique index

    @Column(nullable = false)
    private String passwordHash;               // "{bcrypt}$2a$10$..." from the PasswordEncoder

    private boolean enabled;                   // false until the email link is used
    private int failedLogins;
    private Instant lockedUntil;               // null = not locked
    // getters and setters omitted
}

@Entity
public class EmailToken {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(optional = false) private AppUser user;

    @Column(nullable = false, unique = true, length = 64)
    private String tokenHash;                  // SHA-256 of the token, never the token itself

    @Enumerated(EnumType.STRING) private Purpose purpose;   // ACTIVATION, PASSWORD_RESET
    private Instant expiresAt;
    private Instant usedAt;

    public enum Purpose { ACTIVATION, PASSWORD_RESET }
}

Why hash a token that is already random? Because a database leak or a read-only SQL injection would otherwise hand over working reset links for every pending request. A fast hash such as SHA-256 is fine here (unlike for passwords), since the input has 256 bits of randomness and cannot be guessed offline.

Registration

The controller validates the form with Bean Validation (Validation and Error Handling), and the service does the work in one transaction:

Java
public record RegistrationForm(
        @NotBlank @Email @Size(max = 254) String email,
        @NotBlank @Size(min = 12, max = 128) String password) {}

@Controller
class RegistrationController {
    private final RegistrationService registration;

    RegistrationController(RegistrationService registration) { this.registration = registration; }

    @PostMapping("/register")
    String register(@Valid @ModelAttribute("form") RegistrationForm form, BindingResult errors) {
        if (errors.hasErrors()) {
            return "register";                                    // show field errors again
        }
        registration.register(form.email(), form.password());
        return "redirect:/register/check-your-email";             // same page for new and known addresses
    }
}

@Service
class RegistrationService {
    private final AppUserRepository users;
    private final EmailTokenService tokens;
    private final PasswordEncoder encoder;
    private final ApplicationEventPublisher events;

    // constructor omitted

    @Transactional
    public void register(String rawEmail, String password) {
        String email = rawEmail.trim().toLowerCase(Locale.ROOT);
        Optional<AppUser> existing = users.findByEmail(email);
        if (existing.isPresent()) {
            events.publishEvent(new AlreadyRegisteredEvent(email));        // mail the owner, show nothing new
            return;
        }
        AppUser user = new AppUser(email, encoder.encode(password));
        users.save(user);
        String token = tokens.issue(user, EmailToken.Purpose.ACTIVATION, Duration.ofHours(24));
        events.publishEvent(new ActivationRequestedEvent(email, token));
    }
}

Several choices here are deliberate:

  • Hash with the PasswordEncoder, never store or log the password. Length matters more than "must contain a symbol" rules; allow long passphrases (up to 128 characters, so a huge input can't be used to burn CPU in the hash).
  • Lower-case the email before storing and checking, and back it with a unique index. Two simultaneous sign-ups for one address are decided by the database, not by your findByEmail check, so catch DataIntegrityViolationException and treat it like the "already registered" branch.
  • The response is identical whether the email was new or known. For a known address the owner gets a different mail ("someone tried to register with your address; if it was you, use password reset"). Otherwise the form is a free tool for checking who has an account.
  • The mail is sent after the commit. Publishing an event and handling it with @TransactionalEventListener(phase = AFTER_COMMIT) (see Spring Events and Transactions) means no mail goes out for a transaction that rolled back, and a slow mail server doesn't hold the database transaction open. Sending itself uses JavaMailSender (Sending Email with Jakarta Mail) and should be @Async or queued.
Java
@Component
class ActivationMailer {
    private final JavaMailSender mail;
    ActivationMailer(JavaMailSender mail) { this.mail = mail; }

    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    void on(ActivationRequestedEvent event) {
        var message = new SimpleMailMessage();
        message.setTo(event.email());
        message.setSubject("Confirm your email address");
        message.setText("Welcome! Confirm your address within 24 hours:\n"
            + "https://shop.example.com/activate?token=" + event.token());   // base URL from configuration
        mail.send(message);
    }
}

Build the link from a configured base URL, never from the Host header of the request: a forged Host header would otherwise make your own server mail out a link to the attacker's site (a host header injection).

Activation

The link opens GET /activate?token=.... Looking up a token changes state, so many applications show a confirmation page whose button sends a POST; this stops mail scanners and link-preview bots, which fetch every URL in a mail, from consuming the token before the human does. The service looks up the hash, checks the rules and flips the flag:

Java
@Transactional
public void activate(String rawToken) {
    EmailToken token = tokens.consume(rawToken, EmailToken.Purpose.ACTIVATION)   // throws InvalidTokenException
                             .orElseThrow(InvalidTokenException::new);
    token.getUser().setEnabled(true);
}

consume finds the row by sha256(rawToken), rejects it when usedAt is set or expiresAt is in the past, and sets usedAt = now. A user who is not enabled can't log in: your UserDetailsService maps the flag with .disabled(!user.isEnabled()), and Spring Security throws DisabledException. A login failure handler can turn that exception into "Please confirm your email address", with a link to the resend form (the one message that is safe to be specific about, because the user has just supplied the right password).

Resending the activation mail

Mails get lost, filtered, or expire. The resend form takes an email and, like registration, always says "if that account needs activation, we sent a new link". On the server: find the user, invalidate older activation tokens, issue a new one, and rate-limit (for example one mail per address per few minutes, plus a per-IP limit), because otherwise your form is a free mail-bombing service.

The first stand-in: register, activate, resend

The program below follows the real flow with an in-memory store: PBKDF2 password hashes, SHA-256 token hashes, a controllable clock so tokens can expire without waiting, and an outbox list that plays the role of JavaMailSender. Look at what the caller sees for known and unknown emails: the same string.

Java Registration, activation and resend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Password reset

Reset reuses the same token machinery with Purpose.PASSWORD_RESET and a short lifetime (15 to 60 minutes):

  1. POST /forgot-password with an email. The answer is always "if that address has an account, we sent a link". If it does, invalidate older reset tokens, issue a new one, send the mail.
  2. GET /reset-password?token=... shows a form. Do not trust the token yet; just render the form (and add <meta name="referrer" content="no-referrer"> so the token in the URL can't leak through the Referer header to any third-party resource on the page).
  3. POST /reset-password with the token and the new password (twice if you wish). Validate the password with the same rules as registration, consume the token, store the new hash, and invalidate all other tokens and sessions for the user.
Java
@Transactional
public void resetPassword(String rawToken, String newPassword) {
    EmailToken token = tokens.consume(rawToken, EmailToken.Purpose.PASSWORD_RESET)
                             .orElseThrow(InvalidTokenException::new);
    AppUser user = token.getUser();
    user.setPasswordHash(encoder.encode(newPassword));
    user.setFailedLogins(0);
    user.setLockedUntil(null);
    tokens.invalidateAll(user, EmailToken.Purpose.PASSWORD_RESET);
    sessionRegistry.expireAllSessions(user.getEmail());          // log out other devices
    events.publishEvent(new PasswordChangedEvent(user.getEmail()));   // "your password was changed" mail
}

That last event matters: always mail the owner when a password changes. If an attacker did it, the real owner learns about it immediately. Resetting a password also proves email ownership, so it is a sensible moment to set enabled = true for a user who never found the activation mail, as long as you document that choice.

Changing a password while signed in

The "change password" page asks for the current password as well as the new one. The reason is stolen sessions: someone at an unlocked laptop can click "change password" but does not know the old one. Check it with encoder.matches(current, user.getPasswordHash()), apply the same strength rules, and send the same notification and session expiry as for reset. Changing the email address works the same way and should also verify the new address with a token before switching.

Lockout after failed attempts

Passwords can be guessed by trying many of them. Spring Security's UserDetails already has the switch (accountNonLocked), and Spring publishes an event for each failure, so a small listener counts them:

Java
@Component
class LoginAttemptListener {
    private static final int MAX_FAILURES = 5;
    private static final Duration LOCK_TIME = Duration.ofMinutes(15);
    private final AppUserRepository users;
    private final Clock clock;

    // constructor omitted

    @EventListener
    @Transactional
    void onFailure(AuthenticationFailureBadCredentialsEvent event) {
        users.findByEmail(event.getAuthentication().getName().toLowerCase(Locale.ROOT)).ifPresent(user -> {
            user.setFailedLogins(user.getFailedLogins() + 1);
            if (user.getFailedLogins() >= MAX_FAILURES) {
                user.setLockedUntil(clock.instant().plus(LOCK_TIME));
            }
        });
    }

    @EventListener
    @Transactional
    void onSuccess(AuthenticationSuccessEvent event) {
        users.findByEmail(event.getAuthentication().getName().toLowerCase(Locale.ROOT)).ifPresent(user -> {
            user.setFailedLogins(0);
            user.setLockedUntil(null);
        });
    }
}

and the UserDetailsService turns the timestamp into the lock:

Java
return User.withUsername(user.getEmail())
    .password(user.getPasswordHash())
    .disabled(!user.isEnabled())
    .accountLocked(user.getLockedUntil() != null && user.getLockedUntil().isAfter(clock.instant()))
    .roles("USER")
    .build();

Think about the trade-offs before switching it on:

  • A permanent lock is a denial-of-service weapon. Anyone who knows your email could lock you out by typing wrong passwords. Use a temporary lock that expires (as here), or a growing delay.
  • Lockout per account doesn't stop an attacker who tries one common password against thousands of accounts (password spraying). Add a per-IP rate limit at the proxy or gateway, and watch for patterns in your logs.
  • Telling a locked user "your account is locked" confirms the account exists. Many sites show the same "wrong email or password" and quietly delay instead; others accept that trade-off to support honest users. Decide deliberately.
  • Use a shared counter (database or Redis) if you run more than one server instance. An in-memory map lets an attacker try five passwords on each instance.

The second stand-in combines reset and lockout.

Java Password reset and temporary lockout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Putting it together

A checklist you can review any registration feature against:

Concern Do Avoid
Passwords PasswordEncoder (BCrypt/Argon2), length 12+, allow long passphrases Custom hashing, composition rules, silent truncation
Tokens SecureRandom, 256 bits, store a hash, expire, single-use UUID.randomUUID() of unknown quality, plain tokens in the database, tokens that live forever
Messages Same answer for known and unknown emails "No account with that email"
Links Built from configured base URL Built from the Host header
Mail After commit, async, rate-limited Inside the transaction, unlimited resends
Brute force Temporary lock + per-IP limit Permanent lock on the first mistake
After a change Notify the owner, end other sessions Silence

Finally, test the denials: an expired token, a reused token, a token for the wrong purpose (an activation token must not work on the reset endpoint), an unknown email returning the same body as a known one, and the sixth login attempt locking the account. These are the cases attackers try first. See Testing Spring Boot Applications.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the registration form give the same response whether or not the email address is already registered?

    A different answer turns the form into an account-existence oracle. The owner of a known address gets a separate email instead.
  2. 2. How should activation and reset tokens be stored?

    A leaked table of plain tokens would hand out working links. Random 256-bit values need only a fast hash, and expiry plus single use limit the damage of any token that escapes.
  3. 3. Why is a permanent account lock after five failed logins a risky design?

    Use a temporary lock or growing delays, plus per-IP rate limiting. Resetting the password may also clear the lock, as in the example.
  4. 4. A user changes their password while signed in. Which steps belong to the flow?

    Asking for the current password defeats someone using a stolen or unlocked session. The notification and session expiry limit the damage if it was not the owner.
  5. 5. Where should the base URL in an activation link come from?

    Request headers are attacker-controlled. Building links from them allows host header injection, where your own mail points at the attacker's site.

Summary

  • Spring Security authenticates and authorizes; registration, activation and reset are your code. Build them from a few safe parts: hashed passwords, random single-use expiring tokens, uniform responses, and mail sent after commit.
  • Registration stores an enabled = false user, mails an activation link, and activates when the token is consumed. Resend invalidates old tokens and must be rate-limited.
  • Store only a hash of each token, give it a purpose and an expiry, mark it used, and never build links from the request's Host header.
  • Password reset answers the same for known and unknown addresses, uses short-lived tokens, stores a new PasswordEncoder hash, ends other sessions and notifies the owner. Changing a password while signed in requires the current one.
  • Lock accounts temporarily after repeated failures (AuthenticationFailureBadCredentialsEvent, accountLocked), keep counters in shared storage and add per-IP rate limits.

Next: Spring Security: Two-Factor Auth, API Keys and Role Hierarchy adds a second factor and key-based access.