Spring Boot 使用 Mail 实现登录邮箱验证

Spring Boot 使用 Mail 实现登录邮箱验证

引言

在现代的 Web 应用中,用户验证是一个至关重要的功能。电子邮件验证可以有效地防止虚假注册,并确保用户提供的是有效的邮箱地址。在这篇文章中,我们将详细介绍如何使用 Spring Boot 实现用户注册时的邮箱验证功能。

前置条件

  1. 基础的 Java 编程知识。
  2. 基础的 Spring Boot 使用经验。
  3. 已安装的 Spring Boot 开发环境(例如 IntelliJ IDEA 或 Eclipse)。

项目设置

创建 Spring Boot 项目

使用 Spring Initializr 创建一个新的 Spring Boot 项目。选择以下依赖:

  • Spring Web
  • Spring Data JPA
  • Spring Boot DevTools
  • Thymeleaf
  • Spring Security
  • Spring Mail

配置数据库

application.properties 文件中配置数据库连接信息。例如,使用 H2 数据库:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

配置邮件服务器

application.properties 文件中添加邮件服务器的配置。例如,使用 Gmail SMTP 服务器:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

实现步骤

1. 创建用户实体类

创建一个 User 实体类,用于存储用户信息。

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private String email;
    private String password;
    private boolean enabled;

    // Getters and Setters
}

2. 创建用户仓库接口

创建一个 UserRepository 接口,用于与数据库交互。

package com.example.demo.repository;

import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);
}

3. 创建用户服务类

创建一个 UserService 类,包含用户注册和验证逻辑。

package com.example.demo.service;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JavaMailSender mailSender;

    public void registerUser(User user) {
        user.setEnabled(false);
        userRepository.save(user);

        String token = UUID.randomUUID().toString();
        // Save token to the database (omitted for brevity)
        
        sendVerificationEmail(user.getEmail(), token);
    }

    private void sendVerificationEmail(String email, String token) {
        String subject = "Email Verification";
        String verificationUrl = "http://localhost:8080/verify?token=" + token;
        String message = "Please click the following link to verify your email: " + verificationUrl;

        SimpleMailMessage emailMessage = new SimpleMailMessage();
        emailMessage.setTo(email);
        emailMessage.setSubject(subject);
        emailMessage.setText(message);
        mailSender.send(emailMessage);
    }
}

4. 创建注册控制器

创建一个 RegistrationController,处理用户注册请求。

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class RegistrationController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public String registerUser(@RequestBody User user) {
        userService.registerUser(user);
        return "Registration successful! Please check your email to verify your account.";
    }

    @GetMapping("/verify")
    public String verifyAccount(@RequestParam String token) {
        // Verification logic (omitted for brevity)
        return "Account verified successfully!";
    }
}

5. 配置安全设置

SecurityConfig 中配置 Spring Security,以允许注册和验证请求。

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/register", "/api/verify").permitAll()
                .anyRequest().authenticated()
            .and()
            .csrf().disable();

        return http.build();
    }
}

6. 编写 Thymeleaf 模板

创建一个简单的 Thymeleaf 模板,用于用户注册。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Register</title>
</head>
<body>
    <h1>Register</h1>
    <form action="#" th:action="@{/api/register}" th:object="${user}" method="post">
        <div>
            <label for="email">Email:</label>
            <input type="email" id="email" th:field="*{email}" />
        </div>
        <div>
            <label for="password">Password:</label>
            <input type="password" id="password" th:field="*{password}" />
        </div>
        <div>
            <button type="submit">Register</button>
        </div>
    </form>
</body>
</html>

结论

通过以上步骤,我们实现了一个简单的用户注册和邮箱验证功能。这只是一个基本的实现,实际项目中可能需要更多的错误处理和安全措施。希望这篇文章对你有所帮助,如果你有任何问题,请随时留言。

参考文献

  1. Spring Boot Reference Documentation
  2. Thymeleaf Documentation
  3. Spring Security Reference

希望这篇文章对你有帮助,如果有任何问题或需要进一步的说明,请随时与我联系。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/764092.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

智能技术【机器学习】总结

文章目录 第一部分 优化第二部分 模型第一章 神经网络&#xff08;MLP, BP, CNN, GNN, and Attention&#xff09;1.1 神经网络基础1.1.1 高次非线性函数1.1.2 感知器与神经网络1.1.3 联结主义模型1.1.4 动机——为什么每个人都在谈论深度学习&#xff1f;1.1.5 背景1.1.6 神经…

Keysight 是德 EXR104A 实时示波器

Keysight 是德 EXR104A 实时示波器 全部 4 个通道均可提供 1 GHz 的带宽&#xff0c;强大的 8 合 1 仪器&#xff0c;出色的硬件加速绘图功能&#xff0c;可以全面升级到 2.5 GHz 带宽和 8 个通道 全部 4 个模拟通道上均可提供 1 GHz 带宽通过 ASIC 技术实现更快的测试速度有…

项目范围管理(信息系统项目管理师)

需求管理计划是对项目的需求进行定义、确定、记载、核实管理和控制的行动指南。制定需求管理计划&#xff0c;规划如何分析、记录和管理需求&#xff0c;这样才是较为稳妥的方法在信息系统集成项目中&#xff0c;需求管理贯穿于整个过程&#xff0c;他的最基本的任务就是明确需…

破解电脑卡顿难题,将数据优化,5分钟提升运行速度

当电脑变得缓慢且反应迟钝时&#xff0c;工作效率和娱乐体验都会大打折扣。而电脑卡顿是由于系统资源占用过多、磁盘空间不足等原因引起的。因此&#xff0c;我们经常需要寻找优化措施&#xff0c;提升电脑的运行速度。文章整理了4个优化方法&#xff0c;帮助你破解卡顿难题&am…

Linux下编程之内存检查

前言 我们在进行编程时&#xff0c;有时不免会无意中写出一些容易导致内存问题&#xff08;可能一时表象上正常&#xff09;的代码&#xff0c;导致的后果肯定是不好的&#xff0c;就像一颗颗“哑弹”&#xff0c;令人心慌。网上推荐的辅助工具很多&#xff0c;此篇文章…

机器学习——强化学习中的“策略π”的个人思考

这两天回顾了《西瓜书》中的最后一章——“强化学习”&#xff0c;但是忽然发现之前对于本章中的“策略π”的理解有些偏差&#xff0c;导致我在看值函数公式时有些看不明白。对此&#xff0c;我在网上查了一些资料&#xff0c;但是大部分人都是一笔带过&#xff0c;或者是照本…

Day8: 232.用栈实现队列 225. 用队列实现栈 20. 有效的括号 1047. 删除字符串中的所有相邻重复项

题目232. 用栈实现队列 - 力扣&#xff08;LeetCode&#xff09; class MyQueue { public:MyQueue() {}void push(int x) { // 出栈input.push(x);}int pop() {// 如果出栈为空&#xff0c;把入栈元素全都转移到出栈if (output.empty()) {while (!input.empty()) {int itop i…

基于小波同步压缩变换与集成深度学习的情绪识别

摘要 本研究设计了一种基于小波同步压缩变换(WSST)驱动优化集成深度学习(DL)的自动多类情绪识别(AMER)系统&#xff0c;用于识别样本依赖(subject-dependent)和样本独立(subject-independent)两种模式下的人类情感。使用WSST方法将1-D脑电(EEG)信号转换为2-D时频表征(TFR)&…

2024年6月总结及随笔之打卡网红点

1. 回头看 日更坚持了547天。 读《人工智能时代与人类未来》更新完成读《AI未来进行式》开更并更新完成读《AI新生&#xff1a;破解人机共存密码》开更并持续更新 2023年至2024年6月底累计码字1267912字&#xff0c;累计日均码字2317字。 2024年6月码字90659字&#xff0c;…

hadoop分布式云笔记系统-计算机毕业设计源码15725

摘 要 随着信息技术的飞速发展&#xff0c;人们对于数据的存储、管理和共享需求日益增长。传统的集中式存储系统在处理大规模数据时面临着性能瓶颈和扩展性问题。而 Hadoop 作为一种分布式计算框架&#xff0c;为解决这些问题提供了有效的解决方案。 本研究旨在设计并实现一种…

昇思25天学习打卡营第6天|关于函数与神经网络梯度相关技术探讨

目录 Python 库及 MindSpore 相关模块和类的导入 函数与计算图 微分函数与梯度计算 Stop Gradient Auxiliary data 神经网络梯度计算 Python 库及 MindSpore 相关模块和类的导入 Python 中的 numpy 库被成功导入&#xff0c;并简称为 np。numpy 在科学计算领域应用广泛&#x…

2、SSD基本技术

发展史 上文中说SSD是以闪存为介质的存储设备&#xff0c;这只能算是现代SSD的特点&#xff0c;而不能算是定义。 HDD是磁存储&#xff0c;SSD是电存储&#xff1b;HDD的特点导致寻址到不同扇区其性能存在明显差异&#xff0c;比如寻址下个扇区和上个扇区&#xff1b;而SSD寻…

SpringBoot学习06-[SpringBoot与AOP、SpringBoot自定义starter]

SpringBoot自定义starter SpringBoot与AOP SpringBoot与AOP 使用AOP实现用户接口访问日志功能 添加AOP场景启动器 <!--添加AOP场景启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</…

第十四届蓝桥杯省赛C++A组F题【买瓜】题解(AC)

70pts 题目要求我们在给定的瓜中选择一些瓜&#xff0c;可以选择将瓜劈成两半&#xff0c;使得最后的总重量恰好等于 m m m。我们的目标是求出至少需要劈多少个瓜。 首先&#xff0c;我们注意到每个瓜的重量最多为 1 0 9 10^9 109&#xff0c;而求和的重量 m m m 也最多为…

3.2ui功能讲解之graph页面

本节重点介绍 : graph页面target页面flags页面status页面tsdb-status页面 访问地址 $ip:9090 graph页面 autocomplete 可以补全metrics tag信息或者 内置的关键字 &#xff0c;如sum聚合函数table查询 instante查询&#xff0c; 一个点的查询graph查询调整分辨率 resolutio…

中原汉族与北方游牧民族舞蹈文化在这段剧中表现得淋漓尽致,且看!

中原汉族与北方游牧民族舞蹈文化在这段剧中表现得淋漓尽致&#xff0c;且看&#xff01; 《神探狄仁杰》之使团喋血记是一部深入人心的历史侦探剧&#xff0c;不仅以其曲折离奇的案情和狄仁杰的睿智形象吸引观众&#xff0c;更以其对唐代文化的精准再现而备受赞誉。#李秘书讲写…

云计算【第一阶段(23)】Linux系统安全及应用

一、账号安全控制 1.1、账号安全基本措施 1.1.1、系统账号清理 将非登录用户的shell设为/sbin/nologin锁定长期不使用的账号删除无用的账号 1.1.1.1、实验1 用于匹配以/sbin/nologin结尾的字符串&#xff0c;$ 表示行的末尾。 &#xff08;一般是程序用户改为nologin&…

JavaScript——对象的创建

目录 任务描述 相关知识 对象的定义 对象字面量 通过关键字new创建对象 通过工厂方法创建对象 使用构造函数创建对象 使用原型(prototype)创建对象 编程要求 任务描述 本关任务&#xff1a;创建你的第一个 JavaScript 对象。 相关知识 JavaScript 是一种基于对象&a…

Spring Boot配置文件properties/yml/yaml

一、Spring Boot配置文件简介 &#xff08;1&#xff09;名字必须为application,否则无法识别。后缀有三种文件类型&#xff1a; properties/yml/yaml&#xff0c;但是yml和yaml使用方法相同 &#xff08;2&#xff09; Spring Boot 项⽬默认的配置文件为 properties &#xff…

kafka线上问题:rebalance

我是小米,一个喜欢分享技术的29岁程序员。如果你喜欢我的文章,欢迎关注我的微信公众号“软件求生”,获取更多技术干货! 大家好,我是小米。今天,我们来聊聊一个在大数据处理领域常见但又令人头疼的问题——Kafka消费组内的重平衡(rebalance)。这可是阿里巴巴面试中的经…
最新文章