Spring Security 是一个功能强大且高度可定制的认证和授权框架,主要用于 Spring 应用的安全性管理。
对于 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 Boot 中,Spring Security 自动应用了一些默认的安全设置,例如所有 HTTP 请求都需要经过身份验证。你可以通过创建一个类继承 WebSecurityConfigurerAdapter
并覆盖其方法来定制化这些设置。
javaimport 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);
}
}
这段代码做了以下几件事情:
通常情况下,你会希望从数据库中读取用户信息而不是硬编码在代码里。这可以通过实现 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;
}