北京建站abcseo关键词优化费用
Spring Security 使用教程
Spring Security 是 Spring 提供的强大安全框架,主要用于认证(Authentication)与授权(Authorization)。本教程将从零开始,介绍如何使用 Spring Security 实现基本的安全控制。
一、Spring Security 基础概念
- 认证(Authentication):验证用户身份是否合法。
- 授权(Authorization):验证用户是否有权限访问资源。
- 过滤器链(FilterChain):Spring Security 利用一系列过滤器实现安全逻辑。
二、快速开始
1. 添加依赖
在 pom.xml
中引入:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
三、默认登录功能体验
添加依赖后,访问任意接口时会自动跳转到登录页面,默认用户名为 user
,密码在控制台中输出。
四、自定义用户与密码
在 application.yml
中配置:
spring:security:user:name: adminpassword: 123456
五、自定义 Security 配置类
@Configuration
@EnableWebSecurity
public class SecurityConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(auth -> auth.requestMatchers("/public/**").permitAll() // 允许访问的路径.anyRequest().authenticated()).formLogin(Customizer.withDefaults()).logout(logout -> logout.permitAll());return http.build();}
}
六、自定义用户认证逻辑
1. 自定义 UserDetailsService
@Service
public class CustomUserDetailsService implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {if ("admin".equals(username)) {return User.builder().username("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("USER").build();}throw new UsernameNotFoundException("用户不存在");}
}
2. 注入 UserDetailsService 到配置类
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, CustomUserDetailsService userDetailsService) throws Exception {return http.getSharedObject(AuthenticationManagerBuilder.class).userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()).and().build();
}
七、常用配置说明
配置 | 说明 |
---|---|
permitAll() | 所有人可访问 |
authenticated() | 登录用户可访问 |
hasRole("ADMIN") | 拥有角色 ADMIN 才能访问 |
formLogin() | 启用表单登录 |
httpBasic() | 启用 HTTP Basic 登录 |
csrf().disable() | 关闭 CSRF 保护(开发环境) |
八、整合前后端分离项目
配置跨域和关闭默认登录页面:
http.csrf().disable().cors(Customizer.withDefaults()).formLogin().disable();
在前端登录时使用 /login
接口 + JSON 请求体 + UsernamePasswordAuthenticationFilter
也可以自定义登录接口,手动调用
AuthenticationManager.authenticate()
完成认证。
九、总结
Spring Security 提供了完善的安全体系,可灵活配置认证与授权。通过简单的配置,就能快速构建一个安全的 Web 应用。
推荐结合 OAuth2、JWT、RBAC 等深入实践,提高安全策略的精细化程度。
如需了解更多,可参考官网文档:https://docs.spring.io/spring-security/