1月25日

在前两天的基础上,引入Spring Security框架,实现用户登录和权限管理功能。通过用户认证和授权,提升系统的安全性。
(一)引入Spring Security
添加Spring Security依赖
在pom.xml中添加Spring Security的依赖:
xml

org.springframework.boot
spring-boot-starter-security

配置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<>());
}

}

posted @   skurar  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示