Table of Contents
1. Implement SMS login based on session
1.1 SMS login flow chart
1.2 Implementation of sending SMS verification code
3.1 Redis implements shared session login flow chart
Front-end request instructions:
Home Database Redis How to implement SMS login in Redis shared session application

How to implement SMS login in Redis shared session application

Jun 03, 2023 pm 03:11 PM
redis session

1. Implement SMS login based on session

1.1 SMS login flow chart

How to implement SMS login in Redis shared session application

1.2 Implementation of sending SMS verification code

Front-end request instructions:

##InstructionsRequest methodPOSTRequest path/user/codeRequest parametersphone (phone number)Return valueNone

Back-end interface implementation:

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1. 校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            // 2. 如果不符合,返回错误信息
            return Result.fail("手机号格式错误!");
        }
        // 3. 符合,生成验证码(设置生成6位)
        String code = RandomUtil.randomNumbers(6);
        // 4. 保存验证码到 session
        session.setAttribute("code", code);
        // 5. 发送验证码(这里并未实现,通过日志记录)
        log.debug("发送短信验证码成功,验证码:{}", code);
        // 返回 ok
        return Result.ok();
    }
}
Copy after login

1.3 Implement SMS verification code login and registration

Front-end request instructions

DescriptionRequest methodPOSTRequest path/ user/loginRequest parametersphone (phone number); code (verification code)Return valueNone

Backend interface implementation:

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1. 校验手机号
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            // 不一致,返回错误信息
            return Result.fail("手机号格式错误!");
        }
        // 2. 校验验证码
        String cacheCode = (String) session.getAttribute("code");
        String code = loginForm.getCode();
        if(cacheCode == null || !cacheCode.equals(cacheCode)){
            // 不一致,返回错误信息
            return Result.fail("验证码错误!");
        }
        // 4. 一致,根据手机号查询用户(这里使用的 mybatis-plus)
        User user = query().eq("phone", phone).one();
        // 5. 判断用户是否存在
        if(user == null){
            // 6. 不存在,创建新用户并保存
            user = createUserWithPhone(phone);
        }
        	// 7. 保存用户信息到 session 中(通过 BeanUtil.copyProperties 方法将 user 中的信息过滤到 UserDTO 上,即用来隐藏部分信息)
        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok();
    }

    private User createUserWithPhone(String phone) {
        // 1. 创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + RandomUtil.randomString(10));
        // 2. 保存用户(这里使用 mybatis-plus)
        save(user);
        return user;
    }
}
Copy after login
Copy after login

1.4 Implement login verification interceptor

Login verification interceptor Implementation:

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取 session
        HttpSession session = request.getSession();
        // 2. 获取 session 中的用户
        UserDTO user = (UserDTO) session.getAttribute("user");
        // 3. 判断用户是否存在
        if(user == null){
            // 4. 不存在,拦截,返回 401 未授权
            response.setStatus(401);
            return false;
        }
        // 5. 存在,保存用户信息到 ThreadLocal
        UserHolder.saveUser(user);
        // 6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户,避免内存泄露
        UserHolder.removeUser();
    }
}
Copy after login
Copy after login

UserHolder class implementation: This class defines a static ThreadLocal

public class UserHolder {
    private static final ThreadLocal<UserDTO> tl = new ThreadLocal<>();

    public static void saveUser(UserDTO user){
        tl.set(user);
    }

    public static UserDTO getUser(){
        return tl.get();
    }

    public static void removeUser(){
        tl.remove();
    }
}
Copy after login
Copy after login

Configuration interceptor:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/user/login",
                        "/user/code"
                );
    }
}
Copy after login

Front-end request description:

DescriptionRequest methodPOSTRequest path/user/meRequest parametersNoneReturn value None

Backend interface implementation:

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result me() {
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }
}
Copy after login
Copy after login

2. Cluster session sharing problem

session sharing problem :

Multiple tomcats do not share session storage space. When the request is switched to different tomcat services, it will cause data loss.

Session alternatives should meet the following conditions:

  • Data sharing (different tomcats can access data in Redis)

  • Memory storage (Redis stores through memory)

  • key, value structure (Redis is a key-value structure)

3. Based on Redis implements shared session login

3.1 Redis implements shared session login flow chart

How to implement SMS login in Redis shared session application

How to implement SMS login in Redis shared session application##3.2 Implement sending SMS verification code

Front-end request instructions:

Request methodRequest pathRequest parametersReturn value Backend interface implementation :

Instructions
POST
/user/code
phone(phone number)
None
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1. 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2. 如果不符合,返回错误信息
            return Result.fail("手机号格式错误!");
        }
        // 3. 符合,生成验证码(设置生成6位)
        String code = RandomUtil.randomNumbers(6);
        // 4. 保存验证码到 Redis(以手机号为 key,设置有效期为 2min)
        stringRedisTemplate.opsForValue().set("login:code:" + phone, code, 2, TimeUnit.MINUTES);
        // 5. 发送验证码(这里并未实现,通过日志记录)
        log.debug("发送短信验证码成功,验证码:{}", code);
        // 返回 ok
        return Result.ok();
    }
}
Copy after login

3.3 Implement SMS verification code login and registration

Front-end request instructions:

Request methodRequest pathRequest parameters##Return valueNoneBackend interface implementation:
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1. 校验手机号
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            // 不一致,返回错误信息
            return Result.fail("手机号格式错误!");
        }
        // 2. 校验验证码
        String cacheCode = (String) session.getAttribute("code");
        String code = loginForm.getCode();
        if(cacheCode == null || !cacheCode.equals(cacheCode)){
            // 不一致,返回错误信息
            return Result.fail("验证码错误!");
        }
        // 4. 一致,根据手机号查询用户(这里使用的 mybatis-plus)
        User user = query().eq("phone", phone).one();
        // 5. 判断用户是否存在
        if(user == null){
            // 6. 不存在,创建新用户并保存
            user = createUserWithPhone(phone);
        }
        	// 7. 保存用户信息到 session 中(通过 BeanUtil.copyProperties 方法将 user 中的信息过滤到 UserDTO 上,即用来隐藏部分信息)
        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok();
    }

    private User createUserWithPhone(String phone) {
        // 1. 创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + RandomUtil.randomString(10));
        // 2. 保存用户(这里使用 mybatis-plus)
        save(user);
        return user;
    }
}
Copy after login
Copy after login

Description
POST
/user/login
phone (phone number); code (verification code)
3.4 Implement login verification interceptor

Here the original interceptor is divided into two interceptors The first interceptor intercepts all requests. Each interception refreshes the validity period of the token and saves the user information that can be queried into ThreadLocal. The second interceptor performs the interception function and intercepts the path that requires login.

Refresh token interceptor implementation:

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头中的 token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        // 2. 基于 token 获取 redis 中的用户
        String tokenKey = "login:token:" + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        // 3. 判断用户是否存在
        if (userMap.isEmpty()) {
            return true;
        }
        // 5. 将查询到的 Hash 数据转为 UserDTO 对象
        UserDTO user = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        // 6. 存在,保存用户信息到 ThreadLocal
        UserHolder.saveUser(user);
        // 7. 刷新 token 有效期 30 min
        stringRedisTemplate.expire(tokenKey, 30, TimeUnit.MINUTES);
        // 8. 放行
        return true;
    }
}
Copy after login

Login verification interceptor implementation:

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取 session
        HttpSession session = request.getSession();
        // 2. 获取 session 中的用户
        UserDTO user = (UserDTO) session.getAttribute("user");
        // 3. 判断用户是否存在
        if(user == null){
            // 4. 不存在,拦截,返回 401 未授权
            response.setStatus(401);
            return false;
        }
        // 5. 存在,保存用户信息到 ThreadLocal
        UserHolder.saveUser(user);
        // 6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户,避免内存泄露
        UserHolder.removeUser();
    }
}
Copy after login
Copy after login

UserHolder class implementation: This class defines a static ThreadLocal

public class UserHolder {
    private static final ThreadLocal<UserDTO> tl = new ThreadLocal<>();

    public static void saveUser(UserDTO user){
        tl.set(user);
    }

    public static UserDTO getUser(){
        return tl.get();
    }

    public static void removeUser(){
        tl.remove();
    }
}
Copy after login
Copy after login

Configure interceptor:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate))
                .addPathPatterns("/**").order(0);
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/user/login",
                        "/user/code"
                ).order(1);
    }
}
Copy after login

Front-end request description:

Request methodPOSTRequest path/user/meRequest parametersNoneReturn valueNone Backend interface implementation :
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result me() {
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }
}
Copy after login
Copy after login

The above is the detailed content of How to implement SMS login in Redis shared session application. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

How to implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

What to do if redis-server can't be found What to do if redis-server can't be found Apr 10, 2025 pm 06:54 PM

Steps to solve the problem that redis-server cannot find: Check the installation to make sure Redis is installed correctly; set the environment variables REDIS_HOST and REDIS_PORT; start the Redis server redis-server; check whether the server is running redis-cli ping.

How to view all keys in redis How to view all keys in redis Apr 10, 2025 pm 07:15 PM

To view all keys in Redis, there are three ways: use the KEYS command to return all keys that match the specified pattern; use the SCAN command to iterate over the keys and return a set of keys; use the INFO command to get the total number of keys.

See all articles
Description