feat: 登录密码改用 BCrypt 校验

This commit is contained in:
2026-06-18 00:06:42 +08:00
parent d0c78ceb28
commit 2cf3533141
4 changed files with 41 additions and 7 deletions
+7
View File
@@ -129,6 +129,13 @@
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
</dependency> </dependency>
<!-- jBCrypt (独立 BCrypt 实现,无 Spring Security 依赖) -->
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@@ -7,6 +7,7 @@ import com.guo.learningprogresstracker.exception.AppException;
import com.guo.learningprogresstracker.service.UserService; import com.guo.learningprogresstracker.service.UserService;
import com.guo.learningprogresstracker.mapper.UserMapper; import com.guo.learningprogresstracker.mapper.UserMapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
@@ -23,12 +24,13 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity>
public String authenticate(String username, String password) throws AppException { public String authenticate(String username, String password) throws AppException {
UserEntity userEntity = this.getOneOpt(Wrappers.<UserEntity>lambdaQuery() UserEntity userEntity = this.getOneOpt(Wrappers.<UserEntity>lambdaQuery()
.eq(UserEntity::getUserName, username) .eq(UserEntity::getUserName, username))
.eq(UserEntity::getUserPassword, password)).orElseThrow(() -> new AppException("账号或密码错误!")); .orElseThrow(() -> new AppException("账号或密码错误!"));
return userEntity.getId();
if (!BCrypt.checkpw(password, userEntity.getUserPassword())) {
throw new AppException("账号或密码错误!");
}
return userEntity.getId();
} }
} }
@@ -0,0 +1 @@
ALTER TABLE `user` MODIFY COLUMN `user_password` varchar(60) NOT NULL COMMENT '账号密码(BCrypt哈希)';
@@ -0,0 +1,24 @@
package com.guo.learningprogresstracker.utils;
import org.junit.jupiter.api.Test;
import org.mindrot.jbcrypt.BCrypt;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BCryptPasswordGeneratorTest {
@Test
void generatePasswordHash() {
String password = System.getProperty("password", "admin");
int rounds = Integer.parseInt(System.getProperty("rounds", "10"));
String hash = BCrypt.hashpw(password, BCrypt.gensalt(rounds));
System.out.println("BCrypt hash:");
System.out.println(hash);
System.out.println("SQL:");
System.out.printf("UPDATE `user` SET `user_password` = '%s' WHERE `user_name` = 'admin';%n", hash);
assertTrue(BCrypt.checkpw(password, hash));
}
}