You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3无WebSecurityConfigurerAdapter的权限配置问题求助

Spring Boot 3 Spring Security 配置修正方案

1. 过时注解 @EnableGlobalMethodSecurity 的替代

Spring Boot 3 中,@EnableGlobalMethodSecurity 已被 @EnableMethodSecurity 取代,且 prePostEnabled 属性默认值为 true,直接使用该注解即可开启方法级安全校验:

// 替换原有的 @EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableMethodSecurity

2. 过时方法 authorizeRequests() 的替代

authorizeRequests() 已被 authorizeHttpRequests() 替代,所有路径授权规则需统一在该方法内配置(不可与旧方法混用)。要允许 /api/auth/** 路径无权限访问,同时对其他路径要求认证,配置如下:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            // 统一使用 authorizeHttpRequests 配置路径规则
            .authorizeHttpRequests(authz -> authz
                    // 允许/api/auth/**路径无需认证即可访问
                    .requestMatchers("/api/auth/**").permitAll()
                    // 其他所有路径需要认证
                    .anyRequest().authenticated()
            );
    
    http.authenticationProvider(authenticationProvider());
    http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
                 
    return http.build();
}

关键注意点

原代码中 WebSecurityCustomizer 配置了 ignoring().anyRequest(),这会让 Spring Security 忽略所有请求的安全校验,导致上述路径规则完全失效。如果不需要忽略所有请求,建议修改为忽略静态资源等特定路径,例如:

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.debug(true)
            // 忽略静态资源路径,根据实际业务调整
            .ignoring().requestMatchers("/static/**", "/public/**");
}

完整修正后的配置代码

package com.example.tokenAuth.security;

import com.example.tokenAuth.security.jwt.AuthEntryPointJwt;
import com.example.tokenAuth.security.jwt.AuthTokenFilter;
import com.example.tokenAuth.security.services.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;


@Configuration
@EnableWebSecurity
// 替换过时的@EnableGlobalMethodSecurity
@EnableMethodSecurity
public class WebSecurityConfig 
{
    @Autowired
    UserDetailsServiceImpl userDetailsService; 
    
    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;
    
    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() 
    {
        return new AuthTokenFilter();
    }    
    
    @Bean
    public DaoAuthenticationProvider authenticationProvider() 
    {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
   
        return authProvider;
    }    
    
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfiguration) throws Exception 
    {
        return authConfiguration.getAuthenticationManager();
    }    
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
    {
        http.cors().and().csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 使用authorizeHttpRequests替代authorizeRequests,统一配置路径规则
                .authorizeHttpRequests(authz -> authz
                        .requestMatchers("/api/auth/**").permitAll()
                        .anyRequest().authenticated()
                );
        
        http.authenticationProvider(authenticationProvider());
        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
                 
        return http.build();
    }
    
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() 
    {
        return (web) -> web.debug(true)
                // 忽略静态资源,避免安全校验拦截,可根据实际需求调整路径
                .ignoring().requestMatchers("/static/**", "/public/**");
    }    

    @Bean
    public PasswordEncoder passwordEncoder() 
    {
        return new BCryptPasswordEncoder();
    }
}

内容的提问来源于stack exchange,提问作者MUHIUDDIN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:15:37