使用Spring Boot和Redis實(shí)現郵箱注冊與登錄的驗證碼驗證

admin2024-06-21  11

引言

在現代web應用中,郵箱注冊和登錄是一種常見(jiàn)的用戶(hù)驗證方式。為了增強安全性和便捷性,我們可以利用Redis緩存存儲驗證碼及其過(guò)期時(shí)間。本文將展示如何使用Spring Boot和Redis來(lái)實(shí)現郵箱驗證碼的注冊與登錄功能。

環(huán)境準備

1. 創(chuàng )建Spring Boot項目

首先,你需要創(chuàng )建一個(gè)Spring Boot項目,并配置必要的依賴(lài)。你可以使用Spring Initializr或編輯pom.xml文件。

pom.xml
<!-- 郵件發(fā)送 -->
<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. 創(chuàng )建Redis配置類(lèi)

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. 創(chuàng )建用戶(hù)實(shí)體類(lèi)

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. 編寫(xiě)用戶(hù)服務(wù)類(lèi)

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);

        // 發(fā)送郵件
        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; 



/**
     * 發(fā)送郵件
     *
     * @param email
     */
    public void sendVerificationCode(String email) {
        // 1.構建郵件對象
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("1789714718@qq.com"); // 發(fā)送方
        simpleMailMessage.setTo(email); // 接收方
        simpleMailMessage.setSubject("【沙琪馬】登錄郵箱驗證"); // 標題
        String code = RandomUtil.randomNumbers(4);// 隨機一個(gè) 4位長(cháng)度的驗證碼
        // 2.將驗證碼保存到redis中
        redisTemplate.opsForValue().set(REDIS_KEY_PREFIX + email, code, 10, TimeUnit.MINUTES);
        simpleMailMessage.setSentDate(new Date()); // 設置發(fā)送時(shí)間
        simpleMailMessage.setText("您本次郵箱登錄的驗證碼是:" + code + ",有效時(shí)間為五分鐘.請妥善保管,切勿泄露."); // 內容
        // 3.發(fā)送郵件
        javaMailSender.send(simpleMailMessage);
        log.info("郵件:" + email + ",發(fā)送成功");
    }
本文來(lái)自互聯(lián)網(wǎng)用戶(hù)投稿,該文觀(guān)點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲空間服務(wù),不擁有所有權,不承擔相關(guān)法律責任。如若轉載,請注明原文出處。如若內容造成侵權/違法違規/事實(shí)不符,請聯(lián)系SD編程學(xué)習網(wǎng):675289112@qq.com進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!
一级毛片在线一区二区-亚洲精品无码专区土豆网在线播放-亚洲无乱码一区二区三区-亚洲一区二区三区精品