如何在Spring Boot中实现安全性

Spring Security是Spring Boot中常用的权限认证和授权框架。
添加依赖
在pom.xml中添加Spring Security依赖:
xml
复制

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

配置Spring Security
创建一个配置类,继承WebSecurityConfigurerAdapter并重写方法。
java
复制
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 禁用CSRF保护
.authorizeRequests()
.antMatchers("/admin/").hasRole("ADMIN") // 需要ADMIN角色
.antMatchers("/user/
").hasRole("USER") // 需要USER角色
.anyRequest().authenticated() // 其他请求需要认证
.and()
.formLogin().permitAll() // 允许访问登录页面
.and()
.logout().permitAll(); // 允许访问登出页面
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication() // 使用内存用户
        .withUser("user").password("{noop}password").roles("USER")
        .and()
        .withUser("admin").password("{noop}admin").roles("ADMIN");
}

}
自定义登录页面
创建一个登录页面login.html,并配置登录路径。
HTML
复制

自定义用户详情服务 如果需要从数据库加载用户信息,实现UserDetailsService接口。 java 复制 @Service public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username)
        .orElseThrow(() -> new UsernameNotFoundException("User not found"));
    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
}

}

posted @ 2025-02-18 11:14  软工李文轩  阅读(52)  评论(0)    收藏  举报