1. 项目结构
2. 数据库操作
create database if not exists blog;
use blog;
CREATE TABLE if not exists users
(
id BIGINT AUTO_INCREMENT PRIMARY KEY, -- 用户的唯一标识符,自动递增的主键
email VARCHAR(100) NOT NULL UNIQUE, -- 电子邮件,不能为空且唯一,长度限制为100个字符
username VARCHAR(12) NOT NULL UNIQUE, -- 用户名,不能为空且唯一,长度限制为12个字符
password VARCHAR(255) NOT NULL, -- 用户密码,不能为空,存储为加密后的字符串
name VARCHAR(50), -- 用户显示名称,非必填,长度限制为50个字符
avatar_url VARCHAR(255), -- 用户头像的URL或文件路径,非必填,长度限制为255个字符
role VARCHAR(20) NOT NULL DEFAULT 'USER', -- 用户角色,不能为空,默认值为 'USER'
enabled BOOLEAN NOT NULL DEFAULT TRUE, -- 账户启用状态,不能为空,默认值为TRUE(启用)
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, -- 记录创建时间,默认值为当前时间戳
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP -- 记录最后更新时间,自动更新为当前时间戳
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_unicode_ci;
3. pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>info.liberx</groupId>
<artifactId>blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>eureka-server</module>
<module>gateway-service</module>
<module>article-service</module>
</modules>
<properties>
<java.version>8</java.version>
<spring-cloud.version>2023.0.3</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
说明:统一控制全局Spring Cloud版本和Spring Boot版本。
4. eureka-server 微服务
4.1 项目结构
4.2 pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>info.liberx</groupId>
<artifactId>blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>eureka-server</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
</dependencies>
</project>
4.3 application.yml
server:
port: 8761
spring:
application:
name: eureka-server
eureka:
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10
lease-expiration-duration-in-seconds: 30
client:
register-with-eureka: false
fetch-registry: false
server:
enable-self-preservation: true
renewal-threshold-update-interval-ms: 60000
4.4 EurekaServerApplication.java
package info.libex.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication(exclude = {LoadBalancerAutoConfiguration.class})
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
5. article-service 微服务
5.1 项目结构
5.2 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>info.liberx</groupId>
<artifactId>blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>article-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
</project>
5.3 application.yml
spring:
application:
name: article-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
register-with-eureka: true
fetch-registry: true
server:
port: 8002
5.4 ArticleServiceApplication.java
package info.liberx.articleservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ArticleServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ArticleServiceApplication.class, args);
}
}
5.5 ArticleController.java
package info.liberx.articleservice.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ArticleController {
@GetMapping("/article")
public String article() {
return "this is article service";
}
}
6. gateway-service
6.1 项目结构
6.2 pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>info.liberx</groupId>
<artifactId>blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>gateway-service</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
6.3 application.yml
spring:
application:
name: gateway-service
main:
web-application-type: reactive
allow-bean-definition-overriding: true
datasource:
url: jdbc:mysql://localhost:3306/blog?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
data:
redis:
port: 6379
host: 192.168.186.77
password: 123456
timeout: 10000
mail:
host: smtp.qq.com
port: 465
username: QQ邮箱
password: 邮箱验证码(生成的)
properties:
mail:
smtp:
auth: true
starttls:
enable: true
ssl:
enable: true
required: true
trust: smtp.qq.com
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
mime:
filetype:
map: classpath:mime.types
cloud:
gateway:
routes:
- id: gateway-service
uri: lb://gateway-service
predicates:
- Path=/auth/**
- id: user-service
uri: lb://gateway-service
predicates:
- Path=/user/**
- id: article-service
uri: lb://article-service
predicates:
- Path=/article/**
rabbitmq:
host: 192.168.186.77
port: 5672
username: admin
password: 123456
mybatis:
configuration:
map-underscore-to-camel-case: true
cache-enabled: true
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
jwt:
secret: abc
expiration: 60
register:
url: http://127.0.0.1:8001
server:
port: 8001
6.4 JwtUtils.java
package info.liberx.userservice.config;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@Component
public class JwtUtils {
private final String secretKey;
private final long expirationTime;
private final StringRedisTemplate redisTemplate;
@Autowired
public JwtUtils(StringRedisTemplate redisTemplate, @Value("${jwt.secret}") String secretKey, @Value("${jwt.expiration}") long expirationTime) {
this.redisTemplate = redisTemplate;
this.secretKey = secretKey;
this.expirationTime = expirationTime;
}
private Algorithm getAlgorithm() {
return Algorithm.HMAC256(secretKey);
}
// 生成token
public String generateToken(String username, String role) {
long expirationTimeInMillis = TimeUnit.MINUTES.toMillis(expirationTime); // 统一为分钟单位
String token = JWT.create()
.withSubject(username)
.withClaim("role", role)
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + expirationTimeInMillis))
.sign(getAlgorithm());
// 存储JWT到Redis,使用token作为键,设置与JWT过期时间一致的Redis过期时间
redisTemplate.opsForValue().set("jwt:" + token, "", expirationTime, TimeUnit.MINUTES);
return token;
}
// 验证token是否有效并返回用户名
public Optional<String> validateAndExtractUsername(String token) {
// 先检查token是否在黑名单中
if (isTokenRevoked(token)) {
return Optional.empty(); // Token已被撤销
}
try {
JWTVerifier verifier = JWT.require(getAlgorithm()).build();
DecodedJWT decodedJWT = verifier.verify(token);
return Optional.ofNullable(decodedJWT.getSubject());
} catch (JWTVerificationException exception) {
return Optional.empty();
}
}
// 从token中提取单一角色信息
public Optional<String> extractRole(String token) {
if (isTokenRevoked(token)) {
return Optional.empty(); // Token已被撤销
}
try {
JWTVerifier verifier = JWT.require(getAlgorithm()).build();
DecodedJWT decodedJWT = verifier.verify(token);
return Optional.ofNullable(decodedJWT.getClaim("role").asString()); // 提取单一角色
} catch (JWTVerificationException exception) {
return Optional.empty();
}
}
// 撤销token:将JWT令牌加入黑名单
public void revokeToken(String token) {
// 获取token的剩余有效期
long expirationTime = getExpirationTime(token);
long remainingTime = expirationTime - System.currentTimeMillis();
// 将token加入黑名单,并设置到期时间
if (remainingTime > 0) {
redisTemplate.opsForValue().set("blacklist:" + token, "revoked", remainingTime, TimeUnit.MILLISECONDS);
}
}
// 检查token是否在黑名单中
public boolean isTokenRevoked(String token) {
return Boolean.TRUE.equals(redisTemplate.hasKey("blacklist:" + token));
}
// 获取token的过期时间
public long getExpirationTime(String token) {
try {
JWTVerifier verifier = JWT.require(getAlgorithm()).build();
DecodedJWT decodedJWT = verifier.verify(token);
return decodedJWT.getExpiresAt().getTime();
} catch (JWTVerificationException exception) {
return 0;
}
}
// 存储Hash结构的数据到Redis并设置过期时间
public void storeHashWithExpiration(String key, Map<String, Object> data, long expirationTime, TimeUnit timeUnit) {
redisTemplate.opsForHash().putAll(key, data);
redisTemplate.expire(key, expirationTime, timeUnit);
}
// 从Redis中获取Hash结构的数据
public Map<Object, Object> getHash(String key) {
return redisTemplate.opsForHash().entries(key);
}
// 删除指定键的数据
public void deleteKey(String key) {
redisTemplate.delete(key);
}
// 检查键是否存在
public boolean hasKey(String key) {
return Boolean.TRUE.equals(redisTemplate.hasKey(key));
}
// 存储String类型的数据到Redis并设置过期时间(用于验证码)
public void storeStringWithExpiration(String key, String value, long expirationTime, TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, expirationTime, timeUnit);
}
// 从Redis中获取String类型的数据(用于获取验证码)
public String getString(String key) {
return redisTemplate.opsForValue().get(key);
}
}
6.5 RabbitMQConfig.java
package info.liberx.userservice.config;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
// 定义了一个常量表示邮件队列的名称
public static final String EMAIL_QUEUE = "emailQueue";
// 定义了一个常量表示允许反序列化的包,用于安全考虑
public static final String DESERIALIZATION_PACKAGE = "info.liberx.userservice.model";
/**
* 配置邮件队列。
*
* @return 一个持久化的队列对象。持久化的队列在RabbitMQ服务器重启后依然存在。
*/
@Bean
public Queue emailQueue() {
// 创建一个持久化的队列,队列名称为 EMAIL_QUEUE
return new Queue(EMAIL_QUEUE, true);
}
/**
* 配置 RabbitTemplate,这个模板类是 Spring 提供的与 RabbitMQ 交互的主要工具。
*
* @param connectionFactory 用于连接到 RabbitMQ 的连接工厂
* @return 配置了消息转换器的 RabbitTemplate 对象
*/
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
// 创建 RabbitTemplate 实例,并设置连接工厂
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
// 设置自定义的消息转换器,使用 JSON 格式转换消息
rabbitTemplate.setMessageConverter(messageConverter());
return rabbitTemplate;
}
/**
* 配置消息转换器,将消息转换为 JSON 格式进行发送和接收。
*
* @return 一个 Jackson2JsonMessageConverter 对象,负责消息的序列化和反序列化
*/
@Bean
public MessageConverter messageConverter() {
// 创建 Jackson2JsonMessageConverter,用于将消息转换为 JSON 格式
Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
// 配置 ClassMapper,指定允许反序列化的包,增强安全性
converter.setClassMapper(new DefaultClassMapper() {{
setTrustedPackages(DESERIALIZATION_PACKAGE);
}});
return converter;
}
}
6.6 AdministratorController.java
package info.liberx.userservice.controller;
import info.liberx.userservice.model.Vo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/admin")
public class AdministratorController {
@GetMapping
public ResponseEntity<Vo<Void>> csrfToken() {
return ResponseEntity.ok(new Vo<>(200,"欢迎您超级管理员!",null));
}
}
6.7 AuthController.java
package info.liberx.userservice.controller;
import info.liberx.userservice.model.User;
import info.liberx.userservice.model.UserVo;
import info.liberx.userservice.model.Vo;
import info.liberx.userservice.service.AuthService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import java.time.Duration;
@RestController
@RequestMapping("/auth")
public class AuthController {
private final AuthService authService;
@Autowired
public AuthController(AuthService authService) {
this.authService = authService;
}
// 1. 用户注册
@PostMapping("/register")
public ResponseEntity<Vo<Void>> registerUser(@Valid @RequestBody User user) {
try {
authService.registerUser(user);
return ResponseEntity.ok(new Vo<>(200, "注册成功,请检查您的邮箱进行验证。", null));
} catch (Exception e) {
return ResponseEntity.status(400).body(new Vo<>(400, e.getMessage(), null));
}
}
// 2. 用户激活
@GetMapping("/verify")
public ResponseEntity<Vo<Void>> activateUser(@RequestParam("token") String token) {
boolean activated = authService.activateUser(token);
if (activated) {
return ResponseEntity.ok(new Vo<>(200, "账户激活成功。", null));
} else {
return ResponseEntity.status(400).body(new Vo<>(400, "无效或过期的激活链接。", null));
}
}
// 3. 发送登录验证码
@PostMapping("/send-login-code")
public Mono<ResponseEntity<Vo<Void>>> sendLoginCode(@RequestBody UserVo vo) {
return Mono.fromCallable(() -> {
try {
authService.sendLoginCode(vo.getEmail());
return ResponseEntity.ok(new Vo<>(200, "登录验证码已发送,请检查您的邮箱。", null));
} catch (Exception e) {
return ResponseEntity.status(400)
.body(new Vo<>(400, e.getMessage(), null));
}
});
}
// 4. 用户登录并设置Cookie
@PostMapping("/login")
public Mono<ResponseEntity<Vo<Void>>> loginUser(@RequestBody UserVo vo) {
return authService.loginUser(vo)
.flatMap(token -> {
if (token != null) {
// 设置 JWT Cookie
ResponseCookie jwtCookie = ResponseCookie.from("jwt", token)
.httpOnly(true) // 防止 XSS 攻击
.secure(false) // 如果启用 HTTPS,改为 true
.path("/")
.maxAge(Duration.ofDays(7))
.sameSite("Strict") // 防止跨站请求
.build();
return Mono.just(ResponseEntity.ok()
.header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
.body(new Vo<Void>(200, "登录成功!", null)));
} else {
return Mono.just(ResponseEntity.status(401)
.body(new Vo<Void>(401, "登录失败!", null)));
}
})
.onErrorResume(e -> Mono.just(ResponseEntity.status(401)
.body(new Vo<>(401, "登录失败!", null))));
}
// 5. 用户退出登录
@PostMapping("/logout")
public ResponseEntity<Vo<String>> logoutUser(@CookieValue("jwt") String token) {
try {
authService.logout(token);
return ResponseEntity.ok(new Vo<>(200, "注销成功。", null));
} catch (Exception e) {
return ResponseEntity.status(400).body(new Vo<>(400, "注销失败。", e.getMessage()));
}
}
// 6. 忘记密码:发送重置密码验证码
@PostMapping("/forgot-password")
public Mono<ResponseEntity<Vo<Void>>> sendResetPasswordCode(@RequestBody UserVo vo) {
return Mono.fromCallable(() -> {
authService.sendResetPasswordCode(vo.getEmail());
return ResponseEntity.ok(new Vo<Void>(200, "验证码已发送,请检查您的邮箱。", null));
})
.onErrorResume(e -> Mono.just(ResponseEntity.status(400)
.body(new Vo<>(400,e.getMessage(), null))));
}
// 7. 验证验证码并重置密码
@PostMapping("/reset-password")
public ResponseEntity<Vo<Void>> resetPassword(@RequestBody UserVo vo) {
boolean success = authService.resetPassword(vo.getEmail(), vo.getCode(), vo.getPassword());
if (success) {
return ResponseEntity.ok(new Vo<>(200, "密码重置成功。", null));
} else {
return ResponseEntity.status(400).body(new Vo<>(400, "验证码无效或已过期。", null));
}
}
}
6.8 UserController.java
package info.liberx.userservice.controller;
import com.github.pagehelper.PageInfo;
import info.liberx.userservice.model.User;
import info.liberx.userservice.model.Vo;
import info.liberx.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
@Autowired
UserController(UserService userService){
this.userService=userService;
}
// 动态更新用户信息
@PutMapping
public ResponseEntity<Vo<Void>> updateUser(@RequestBody User user) {
int rows = userService.updateUser(user);
if (rows > 0) {
return new ResponseEntity<>(new Vo<>(200, "更新成功", null), HttpStatus.OK);
} else {
return new ResponseEntity<>(new Vo<>(404, "更新失败", null), HttpStatus.NOT_MODIFIED);
}
}
// 删除用户
@DeleteMapping("/{id}")
public ResponseEntity<Vo<Void>> deleteUser(@PathVariable Long id) {
int rows = userService.deleteUserById(id);
if (rows > 0) {
return new ResponseEntity<>(new Vo<>(200, "删除成功", null), HttpStatus.OK);
} else {
return new ResponseEntity<>(new Vo<>(404, "删除失败", null), HttpStatus.NOT_FOUND);
}
}
// 分页查询所有用户
@GetMapping
public ResponseEntity<Vo<PageInfo<User>>> findAllUsers(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
PageInfo<User> users = userService.findAllUsers(pageNum, pageSize);
return new ResponseEntity<>(new Vo<>(200, "查询成功", users), HttpStatus.OK);
}
}
6.9 RateLimiterWebFilter.java
package info.liberx.userservice.filter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import info.liberx.userservice.model.Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.logging.Logger;
/**
* RateLimiterWebFilter 是一个基于令牌桶算法的速率限制过滤器。
* 每个 IP 在 1 分钟内最多允许 10 次请求。
* 它使用 Redis 存储令牌数量和上次请求的时间戳,以保证在分布式环境中的速率限制的一致性。
*/
@Component
public class RateLimiterWebFilter implements WebFilter {
private static final int MAX_TOKENS = 10; // 每分钟的最大令牌数
private static final int REFILL_RATE = 1; // 每分钟补充的令牌数
private static final int WINDOW_DURATION = 60; // 时间窗口大小(以秒为单位)
private static final Logger logger = Logger.getLogger(RateLimiterWebFilter.class.getName());
private final ReactiveRedisTemplate<String, String> redisTemplate;
private final ObjectMapper objectMapper = new ObjectMapper();
/**
* 构造函数,用于注入 ReactiveRedisTemplate 以便与 Redis 交互。
*
* @param redisTemplate 用于操作 Redis 的模板类
*/
@Autowired
public RateLimiterWebFilter(ReactiveRedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 过滤器方法,用于检查请求是否超过了速率限制。
*
* @param exchange 当前的 ServerWebExchange,代表一个 HTTP 请求-响应交换
* @param chain WebFilterChain,表示过滤器链
* @return 一个 Mono<Void>,表示过滤器的执行结果
*/
@NonNull
@Override
public Mono<Void> filter(@NonNull ServerWebExchange exchange, @NonNull WebFilterChain chain) {
// 从请求中获取客户端的 IP 地址
String ip = Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress();
// 获取请求的路径
String path = exchange.getRequest().getURI().getPath();
// 根据 IP 和请求路径生成唯一的速率限制键
String key = ip + ":" + path;
// 调用 handleRateLimiting 方法处理速率限制逻辑
return handleRateLimiting(key)
.flatMap(allowed -> {
if (allowed) {
// 如果请求未超过速率限制,继续处理请求
return chain.filter(exchange);
} else {
// 如果请求超过了速率限制,返回 HTTP 429 状态码(Too Many Requests)
return handleRateLimitExceeded(exchange);
}
});
}
private Mono<Void> handleRateLimitExceeded(ServerWebExchange exchange) {
try {
String json = objectMapper.writeValueAsString(new Vo<>(429, "您发送的请求过多,请稍后再试。", null));
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(json.getBytes());
return exchange.getResponse().writeWith(Mono.just(buffer));
} catch (JsonProcessingException e) {
return Mono.error(e);
}
}
/**
* 处理速率限制的核心逻辑,基于令牌桶算法。
*
* @param key 用于速率限制的 Redis 键,通常是 IP 地址和请求路径的组合
* @return 一个 Mono<Boolean>,表示请求是否被允许
*/
private Mono<Boolean> handleRateLimiting(String key) {
// Redis 中存储令牌数量的键
String tokensKey = key + ":tokens";
// Redis 中存储上次请求时间戳的键
String timestampKey = key + ":timestamp";
// 获取当前时间的 Unix 时间戳(秒)
long now = Instant.now().getEpochSecond();
// 从 Redis 中获取上次请求的时间戳
return redisTemplate.opsForValue().get(timestampKey)
.defaultIfEmpty(String.valueOf(now))
.flatMap(lastTimeStr -> {
long lastTime = Long.parseLong(lastTimeStr);
// 计算自上次请求以来经过的时间(秒)
long elapsedTime = now - lastTime;
// 根据经过的时间计算需要补充的令牌数量
long tokensToAdd = elapsedTime / WINDOW_DURATION * REFILL_RATE;
// 从 Redis 中获取当前的令牌数量
return redisTemplate.opsForValue().get(tokensKey)
.defaultIfEmpty(String.valueOf(MAX_TOKENS)) // 如果没有找到令牌,则初始化为最大令牌数
.flatMap(tokensStr -> {
long currentTokens = Long.parseLong(tokensStr);
// 计算补充后的令牌数量,不能超过 MAX_TOKENS
long newTokens = Math.min(currentTokens + tokensToAdd, MAX_TOKENS);
if (newTokens > 0) {
// 如果令牌充足,消耗一个令牌并允许请求
logger.info("当前-" + Thread.currentThread().getName() + " -" + key + "-剩余令牌:" + currentTokens);
return redisTemplate.opsForValue().set(tokensKey, String.valueOf(newTokens - 1))
.and(redisTemplate.opsForValue().set(timestampKey, String.valueOf(now)))
.and(redisTemplate.expire(tokensKey, Duration.ofSeconds(WINDOW_DURATION)))
.and(redisTemplate.expire(timestampKey, Duration.ofSeconds(WINDOW_DURATION)))
.thenReturn(true);
} else {
// 如果令牌不足,拒绝请求
return redisTemplate.opsForValue().set(timestampKey, String.valueOf(now))
.and(redisTemplate.expire(tokensKey, Duration.ofSeconds(WINDOW_DURATION)))
.and(redisTemplate.expire(timestampKey, Duration.ofSeconds(WINDOW_DURATION)))
.thenReturn(false);
}
});
});
}
}
6.10 AuthMapper.java
package info.liberx.userservice.mapper;
import info.liberx.userservice.model.User;
import org.apache.ibatis.annotations.*;
import java.util.Optional;
@Mapper
public interface AuthMapper {
// 插入新用户
@Insert("INSERT INTO users(email, username, password, name, avatar_url) VALUES(#{email}, #{username}, #{password}, #{name}, #{avatarUrl})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insertUser(User user); // 返回插入的行数或生成的主键
//根据邮箱或用户名查找用户
@Select("SELECT * FROM users WHERE email = #{email} OR username = #{username}")
Optional<User> findUserByUsernameOrEmail(@Param("username") String username, @Param("email") String email); // 返回 Optional
// 动态更新用户信息
@UpdateProvider(type = UserSqlProvider.class, method = "updateUserSql")
void updateUser(User user); // 返回更新的行数
}
6.11 UserMapper.java
package info.liberx.userservice.mapper;
import info.liberx.userservice.model.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
// 动态更新用户信息
@UpdateProvider(type = UserSqlProvider.class, method = "updateUserSql")
int updateUser(User user); // 返回更新的行数
// 删除用户
@Delete("DELETE FROM users WHERE id = #{id}")
int deleteUserById(@Param("id") Long id); // 返回删除的行数
// 查询所有用户(分页)
@Select("SELECT * FROM users")
List<User> findAllUsers(); // 返回用户列表
}
6.12 UserSqlProvider.java
package info.liberx.userservice.mapper;
import info.liberx.userservice.model.User;
import org.apache.ibatis.jdbc.SQL;
public class UserSqlProvider {
public String updateUserSql(User user) {
return new SQL() {{
UPDATE("users");
if (user.getEmail() != null) {
SET("email = #{email}");
}
if (user.getUsername() != null) {
SET("username = #{username}");
}
if (user.getPassword() != null) {
SET("password = #{password}");
}
if (user.getName() != null) {
SET("name = #{name}");
}
if (user.getAvatarUrl() != null) {
SET("avatar_url = #{avatarUrl}");
}
if (user.getRole() != null) {
SET("role = #{role}");
}
if (user.getEnabled() != null) {
SET("enabled = #{enabled}");
}
SET("updated_at = #{updatedAt}");
WHERE("id = #{id}");
}}.toString();
}
}
6.13 EmailMessage.java
package info.liberx.userservice.model;
import lombok.Data;
import java.io.Serializable;
@Data
public class EmailMessage implements Serializable {
private String to;
private String subject;
private EmailType emailType;
private String tokenOrCode;
public EmailMessage(String to, EmailType emailType, String tokenOrCode) {
this.to = to;
this.emailType = emailType;
this.tokenOrCode = tokenOrCode;
this.subject = emailType.getSubject();
}
}
6.14 EmailType.java
package info.liberx.userservice.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public enum EmailType {
VERIFICATION_EMAIL("邮箱验证", "verification_email", "token"),
LOGIN_CODE("您的验证码", "login_code", "code"),
RESET_PASSWORD_CODE("密码重置验证码", "reset_password_code.html", "code"),
RESET_PASSWORD_CONFIRMATION("密码重置确认", "reset_password_confirmation", null);
private final String subject;
private final String templateName;
private final String variableName;
}
6.15 User.java
package info.liberx.userservice.model;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class User {
private Long id;
@NotBlank(message = "Username is required")
@Size(min = 6, max = 12, message = "Username must be between 6 and 12 characters")
private String username;
@NotBlank(message = "Password is required")
@Size(min = 8, message = "Password must be at least 8 characters long")
private String password;
@NotBlank(message = "Email is required")
@Email(message = "Email should be valid")
private String email;
private String role = "USER";
private Boolean enabled;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@Size(max = 50, message = "Name must be less than 50 characters")
private String name;
@Size(max = 255, message = "Avatar URL must be less than 255 characters")
private String avatarUrl;
}
6.16 UserVo.java
package info.liberx.userservice.model;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class UserVo {
@NotBlank(message = "Username is required")
@Size(min = 6, max = 12, message = "Username must be between 6 and 12 characters")
private String username;
@NotBlank(message = "Password is required")
@Size(min = 8, message = "Password must be at least 8 characters long")
private String password;
@NotBlank(message = "Email is required")
@Email(message = "Email should be valid")
private String email;
String code;
}
6.17 Vo.java
package info.liberx.userservice.model;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Vo<T> {
private Integer status;
private String message;
private String csrfToken;
private T data;
public Vo(Integer status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
}
6.18 CookieJwtConverter.java
package info.liberx.userservice.security;
import info.liberx.userservice.config.JwtUtils;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Optional;
@Component
public class CookieJwtConverter implements ServerAuthenticationConverter {
// JwtUtils 是一个用于处理 JWT 的工具类,用于验证和解析 JWT 令牌
private final JwtUtils jwtUtils;
public CookieJwtConverter(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}
/**
* 从 ServerWebExchange 中提取 JWT 令牌,并基于该令牌构建 Authentication 对象。
*
* @param exchange ServerWebExchange,包含当前 HTTP 请求和响应
* @return 如果 JWT 有效,返回包含身份信息的 Mono<Authentication>;否则返回 Mono.empty()
*/
@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
// 从请求中提取 JWT 令牌
String token = extractToken(exchange);
if (token == null || token.isEmpty()) {
// 如果没有找到令牌,返回空的 Mono 表示没有身份验证信息
return Mono.empty();
}
// 验证 JWT 令牌并提取用户名和角色
Optional<String> usernameOpt = jwtUtils.validateAndExtractUsername(token);
Optional<String> roleOpt = jwtUtils.extractRole(token);
// 如果提取到用户名和角色,创建 Authentication 对象
if (usernameOpt.isPresent() && roleOpt.isPresent()) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(usernameOpt.get(), null, AuthorityUtils.createAuthorityList(roleOpt.get()));
// 返回包含身份验证信息的 Mono
return Mono.just(authentication);
}
// 如果验证失败或没有提取到有效信息,返回空的 Mono
return Mono.empty();
}
/**
* 从请求的 Cookie 中提取 JWT 令牌。
*
* @param exchange ServerWebExchange,包含当前 HTTP 请求和响应
* @return 如果 Cookie 中存在 JWT 令牌,返回令牌字符串;否则返回 null
*/
private String extractToken(ServerWebExchange exchange) {
// 从 ServerWebExchange 中获取 HTTP 请求
ServerHttpRequest request = exchange.getRequest();
// 从请求的 Cookie 中获取名为 "jwt" 的 Cookie
HttpCookie cookie = request.getCookies().getFirst("jwt");
// 如果找到了该 Cookie,返回其值(即 JWT 令牌);否则返回 null
return cookie != null ? cookie.getValue() : null;
}
}
6.19 ReactiveSecurityConfig.java
package info.liberx.userservice.security;
import info.liberx.userservice.service.ReactiveUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class ReactiveSecurityConfig {
// 注入 ReactiveUserService,提供用户详情服务
private final ReactiveUserService reactiveUserService;
@Autowired
public ReactiveSecurityConfig(ReactiveUserService reactiveUserService) {
this.reactiveUserService = reactiveUserService;
}
/**
* 配置密码编码器 Bean。
*
* @return PasswordEncoder,用于对密码进行编码和匹配,使用 BCrypt 算法
*/
@Bean
public PasswordEncoder passwordEncoder() {
// 使用 BCryptPasswordEncoder 作为密码编码器
return new BCryptPasswordEncoder();
}
/**
* 配置反应式身份验证管理器 Bean。
*
* @return ReactiveAuthenticationManager,管理用户身份验证的组件
*/
@Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager() {
// 使用 ReactiveUserService 作为用户详情服务来构建身份验证管理器
UserDetailsRepositoryReactiveAuthenticationManager authenticationManager =
new UserDetailsRepositoryReactiveAuthenticationManager(reactiveUserService);
// 设置密码编码器,确保身份验证时使用相同的编码策略
authenticationManager.setPasswordEncoder(passwordEncoder());
return authenticationManager;
}
}
6.20 SecurityConfig.java
package info.liberx.userservice.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import info.liberx.userservice.model.Vo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
// 用于从 Cookie 中提取 JWT 并进行身份验证的转换器
private final CookieJwtConverter cookieJwtConverter;
// 用于将 Java 对象转换为 JSON 字符串的工具
private final ObjectMapper objectMapper = new ObjectMapper();
public SecurityConfig(CookieJwtConverter cookieJwtConverter) {
this.cookieJwtConverter = cookieJwtConverter;
}
/**
* 自定义身份验证入口点处理器,当用户未认证时返回 401 未授权响应。
*/
ServerAuthenticationEntryPoint authenticationEntryPoint = (exchange, ex) -> {
Vo<Object> responseVo = new Vo<>(401, "访问此资源需要身份验证。", null);
return writeResponse(exchange, HttpStatus.UNAUTHORIZED, responseVo);
};
/**
* 自定义访问被拒绝处理器,当用户无权限访问资源时返回 403 禁止访问响应。
*/
ServerAccessDeniedHandler accessDeniedHandler = (exchange, denied) -> {
Vo<Object> responseVo = new Vo<>(403, "您没有权限访问此资源。", null);
return writeResponse(exchange, HttpStatus.FORBIDDEN, responseVo);
};
/**
* 将响应写入到 HTTP 响应中,包括状态码和 JSON 格式的响应体。
*/
private Mono<Void> writeResponse(ServerWebExchange exchange, HttpStatus status, Vo<Object> responseVo) {
try {
// 将响应对象转换为 JSON 字符串
String json = objectMapper.writeValueAsString(responseVo);
exchange.getResponse().setStatusCode(status);
exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
// 将 JSON 数据写入响应中
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(json.getBytes());
return exchange.getResponse().writeWith(Mono.just(buffer));
} catch (Exception e) {
return Mono.error(e);
}
}
/**
* 配置 Spring Security 的反应式安全过滤链。
*
* @param http ServerHttpSecurity 对象,用于配置安全性
* @param jwtAuthenticationManager 自定义的 JWT 认证管理器
* @return 配置好的 SecurityWebFilterChain
*/
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http, ReactiveAuthenticationManager jwtAuthenticationManager) {
// 创建 JWT 身份验证过滤器
AuthenticationWebFilter jwtAuthenticationWebFilter = new AuthenticationWebFilter(jwtAuthenticationManager);
jwtAuthenticationWebFilter.setServerAuthenticationConverter(cookieJwtConverter);
// 配置安全过滤链
http.csrf(ServerHttpSecurity.CsrfSpec::disable) // 禁用 CSRF 防护
.formLogin(ServerHttpSecurity.FormLoginSpec::disable) // 禁用表单登录
.httpBasic(ServerHttpSecurity.HttpBasicSpec::disable) // 禁用 HTTP Basic 认证
.addFilterBefore(jwtAuthenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION) // 在认证之前添加 JWT 过滤器
.authorizeExchange(exchange -> exchange
.pathMatchers("/auth/**","/index").permitAll() // 公开访问的路径
.pathMatchers("/admin/**").hasRole("ADMIN") // 仅管理员可访问的路径
.pathMatchers("/user/**","/article").hasAnyRole("USER", "ADMIN") // 用户和管理员都可以访问的路径
.anyExchange().authenticated() // 其他所有路径都需要身份验证
)
.exceptionHandling(exceptionHandlingSpec -> exceptionHandlingSpec
.accessDeniedHandler(accessDeniedHandler) // 配置无权限访问处理器
.authenticationEntryPoint(authenticationEntryPoint) // 配置未认证访问处理器
);
return http.build();
}
/**
* 配置 JWT 认证管理器,用于从 JWT 中解析用户信息并进行身份验证。
*
* @return ReactiveAuthenticationManager 实例
*/
@Bean
@Primary
public ReactiveAuthenticationManager jwtAuthenticationManager() {
return Mono::just;
}
}
6.21 AuthService.java
package info.liberx.userservice.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import info.liberx.userservice.config.JwtUtils;
import info.liberx.userservice.mapper.AuthMapper;
import info.liberx.userservice.model.User;
import info.liberx.userservice.model.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Service
public class AuthService {
private final AuthMapper authMapper;
private final PasswordEncoder passwordEncoder;
private final JwtUtils jwtUtils;
private final EmailProducerService emailService;
private final ObjectMapper objectMapper;
private final ReactiveAuthenticationManager reactiveAuthenticationManager;
@Autowired
public AuthService(AuthMapper authMapper, PasswordEncoder passwordEncoder,
JwtUtils jwtUtils, EmailProducerService emailService,
ObjectMapper objectMapper, @Qualifier("reactiveAuthenticationManager") ReactiveAuthenticationManager reactiveAuthenticationManager) {
this.authMapper = authMapper;
this.passwordEncoder = passwordEncoder;
this.jwtUtils = jwtUtils;
this.emailService = emailService;
this.objectMapper = objectMapper;
this.reactiveAuthenticationManager = reactiveAuthenticationManager;
}
// 获取用户逻辑(通过用户名或邮箱进行获取)
private User getUserByEmailOrThrow(String identifier) {
Optional<User> user = authMapper.findUserByUsernameOrEmail(identifier,identifier);
if (!user.isPresent()) {
throw new RuntimeException(identifier+"不存在!");
}
return user.orElse(null);
}
// 1. 用户注册
public void registerUser(User user) {
// 1. 检查 Redis 缓存中是否存在用户名
String key = "pending_user:" + user.getUsername();
if (jwtUtils.hasKey(key)) {
throw new RuntimeException("注册验证已发送,请检查您的邮箱。");
}
// 2. 检查数据库中是否存在该用户名或邮箱
Optional<User> existingUser = authMapper.findUserByUsernameOrEmail(user.getUsername(), user.getEmail());
if (existingUser.isPresent()) {
if (existingUser.get().getUsername().equals(user.getUsername())) {
throw new RuntimeException("用户名已存在,请选择其他用户名。");
}
if (existingUser.get().getEmail().equals(user.getEmail())) {
throw new RuntimeException("邮箱已存在,请选择其他邮箱。");
}
}
// 3. 如果用户名和邮箱不存在,继续注册流程
user.setPassword(passwordEncoder.encode(user.getPassword())); // 加密密码
user.setCreatedAt(LocalDateTime.now()); // 设置创建日期
String token = jwtUtils.generateToken(user.getUsername(), null); // 生成验证用的token
// 4. 将用户信息转换为 Map 并存储到 Redis 缓存,设置 5 分钟有效期
Map<String, Object> userMap = objectMapper.convertValue(user, new TypeReference<Map<String, Object>>() {});
jwtUtils.storeHashWithExpiration(key, userMap, 5, TimeUnit.MINUTES);
// 5. 发送验证邮件
emailService.sendVerificationEmail(user.getEmail(), token);
}
// 2. 用户激活
public boolean activateUser(String token) {
Optional<String> username = jwtUtils.validateAndExtractUsername(token); // 同时验证Token和提取用户名
if (!username.isPresent()) {
return false; // Token无效或验证失败
}
String key = "pending_user:" + username.get();
if (jwtUtils.hasKey(key)) {
Map<Object, Object> userMap = jwtUtils.getHash(key); // 从缓存拿取用户数据
User user = objectMapper.convertValue(userMap, User.class); // 将map转换为用户实体
user.setEnabled(true);
authMapper.insertUser(user); // 插入到数据库
jwtUtils.deleteKey(key); // 删除用户数据
jwtUtils.revokeToken(token);
return true;
} else {
return false; // 用户数据不存在,可能Token已经失效或用户未注册
}
}
// 3. 发送登录验证码
public void sendLoginCode(String email) {
getUserByEmailOrThrow(email); // 验证邮箱是否存在
String key = "login_code:" + email; // 生成 Redis 中存储验证码的键
String existingCode = jwtUtils.getString(key); // 检查是否存在有效的验证码
if (existingCode != null) {
throw new RuntimeException("验证码已发送,请5分钟后再尝试");
}
String code = String.format("%06d", new Random().nextInt(1000000)); // 生成新验证码
jwtUtils.storeStringWithExpiration(key, code, 5, TimeUnit.MINUTES); // 存储验证码并设置过期时间为5分钟
// 发送验证码到用户邮箱
emailService.sendLoginCodeEmail(email,code);
}
// 4. 用户登录并生成JWT令牌
public Mono<String> loginUser(UserVo vo) {
return Mono.defer(() -> {
User user = getUserByEmailOrThrow(vo.getUsername());
String key = "login_code:" + user.getEmail();
String storedCode = jwtUtils.getString(key);
if (storedCode != null && storedCode.equals(vo.getCode())) {
Authentication authenticationToken = new UsernamePasswordAuthenticationToken(vo.getUsername(), vo.getPassword());
return reactiveAuthenticationManager.authenticate(authenticationToken)
.flatMap(authenticate -> {
jwtUtils.deleteKey(key); // 认证成功,删除验证码
String username = authenticate.getName();
String role = authenticate.getAuthorities().iterator().next().getAuthority();
return Mono.just(jwtUtils.generateToken(username, role)); // 生成并返回JWT令牌
}).onErrorResume(AuthenticationException.class, e -> Mono.error(new RuntimeException("认证失败", e)));
} else {
return Mono.error(new RuntimeException("无效的验证码或验证码已过期"));
}
});
}
// 5. 用户退出登录
public void logout(String token) {
if(jwtUtils.validateAndExtractUsername(token).isPresent())
jwtUtils.revokeToken(token);
else throw new RuntimeException("您还没有进行身份认证。");
}
// 6. 忘记密码:发送重置密码验证码
public void sendResetPasswordCode(String email) {
getUserByEmailOrThrow(email); // 验证邮箱是否存在
String key = "reset_password_code.html:" + email; // 生成 Redis 中存储重置密码验证码的键
String existingCode = jwtUtils.getString(key); // 检查是否存在有效的验证码
if (existingCode != null) {
throw new RuntimeException("重置密码验证码已发送,请5分钟后再尝试");
}
String code = String.format("%06d", new Random().nextInt(1000000));// 生成新验证码
jwtUtils.storeStringWithExpiration(key, code, 5, TimeUnit.MINUTES); // 存储验证码并设置过期时间为5分钟
// 发送验证码到用户邮箱
emailService.sendResetPasswordCodeEmail(email,code);
}
// 7. 验证验证码并重置密码
public boolean resetPassword(String email, String code, String password) {
String key = "reset_password_code.html:" + email;
String storedCode = jwtUtils.getString(key);
if (storedCode != null && storedCode.equals(code)) {
User user = getUserByEmailOrThrow(email);
user.setPassword(passwordEncoder.encode(password));
authMapper.updateUser(user);
emailService.sendResetPasswordConfirmationEmail(email);
jwtUtils.deleteKey(key);
return true;
} else {
return false; // 验证码无效或已过期
}
}
}
6.22 EmailConsumerService.java
package info.liberx.userservice.service;
import info.liberx.userservice.config.RabbitMQConfig;
import info.liberx.userservice.model.EmailMessage;
import info.liberx.userservice.model.EmailType;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringWebFluxTemplateEngine;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
@Service
public class EmailConsumerService {
private final JavaMailSender mailSender;
private final SpringWebFluxTemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String fromEmail;
@Value("${register.url}")
private String url;
@Autowired
public EmailConsumerService(JavaMailSender mailSender, SpringWebFluxTemplateEngine templateEngine) {
this.mailSender = mailSender;
this.templateEngine = templateEngine;
}
@RabbitListener(queues = RabbitMQConfig.EMAIL_QUEUE)
public void processEmailQueue(EmailMessage emailMessage) throws MessagingException {
Map<String, Object> variables = new HashMap<>();
EmailType emailType = emailMessage.getEmailType();
if (emailType.getVariableName() != null) {
if ("token".equals(emailType.getVariableName())) {
variables.put("verificationUrl", url + "/auth/verify?token=" + emailMessage.getTokenOrCode());
}else{
variables.put("code", emailMessage.getTokenOrCode());
}
}
Context context = new Context();
context.setVariables(variables);
String content = templateEngine.process(emailType.getTemplateName(), context);
sendEmail(emailMessage.getTo(), emailMessage.getSubject(), content);
}
private void sendEmail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setTo(to);
try {
helper.setFrom(new InternetAddress(fromEmail, "Some-Blog", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
}
}
6.23 EmailProducerService.java
package info.liberx.userservice.service;
import info.liberx.userservice.config.RabbitMQConfig;
import info.liberx.userservice.model.EmailMessage;
import info.liberx.userservice.model.EmailType;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmailProducerService {
private final RabbitTemplate rabbitTemplate;
@Autowired
public EmailProducerService(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
// 发送邮箱验证邮件
public void sendVerificationEmail(String to, String token) {
EmailMessage message = new EmailMessage(to, EmailType.VERIFICATION_EMAIL, token);
rabbitTemplate.convertAndSend(RabbitMQConfig.EMAIL_QUEUE, message);
}
// 发送登录验证码邮件
public void sendLoginCodeEmail(String to, String code) {
EmailMessage message = new EmailMessage(to, EmailType.LOGIN_CODE, code);
rabbitTemplate.convertAndSend(RabbitMQConfig.EMAIL_QUEUE, message);
}
// 发送密码重置验证码邮件
public void sendResetPasswordCodeEmail(String to, String code) {
EmailMessage message = new EmailMessage(to, EmailType.RESET_PASSWORD_CODE, code);
rabbitTemplate.convertAndSend(RabbitMQConfig.EMAIL_QUEUE, message);
}
// 发送密码重置确认邮件
public void sendResetPasswordConfirmationEmail(String to) {
EmailMessage message = new EmailMessage(to, EmailType.RESET_PASSWORD_CONFIRMATION, null);
rabbitTemplate.convertAndSend(RabbitMQConfig.EMAIL_QUEUE, message);
}
}
6.24 ReactiveUserService.java
package info.liberx.userservice.service;
import info.liberx.userservice.mapper.AuthMapper;
import info.liberx.userservice.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class ReactiveUserService implements ReactiveUserDetailsService {
private final AuthMapper authMapper;
@Autowired
public ReactiveUserService(AuthMapper AuthMapper) {
this.authMapper = AuthMapper;
}
private Mono<User> getUserByEmailOrThrow(String identifier) {
return Mono.defer(() -> Mono.justOrEmpty(authMapper.findUserByUsernameOrEmail(identifier,identifier))
.switchIfEmpty(Mono.error(new UsernameNotFoundException(identifier+"不存在"))));
}
@Override
public Mono<UserDetails> findByUsername(String identifier) {
return getUserByEmailOrThrow(identifier)
.map(user -> org.springframework.security.core.userdetails.User
.withUsername(user.getUsername())
.password(user.getPassword())
.authorities(AuthorityUtils.createAuthorityList("ROLE_"+user.getRole()))
.accountExpired(false)
.accountLocked(false)
.credentialsExpired(false)
.disabled(!user.getEnabled())
.build());
}
}
6.25 UserService.java
package info.liberx.userservice.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import info.liberx.userservice.mapper.UserMapper;
import info.liberx.userservice.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
private final PasswordEncoder passwordEncoder;
private final UserMapper userMapper;
@Autowired
UserService(UserMapper userMapper,PasswordEncoder passwordEncoder) {
this.userMapper = userMapper;
this.passwordEncoder=passwordEncoder;
}
public int updateUser(User user) {
if(user.getPassword()!=null) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
return userMapper.updateUser(user);
}
public int deleteUserById(Long id) {
return userMapper.deleteUserById(id);
}
public PageInfo<User> findAllUsers(int pageNum, int pageSize) {
// 设置分页参数
PageHelper.startPage(pageNum, pageSize);
// 查询所有用户
List<User> users = userMapper.findAllUsers();
// 返回分页后的数据
return new PageInfo<>(users);
}
}
6.26 UserServiceApplication.java
package info.liberx.userservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration;
@SpringBootApplication(exclude = {LoadBalancerAutoConfiguration.class, LoadBalancerBeanPostProcessorAutoConfiguration.class})
@EnableDiscoveryClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
6.27 login_code.html
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>您的验证码</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
body {
font-family: 'Roboto', Arial, Helvetica, sans-serif;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.85), rgba(240, 240, 240, 0.85));
margin: 0;
padding: 0;
line-height: 1.8;
color: #444444;
}
.email-container {
max-width: 600px;
margin: 40px auto;
background-color: rgba(255, 255, 255, 0.85);
padding: 40px;
border-radius: 12px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(8px);
}
.email-header {
text-align: center;
font-size: 26px;
font-weight: 700;
color: #333333;
margin-bottom: 25px;
text-transform: uppercase;
letter-spacing: 1.5px;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}
.email-body {
font-size: 18px;
margin-top: 20px;
color: #555555;
font-weight: 300;
}
.email-body p {
margin: 18px 0;
text-indent: 2em;
}
.verification-code {
display: block;
padding: 18px 36px;
margin: 30px auto;
background: linear-gradient(135deg, #6db3f2, #1e88e5);
color: #ffffff;
border-radius: 50px;
font-weight: 500;
font-size: 26px;
text-align: center;
cursor: pointer;
width: max-content;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
transition: background-color 0.3s ease, box-shadow 0.3s ease;
}
.verification-code:hover {
background-color: #1e88e5;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}
.email-footer {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid rgba(255, 255, 255, 0.5);
text-align: center;
font-size: 16px;
color: #666666;
font-weight: 400;
}
.email-footer p {
margin: 5px 0;
}
</style>
</head>
<body>
<div class="email-container">
<div class="email-header">
</div>
<div class="email-body">
<p>尊敬的用户:</p>
<p>
感谢您选择我们的服务!为了确保您的账户安全,我们需要验证您的身份。请使用下面的验证码完成登录或其他操作。这一步骤可以帮助我们确认是您本人在进行操作,保护您的账户安全。
</p>
<p>您的验证码是:</p>
<span id="verification-code" class="verification-code" th:text="${code}"></span>
<p>
此验证码有效期为5分钟,请尽快使用。如果您并未尝试登录,请忽略此邮件,并确保您的账户安全。
</p>
</div>
<div class="email-footer">
<p>© 2024 someliber 博客</p>
</div>
</div>
</body>
</html>
6.28 reset_password_code.html
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>密码重置验证码</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
body {
font-family: 'Roboto', Arial, Helvetica, sans-serif;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.85), rgba(240, 240, 240, 0.85));
margin: 0;
padding: 0;
line-height: 1.8;
color: #444444;
}
.email-container {
max-width: 600px;
margin: 40px auto;
background-color: rgba(255, 255, 255, 0.85);
padding: 40px;
border-radius: 12px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(8px);
}
.email-header {
text-align: center;
font-size: 26px;
font-weight: 700;
color: #333333;
margin-bottom: 25px;
text-transform: uppercase;
letter-spacing: 1.5px;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}
.email-body {
font-size: 18px;
margin-top: 20px;
color: #555555;
font-weight: 300;
}
.email-body p {
margin: 18px 0;
text-indent: 2em;
}
.verification-code {
display: block;
padding: 18px 36px;
margin: 30px auto;
background: linear-gradient(135deg, #6db3f2, #1e88e5);
color: #ffffff;
border-radius: 50px;
font-weight: 500;
font-size: 26px;
text-align: center;
cursor: pointer;
width: max-content;
box-shadow: 0px 6px 20px rgba(0, 0, 0, 0.15);
transition: background-color 0.3s ease, box-shadow 0.3s ease;
}
.verification-code:hover {
background-color: #1e88e5;
box-shadow: 0px 8px 25px rgba(0, 0, 0, 0.2);
}
.email-footer {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid rgba(255, 255, 255, 0.5);
text-align: center;
font-size: 16px;
color: #666666;
font-weight: 400;
}
</style>
</head>
<body>
<div class="email-container">
<div class="email-header">
</div>
<div class="email-body">
<p>尊敬的用户:</p>
<p>
我们收到了您重置密码的请求。为了确保您的账户安全,我们需要验证您的身份。请使用以下验证码来完成密码重置操作。
</p>
<p>您的验证码是:</p>
<span id="verification-code" class="verification-code" th:text="${code}"></span>
<p>
此验证码有效期为5分钟,请尽快使用。如果您并未尝试重置密码,请忽略此邮件,并确保您的账户安全。
</p>
</div>
<div class="email-footer">
<p>© 2024 someliber 博客</p>
</div>
</div>
</body>
</html>
6.29 reset_password_confirmation.html
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>密码重置确认</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
body {
font-family: 'Roboto', Arial, Helvetica, sans-serif;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.85), rgba(240, 240, 240, 0.85));
margin: 0;
padding: 0;
line-height: 1.8;
color: #444444;
}
.email-container {
max-width: 600px;
margin: 40px auto;
background-color: rgba(255, 255, 255, 0.85);
padding: 40px;
border-radius: 12px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(8px);
}
.email-header {
text-align: center;
font-size: 26px;
font-weight: 700;
color: #333333;
margin-bottom: 25px;
text-transform: uppercase;
letter-spacing: 1.5px;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}
.email-body {
font-size: 18px;
margin-top: 20px;
color: #555555;
font-weight: 300;
}
.email-body p {
margin: 18px 0;
text-indent: 2em;
}
.email-footer {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid rgba(255, 255, 255, 0.5);
text-align: center;
font-size: 16px;
color: #666666;
font-weight: 400;
}
</style>
</head>
<body>
<div class="email-container">
<div class="email-header"></div>
<div class="email-body">
<p>尊敬的用户:</p>
<p>
您的密码已成功重置。为确保您的账户安全,如果此次密码重置不是由您本人操作,请立即与我们的支持团队联系。我们将采取必要措施,保护您的账户安全。
</p>
</div>
<div class="email-footer">
<p>© 2024 someliber 博客</p>
</div>
</div>
</body>
</html>
6.30 verification_email.html
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>密码重置确认</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
body {
font-family: 'Roboto', Arial, Helvetica, sans-serif;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.85), rgba(240, 240, 240, 0.85));
margin: 0;
padding: 0;
line-height: 1.8;
color: #444444;
}
.email-container {
max-width: 600px;
margin: 40px auto;
background-color: rgba(255, 255, 255, 0.85);
padding: 40px;
border-radius: 12px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(8px);
}
.email-header {
text-align: center;
font-size: 26px;
font-weight: 700;
color: #333333;
margin-bottom: 25px;
text-transform: uppercase;
letter-spacing: 1.5px;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}
.email-body {
font-size: 18px;
margin-top: 20px;
color: #555555;
font-weight: 300;
}
.email-body p {
margin: 18px 0;
text-indent: 2em;
}
.email-footer {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid rgba(255, 255, 255, 0.5);
text-align: center;
font-size: 16px;
color: #666666;
font-weight: 400;
}
</style>
</head>
<body>
<div class="email-container">
<div class="email-header"></div>
<div class="email-body">
<p>尊敬的用户:</p>
<p>
您的密码已成功重置。为确保您的账户安全,如果此次密码重置不是由您本人操作,请立即与我们的支持团队联系。我们将采取必要措施,保护您的账户安全。
</p>
</div>
<div class="email-footer">
<p>© 2024 someliber 博客</p>
</div>
</div>
</body>
</html>
7. 测试验证
7.1 接口类型
7.2 测试注册
7.3 测试登录
7.4 验证网关转发
- id: article-service
uri: lb://article-service
predicates:
- Path=/article/**
这是文章的微服务,通过网关进行转发。
说明:我设置了jwt存储到cookie,如果是同一个组内(比如用户服务)无需填写jwt,反之需要携带jwt进行验证,自行验证。
7.5 其他
7.5.1 同一个ip+路径限制1分钟(令牌桶算法)内只能请求10次。
7.5.2 每5分钟只能发一个验证码。
7.5.3 用户名和邮箱都可以进行登录,不过得存储在username字段。
7.5.4 需要先进行登录,才能进行端口转发,你可以自行修改SecurityConfig配置类,放行不需要验证的接口。
7.5.5 添加了黑名单,把注销的token放置黑名单。
7.5.6 使用rabbitmq发送邮件。
7.5.7 使用thymeleaf解析邮件模板。
7.5.8 使用Object和Map之间的相互转换,通过第三方依赖jackson-databind。
不再进行验证,请自行验证。