Information Security 7 min read

Master One-Time Token Login with Spring Security 6.4: A Step-by-Step Guide

This guide explains Spring Security 6.4’s one-time token login feature, covering its concept, authentication flow, core components, and step‑by‑step implementation with code samples, enabling developers to add secure magic‑link authentication to Spring Boot applications.

macrozheng
macrozheng
macrozheng
Master One-Time Token Login with Spring Security 6.4: A Step-by-Step Guide

1. Overview

Spring Security 6.4 introduced a new feature called One-Time Token Login. This method lets users receive a magic link via email to authenticate, eliminating the need for a username‑password pair, improving user experience and security.

mintlify email login
mintlify email login

1.1 Login Flow Diagram

1.2 Source Code Analysis

This may be a useful open‑source project: the mall project is an e‑commerce system built with SpringBoot3 + Vue, featuring a 2024 micro‑service architecture, Docker and K8s deployment, and includes front‑end shop and back‑office management with full order workflow, product, cart, permissions, coupons, members, payment, etc. Boot project: https://github.com/macrozheng/mall Cloud project: https://github.com/macrozheng/mall-swarm Video tutorials: https://www.macrozheng.com/video/ Project demo:

2. Core Concepts

2.1 One-Time Token

A temporary credential that can be used only once.

Usually delivered to the user as a URL parameter or token string.

Typically valid for 5–15 minutes.

2.2 Magic Link

A URL containing the one‑time token.

Sent to the user via email.

Clicking the link completes authentication.

3. Implementation Principles

3.1 Authentication Process

Token generation: a cryptographically secure random 128‑bit token is created.

Token storage: supports various stores such as in‑memory, Redis, or a database.

Email sending: the magic link containing the token is sent asynchronously.

Token verification: a filter in the security chain validates the token.

Session establishment: a security context is created after successful verification.

3.2 Core Components

OneTimeTokenFilter : intercepts token verification requests.

OneTimeTokenManager : manages the token lifecycle.

TokenExpirationStrategy : defines token expiration policy.

TokenVerificationHandler : handles the token verification logic.

4. Implementation Steps

4.1 Add Dependencies

<code>&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
&lt;/dependency&gt;
</code>

4.2 Configure One-Time Token Service

<code>@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/login/**").permitAll()
                .anyRequest().authenticated()
            )
            .oneTimeTokenLogin(oneTime -> oneTime
                .tokenRepository(tokenRepository())
                .tokenValidityDuration(Duration.ofMinutes(5))
            );
        return http.build();
    }

    @Bean
    public OneTimeTokenRepository tokenRepository() {
        return new InMemoryOneTimeTokenRepository();
    }
}
</code>

4.3 Implement Token Generation and Sending

<code>@Service
public class OneTimeTokenService {

    @Autowired
    private OneTimeTokenRepository tokenRepository;

    @Autowired
    private EmailService emailService;

    public void sendLoginToken(String email) {
        String token = generateToken();
        tokenRepository.save(new OneTimeToken(token, email));

        String loginLink = "https://your-domain.com/login/verify?token=" + token;
        emailService.sendLoginLink(email, loginLink);
    }

    private String generateToken() {
        return UUID.randomUUID().toString();
    }
}
</code>

5. Summary

Spring Security 6.4’s one‑time token login provides a modern, secure authentication method that enhances user experience while maintaining strong security. Proper configuration and integration allow developers to build a complete security solution tailored to their specific scenarios.

The related mall‑swarm micro‑service project (⭐ 11K) and its 2024 video tutorial series (≈26 hours, 59 lessons) offer a comprehensive hands‑on reference for the latest micro‑service stack.

JavaSpring Bootbackend securitySpring SecurityOne-Time TokenMagic Link
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.