2025-03-26
编程
00
请注意,本文编写于 33 天前,最后修改于 33 天前,其中某些信息可能已经过时。

目录

引入 Spring Security
1. 添加依赖
配置 Spring Security
1. 基本配置(适用于 Spring Boot)
2. 使用数据库中的用户信息

Spring Security 是一个功能强大且高度可定制的认证和授权框架,主要用于 Spring 应用的安全性管理。

引入 Spring Security

1. 添加依赖

对于 Maven 项目,你可以在 pom.xml 文件中添加 Spring Security 的依赖:

xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>

如果你正在开发的是一个传统的 Spring 项目而非 Spring Boot 项目,你需要手动添加 Spring Security 相关的依赖:

xml
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>当前版本号</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>当前版本号</version> </dependency>

请确保替换 "当前版本号" 为实际需要使用的版本号。

配置 Spring Security

1. 基本配置(适用于 Spring Boot)

在 Spring Boot 中,Spring Security 自动应用了一些默认的安全设置,例如所有 HTTP 请求都需要经过身份验证。你可以通过创建一个类继承 WebSecurityConfigurerAdapter 并覆盖其方法来定制化这些设置。

java
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() // 允许所有人访问 .anyRequest().authenticated() // 所有其他请求需要认证 .and() .formLogin() .loginPage("/login") // 指定登录页面 .permitAll() // 登录页面允许所有人访问 .and() .logout() .permitAll(); // 注销请求也允许所有人访问 } @Bean @Override public UserDetailsService userDetailsService() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } }

这段代码做了以下几件事情:

  • 定义了哪些 URL 路径是公开的,哪些需要用户登录。
  • 配置了一个简单的登录表单。
  • 创建了一个内存中的用户详细信息服务,用于演示目的。

2. 使用数据库中的用户信息

通常情况下,你会希望从数据库中读取用户信息而不是硬编码在代码里。这可以通过实现 UserDetailsService 接口来完成,该接口定义了加载用户特定数据的方法。

java
@Service public class MyUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("Could not find user"); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), mapRolesToAuthorities(user.getRoles())); } private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles) { return roles.stream() .map(role -> new SimpleGrantedAuthority(role.getName())) .collect(Collectors.toList()); } }

然后,在你的安全配置中指定使用这个服务:

java
@Autowired private MyUserDetailsService myUserDetailsService; @Override @Bean public UserDetailsService userDetailsService() { return myUserDetailsService; }