feat(security): 重构安全配置并添加用户认证功能
refactor: 将ResponseMessage移动到config包并增强功能 feat: 添加用户管理相关功能及密码加密配置 fix: 修复HelpController中README文件路径问题 docs: 更新application.properties配置注释 style: 清理无用导入和日志文件
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package com.qf.myafterprojecy.config;
|
||||
|
||||
import com.qf.myafterprojecy.pojo.Users;
|
||||
import com.qf.myafterprojecy.repository.UsersRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 自定义的UserDetailsService实现
|
||||
* 用于从数据库加载用户信息进行认证
|
||||
*/
|
||||
@Component
|
||||
public class CustomUserDetailsService implements UserDetailsService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
|
||||
|
||||
@Autowired
|
||||
private UsersRepository usersRepository;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
logger.info("用户登录认证: {}", username);
|
||||
|
||||
// 从数据库中查询用户
|
||||
Users user = usersRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
|
||||
|
||||
// 转换用户角色为Spring Security的权限
|
||||
// 根据role字段的值设置不同的角色权限
|
||||
String role = "ROLE_USER"; // 默认角色
|
||||
if (user.getRole() == 1) {
|
||||
role = "ROLE_ADMIN"; // 管理员角色
|
||||
}
|
||||
|
||||
List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(role));
|
||||
|
||||
// 返回Spring Security的User对象
|
||||
return new org.springframework.security.core.userdetails.User(
|
||||
user.getUsername(),
|
||||
user.getPassword(),
|
||||
authorities
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user