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

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.lryc.cn/news/601758.html

相关文章:

  • 由于主库切换归档路径导致的 Oracle DG 无法同步问题的解决过程
  • Python堆栈实现:从基础到高并发系统的核心技术
  • 模拟实现python的sklearn库中的Bunch类以及 load_iris 功能
  • 20250727让飞凌OK3576-C开发板在Rockchip的原厂Android14下通过耳机播音
  • 两个函数的卷积
  • Node.js特训专栏-配置与环境部署:20.PM2进程守护与负载均衡
  • 以使命为帆,结业是重新出发的号角
  • 电科金仓 KingbaseES 深度解码:技术突破・行业实践・沙龙邀约 -- 融合数据库的变革之力
  • 从0开始学linux韦东山教程Linux驱动入门实验班(6)
  • c# everthing.exe 通信
  • Android基础(一) 运行HelloWorld
  • 【java】 IntelliJ IDEA高效编程设置指南
  • 大模型算法面试笔记——常用优化器SGD,Momentum,Adagrad,RMSProp,Adam
  • Java 代理机制详解:从静态代理到动态代理,彻底掌握代理模式的原理与实战
  • 雪花算法原理深度解析
  • 【0基础PS】PS工具详解--选择工具--快速选择工具
  • 【n8n教程笔记——工作流Workflow】文本课程(第一阶段)——5.4 计算预订订单数量和总金额 (Calculating booked orders)
  • 使用Python,OpenCV,K-Means聚类查找图像中最主要的颜色
  • Unity Catalog与Apache Iceberg如何重塑Data+AI时代的企业数据架构
  • 【LeetCode 热题 100】35. 搜索插入位置——二分查找(左闭右开)
  • 高格办公空间:以 “空间为基,服务为翼”,重塑办公场景生态
  • 【语义分割】记录2:yolo系列
  • libomxil-bellagio移植到OpenHarmony
  • java小白闯关记第一天(两个数相加)
  • Python-初学openCV——图像预处理(三)
  • XSS利用
  • Web-Machine-N7靶机攻略
  • 文件权限标记机制在知识安全共享中的应用实践
  • JavaEE初阶第十二期:解锁多线程,从 “单车道” 到 “高速公路” 的编程升级(十)
  • C++学习(线程相关)