在Spring Security 6上禁用Web Security

jhkqcmku  于 11个月前  发布在  Spring
关注(0)|答案(2)|浏览(208)

我正在寻找一种方法,我将能够禁用特定配置文件的Spring Security ,例如“开发”。这个问题之前已经被问过,但最近随着Spring Security 6的推出,有很多变化,我想知道这是如何实现的。这是我当前的安全配置:

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
        securedEnabled = true
)
public class WebSecurityConfig {

    private final UserDetailsServiceImpl userDetailsService;
    private final AuthJwtEntrypoint unauthorizedHandler;
    private final FilterChainExceptionHandler filterChainExceptionHandler;

    public WebSecurityConfig(UserDetailsServiceImpl userDetailsService,
                             AuthJwtEntrypoint unauthorizedHandler,
                             FilterChainExceptionHandler filterChainExceptionHandler) {
        this.userDetailsService = userDetailsService;
        this.unauthorizedHandler = unauthorizedHandler;
        this.filterChainExceptionHandler = filterChainExceptionHandler;
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

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

    @Bean
    public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults())
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        httpSecurity.authorizeHttpRequests(auth ->
                auth.requestMatchers("/api/auth/**").permitAll()
                        .requestMatchers("/api/country/**").permitAll()
                        .anyRequest().authenticated()
        );
        httpSecurity.authenticationProvider(authenticationProvider());
        httpSecurity.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        httpSecurity.addFilterBefore(filterChainExceptionHandler, LogoutFilter.class);
        return httpSecurity.build();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080", "http://127.0.0.1:8080"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
        configuration.setExposedHeaders(Arrays.asList("Authorization"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

字符串
我想在没有jwt token或特殊角色(方法保护安全)的情况下发送请求,如何才能实现?

编辑

我所尝试的:

public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults())
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        if (Arrays.asList(environment.getActiveProfiles()).contains("development")) {
            // In the development profile, permit all requests.
            httpSecurity.authorizeHttpRequests(auth ->
                    auth.anyRequest().permitAll()
            );
        } else {
            // In other profiles, use your regular security configuration.
            httpSecurity.authorizeHttpRequests(auth ->
                    auth.requestMatchers("/api/auth/**").permitAll()
                            .requestMatchers("/api/country/**").permitAll()
                            // ... (other authorization rules)
                            .anyRequest().authenticated()
            );
        }

        httpSecurity.authenticationProvider(authenticationProvider());
        httpSecurity.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        httpSecurity.addFilterBefore(filterChainExceptionHandler, LogoutFilter.class);

        return httpSecurity.build();
    }


这工作正常,但我仍然会在使用@Secured注解的方法上被拒绝访问。我该怎么办?

6ioyuze2

6ioyuze21#

试试这个

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(
    securedEnabled = true
)
@Profile("development")
public class WebSecurityConfig {
    ...
}

字符串
在application.properties

# As you can choose whatever
spring.profiles.active=production


这可能会禁用WebSecurityConfig类中的所有写入配置,然后您可以在开发服务器中执行一些没有任何配置的操作。

rvpgvaaj

rvpgvaaj2#

首先,使用@Profile("!development")注解生产配置文件,这将确保此配置仅在您没有将Sping Boot 应用程序配置文件设置为development时才会执行。现在您已经准备好为您的development profile创建一个类了!

@Configuration
@EnableWebSecurity
@Profile("development")
public class UnsecuredWebConfig {

    private final UserDetailsServiceImpl userDetailsService;
    private final AuthJwtEntrypoint unauthorizedHandler;
    private final FilterChainExceptionHandler filterChainExceptionHandler;

    public UnsecuredWebConfig(UserDetailsServiceImpl userDetailsService,
                              AuthJwtEntrypoint unauthorizedHandler,
                              FilterChainExceptionHandler filterChainExceptionHandler) {
        this.userDetailsService = userDetailsService;
        this.unauthorizedHandler = unauthorizedHandler;
        this.filterChainExceptionHandler = filterChainExceptionHandler;
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

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

    @Bean
    public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf(AbstractHttpConfigurer::disable)
                .cors(Customizer.withDefaults())
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        httpSecurity.authorizeHttpRequests(auth ->
                auth.anyRequest().permitAll()
        );
        httpSecurity.authenticationProvider(authenticationProvider());
        httpSecurity.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        httpSecurity.addFilterBefore(filterChainExceptionHandler, LogoutFilter.class);

        return httpSecurity.build();
    }

}

字符串
这将帮助您测试您的API,而无需特殊角色或发送jwt令牌。

相关问题