Backend Development 5 min read

How to Implement Secure Auto‑Login with Cookie + Token in Java Spring

This guide explains how to create a seamless auto‑login feature by persisting a token in a cookie after the first successful login, storing the token in Redis, and validating it on subsequent visits, complete with Java Spring code examples.

Lobster Programming
Lobster Programming
Lobster Programming
How to Implement Secure Auto‑Login with Cookie + Token in Java Spring

In software applications, improving user experience often involves providing an automatic login feature, which persists the user's login state after the first successful sign‑in.

The auto‑login works by storing a token in a cookie after the initial login; on subsequent visits the token is retrieved from the cookie, validated against Redis and the database, and the user is set to a logged‑in state without re‑entering credentials.

1. Cookie + Token implementation

When the user selects “auto‑login” and logs in, the server generates a token, saves it in Redis, updates the user record in the database, and writes the token into a cookie that lasts for a week.

On the next request, the browser sends the cookie; the server extracts the token, checks Redis (and optionally the database), and if the token is valid, marks the user as logged in.

2. Core implementation code

Login endpoint (generates token and sets cookie)

<code>@PostMapping("/login")
public String login(@RequestBody User loginUser, HttpServletResponse response) {
    User user = userService.queryUserByName(loginUser.getUsername());
    // User verification
    if (user != null && user.getPassword().equals(loginUser.getPassword())) {
        String token = JWTUtils.generateToken(user);
        user.setToken(token);
        userService.save(user);
        // Store token in Redis for 7 days
        stringRedisTemplate.opsForValue().set("login_token_" + token,
            user.getId().toString(), 7 * 24 * 60 * 60, TimeUnit.SECONDS);
        // Set cookie
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        cookie.setMaxAge(7 * 24 * 60 * 60);
        response.addCookie(cookie);
        return "登录成功";
    } else {
        return "用户名或密码错误";
    }
}
</code>

Auto‑login endpoint (validates token from cookie)

<code>@GetMapping("/autoLogin")
public String autoLogin(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (Objects.isNull(cookies)) {
        return "自动登录失败";
    }
    for (Cookie cookie : cookies) {
        if ("token".equals(cookie.getName())) {
            String token = cookie.getValue();
            if (stringRedisTemplate.opsForValue().get("login_token_" + token) == null) {
                return "自动登录失败";
            }
            String userIdStr = JWTUtils.parseToken(token);
            User user = userService.queryByToken(token);
            if (Objects.nonNull(user) && user.getId().toString().equals(userIdStr)) {
                return "自动登录成功了";
            } else {
                return "自动登录失败";
            }
        }
    }
    return "自动登录失败";
}
</code>

In summary, by generating a token on the first successful login, storing it in both Redis and a browser cookie, and later verifying the token on each request, the system provides a reliable automatic login experience.

JavaRedisSpringtokencookieAuto Login
Lobster Programming
Written by

Lobster Programming

Sharing insights on technical analysis and exchange, making life better through technology.

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.