1月25日
在前两天的基础上,引入Spring Security框架,实现用户登录和权限管理功能。通过用户认证和授权,提升系统的安全性。
(一)引入Spring Security
添加Spring Security依赖
在pom.xml中添加Spring Security的依赖:
xml
配置Spring Security
创建SecurityConfig类,继承WebSecurityConfigurerAdapter,并配置用户认证和授权规则:
java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 禁用CSRF保护(开发阶段)
.authorizeRequests()
.antMatchers("/user/**", "/admin/**").authenticated() // 需要认证的路径
.antMatchers("/admin/**").hasRole("ADMIN") // 需要管理员权限的路径
.antMatchers("/", "/login", "/register").permitAll() // 不需要认证的路径
.and()
.formLogin()
.loginPage("/login").defaultSuccessUrl("/users", true) // 自定义登录页面
.and()
.logout().logoutSuccessUrl("/login");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
创建用户详情服务
实现UserDetailsService接口,用于从数据库加载用户信息:
java
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.selectByName(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
return new org.springframework.security.core.userdetails.User(user.getName(), user.getPassword(), new ArrayList<>());
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)