当前位置: 首页 > ops >正文

SpringSecurity实战:核心配置技巧

基于Spring Security的实例

以下是基于Spring Security的实用示例,涵盖认证、授权、OAuth2等常见场景,按功能分类整理:

基础认证与授权

  1. 表单登录配置
    配置默认表单登录页面,自定义登录路径和参数:

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin().loginPage("/custom-login").usernameParameter("user").passwordParameter("pass");}
    }
    
  2. 内存用户存储
    快速测试时配置内存用户:

    @Bean
    public UserDetailsService users() {UserDetails user = User.builder().username("user").password("{noop}password").roles("USER").build();return new InMemoryUserDetailsManager(user);
    }
    
  3. 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=?");
    }
    
  4. 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");
    }
    
  5. 自定义登录成功处理
    登录成功后自定义逻辑:

    http.formLogin().successHandler((request, response, authentication) -> {response.sendRedirect("/dashboard");});
    

高级配置

  1. 方法级安全控制
    使用注解保护方法:

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    public String adminPage() {return "admin";
    }
    
  2. CSRF防护禁用
    特定场景下禁用CSRF(如API服务):

    http.csrf().disable();
    
  3. CORS配置
    允许跨域请求:

    http.cors().configurationSource(request -> {CorsConfiguration config = new CorsConfiguration();config.addAllowedOrigin("*");config.addAllowedMethod("*");return config;
    });
    
  4. 多HttpSecurity配置
    针对不同URL路径应用不同安全规则:

    @Configuration
    @Order(1)
    public static class ApiSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated();}
    }
    
  5. 自定义AccessDenied处理
    自定义403页面:

    http.exceptionHandling().accessDeniedHandler((request, response, ex) -> {response.sendRedirect("/403");});
    

OAuth2集成

  1. OAuth2登录配置
    集成Google登录:

    http.oauth2Login().clientRegistrationRepository(clientRegistrationRepository()).authorizedClientService(authorizedClientService());
    
  2. 自定义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");};
    }
    
  3. JWT资源服务器
    配置JWT验证的资源服务器:

    @Override
    protected void configure(HttpSecurity http) throws Exception {http.oauth2ResourceServer().jwt().decoder(jwtDecoder());
    }
    
  4. 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;
    }
    

安全进阶

  1. 自定义过滤器
    添加前置认证过滤器:

    http.addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class);
    
  2. IP白名单限制
    限制特定IP访问:

    http.authorizeRequests().antMatchers("/admin/**").hasIpAddress("192.168.1.100");
    
  3. 会话固定保护
    防止会话固定攻击:

    http.sessionManagement().sessionFixation().migrateSession();
    
  4. 密码加密配置
    使用BCrypt加密:

    @Bean
    public PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();
    }
    
  5. H2控制台安全
    开发环境允许H2控制台访问:

    http.headers().frameOptions().disable().and().authorizeRequests().antMatchers("/h2-console/**").permitAll();
    

响应式安全

  1. WebFlux基础配置
    响应式安全配置:

    @Bean
    SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {return http.authorizeExchange().pathMatchers("/admin/**").hasRole("ADMIN").anyExchange().authenticated().and().formLogin().and().build();
    }
    

  2. 响应式方法安全
    启用响应式方法注解:

    @EnableReactiveMethodSecurity
    public class SecurityConfig {@Beanpublic MapReactiveUserDetailsService userDetailsService() {UserDetails user = User.withUsername("user").password("{noop}password").roles("USER").build();return new MapReactiveUserDetailsService(user);}
    }
    

测试相关

  1. 测试安全配置
    Mock用户进行测试:

    @Test
http://www.xdnf.cn/news/16431.html

相关文章:

  • 记录几个SystemVerilog的语法——时钟块和进程通信
  • 盛最多水的容器-leetcode
  • 洛谷 P10446 64位整数乘法-普及-
  • 详解力扣高频SQL50题之1164. 指定日期的产品价格【中等】
  • 3,Windows11安装docker保姆级教程
  • LeetCode 76:最小覆盖子串
  • mybatis的insert(pojo),会返回pojo吗
  • Petalinux生成文件的关系
  • 力扣面试150题--二进制求和
  • mmap机制
  • 2.qt调试日志输出
  • 《C++》STL--string详解(上)
  • vue3报错:this.$refs.** undefined
  • 在Podman/Docker容器中为Luckfox Lyra Zero W编译SDK:终极排错指南
  • Linux实战:从零搭建基于LNMP+NFS+DNS的WordPress博客系统
  • yolo11分类一键训练工具免安装环境windows版使用教程
  • 小白成长之路-Ansible自动化(一)
  • 20250707-2-Kubernetes 网络-Ingress暴露应用(http与https)_笔记
  • LeetCode 60:排列序列
  • 10.模块与包:站在巨人的肩膀上
  • MySQL ROUTER安装部署
  • 网络配置实验报告:主机间通信配置
  • python---eval函数
  • Day44 Java数组08 冒泡排序
  • 51核和ARM核单片机OTA实战解析(二)
  • day062-监控告警方式与Grafana优雅展示
  • 【通识】设计模式
  • Ashampoo Background Remover(照片去背景工具) v2.0.2 免费版
  • MyBatis-Plus IService 接口全量方法实现与测试(续)
  • 【Python系列】从内存分析到性能剖析