SpringSecurity实战:核心配置技巧
基于Spring Security的实例
以下是基于Spring Security的实用示例,涵盖认证、授权、OAuth2等常见场景,按功能分类整理:
基础认证与授权
-
表单登录配置
配置默认表单登录页面,自定义登录路径和参数:@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().loginPage("/custom-login").usernameParameter("user").passwordParameter("pass");} }
-
内存用户存储
快速测试时配置内存用户:@Bean public UserDetailsService users() {UserDetails user = User.builder().username("user").password("{noop}password").roles("USER").build();return new InMemoryUserDetailsManager(user); }
-
JDBC用户存储
通过JDBC连接数据库认证:@Autowired private DataSource dataSource;@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username=?").authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username=?"); }
-
LDAP认证
集成LDAP服务器认证:@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.ldapAuthentication().userDnPatterns("uid={0},ou=people").groupSearchBase("ou=groups").contextSource().url("ldap://localhost:8389/dc=example,dc=com"); }
-
自定义登录成功处理
登录成功后自定义逻辑:http.formLogin().successHandler((request, response, authentication) -> {response.sendRedirect("/dashboard");});
高级配置
-
方法级安全控制
使用注解保护方法:@PreAuthorize("hasRole('ADMIN')") @GetMapping("/admin") public String adminPage() {return "admin"; }
-
CSRF防护禁用
特定场景下禁用CSRF(如API服务):http.csrf().disable();
-
CORS配置
允许跨域请求:http.cors().configurationSource(request -> {CorsConfiguration config = new CorsConfiguration();config.addAllowedOrigin("*");config.addAllowedMethod("*");return config; });
-
多HttpSecurity配置
针对不同URL路径应用不同安全规则:@Configuration @Order(1) public static class ApiSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated();} }
-
自定义AccessDenied处理
自定义403页面:http.exceptionHandling().accessDeniedHandler((request, response, ex) -> {response.sendRedirect("/403");});
OAuth2集成
-
OAuth2登录配置
集成Google登录:http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository()).authorizedClientService(authorizedClientService());
-
自定义OAuth2用户服务
处理OAuth2用户信息:@Bean public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {return request -> {DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();OAuth2User user = delegate.loadUser(request);return new DefaultOAuth2User(user.getAuthorities(), user.getAttributes(), "sub");}; }
-
JWT资源服务器
配置JWT验证的资源服务器:@Override protected void configure(HttpSecurity http) throws Exception {http.oauth2ResourceServer().jwt().decoder(jwtDecoder()); }
-
OAuth2客户端
配置客户端凭证模式:@Bean public OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clientRegistrationRepository,OAuth2AuthorizedClientRepository authorizedClientRepository) {OAuth2AuthorizedClientProvider provider = OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build();DefaultOAuth2AuthorizedClientManager manager = new DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientRepository);manager.setAuthorizedClientProvider(provider);return manager; }
安全进阶
-
自定义过滤器
添加前置认证过滤器:http.addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class);
-
IP白名单限制
限制特定IP访问:http.authorizeRequests().antMatchers("/admin/**").hasIpAddress("192.168.1.100");
-
会话固定保护
防止会话固定攻击:http.sessionManagement().sessionFixation().migrateSession();
-
密码加密配置
使用BCrypt加密:@Bean public PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder(); }
-
H2控制台安全
开发环境允许H2控制台访问:http.headers().frameOptions().disable().and().authorizeRequests().antMatchers("/h2-console/**").permitAll();
响应式安全
-
WebFlux基础配置
响应式安全配置:@Bean SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {return http.authorizeExchange().pathMatchers("/admin/**").hasRole("ADMIN").anyExchange().authenticated().and().formLogin().and().build(); }
-
响应式方法安全
启用响应式方法注解:@EnableReactiveMethodSecurity public class SecurityConfig {@Beanpublic MapReactiveUserDetailsService userDetailsService() {UserDetails user = User.withUsername("user").password("{noop}password").roles("USER").build();return new MapReactiveUserDetailsService(user);} }
测试相关
-
测试安全配置
Mock用户进行测试:@Test