使用Spring Boot和Redis实现邮箱注册与登录的验证码验证

引言

在现代web应用中,邮箱注册和登录是一种常见的用户验证方式。为了增强安全性和便捷性,我们可以利用Redis缓存存储验证码及其过期时间。本文将展示如何使用Spring Boot和Redis来实现邮箱验证码的注册与登录功能。

环境准备

1. 创建Spring Boot项目

首先,你需要创建一个Spring Boot项目,并配置必要的依赖。你可以使用Spring Initializr或编辑pom.xml文件。

pom.xml
<!-- 邮件发送 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. 配置文件

application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: your_username
    password: your_password
  data:
    redis:
      host: localhost
      port: 6379
      password: your_password
  mail:
    host: smtp.qq.com
    port: 465
    username: your_email@qq.com
    password: your_smtp_password
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
          ssl:
            enable: true

3. 创建Redis配置类

RedisConfig.java
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }
}

4. 创建用户实体类

User.java
package com.example.demo.entity;

import lombok.Data;

import javax.persistence.*;

@Data
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String password;
}

5. 编写用户服务类

UserService.java
package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.Random;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final String REDIS_KEY_PREFIX = "email:verification:";

    public void sendVerificationCode(String email) {
        String code = generateVerificationCode();
        redisTemplate.opsForValue().set(REDIS_KEY_PREFIX + email, code, 10, TimeUnit.MINUTES);

        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("your_email@qq.com");
        message.setTo(email);
        message.setSubject("邮箱验证码");
        message.setText("您的验证码是:" + code + ",有效期为10分钟。");
        mailSender.send(message);
    }

    public boolean verifyCode(String email, String code) {
        String redisCode = (String) redisTemplate.opsForValue().get(REDIS_KEY_PREFIX + email);
        return code.equals(redisCode);
    }

    public User registerUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    private String generateVerificationCode() {
        Random random = new Random();
        return String.format("%06d", random.nextInt(999999));
    }
}

6,总结

核心代码

@Resource
JavaMailSender javaMailSender; 



/**
     * 发送邮件
     *
     * @param email
     */
    public void sendVerificationCode(String email) {
        // 1.构建邮件对象
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("1789714718@qq.com"); // 发送方
        simpleMailMessage.setTo(email); // 接收方
        simpleMailMessage.setSubject("【沙琪马】登录邮箱验证"); // 标题
        String code = RandomUtil.randomNumbers(4);// 随机一个 4位长度的验证码
        // 2.将验证码保存到redis中
        redisTemplate.opsForValue().set(REDIS_KEY_PREFIX + email, code, 10, TimeUnit.MINUTES);
        simpleMailMessage.setSentDate(new Date()); // 设置发送时间
        simpleMailMessage.setText("您本次邮箱登录的验证码是:" + code + ",有效时间为五分钟.请妥善保管,切勿泄露."); // 内容
        // 3.发送邮件
        javaMailSender.send(simpleMailMessage);
        log.info("邮件:" + email + ",发送成功");
    }

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值