SpringSecurity,在 maven 中使用特定配置文件时禁用安全性

问题描述 投票:0回答:1

我面临这个问题,我想在maven中使用“dev”配置文件时禁用SpringSecurity,并在使用“prod”配置文件时让它工作。

最初我使用了 SpringSecurity 的一个非常基本的版本,它非常开箱即用,在这种情况下,我只是在 application.properties 文件中使用了这个属性:

spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

工作正常,当我添加像这样的自定义@Configuration类时,问题就出现了:

@Configuration

public class SecurityConfiguration {


    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
        http
            .csrf(AbstractHttpConfigurer::disable)
            .sessionManagement(s->s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests((authz) -> authz
                    .requestMatchers(HttpMethod.POST, "/login/**").permitAll()
                    .requestMatchers(HttpMethod.POST, "/users/**").hasAuthority("ROLE_ADMIN")
                    .anyRequest().authenticated()
            )
            .addFilter(new CustomAuthenticationFilter(authenticationManager))
            .addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
            .headers(h -> h.cacheControl(Customizer.withDefaults()));
    
        return http.build();
    }

}

然后我遇到了这个错误,程序崩溃了。

Parameter 0 of method authenticationManager in it.kevinpirola.passacarte.security.SecurityConfiguration required a bean of type 'org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration' that could not be found.

我的目标是在开发时禁用安全性,只是为了避免每次输入密码的麻烦,第二件事我想将其保留在配置文件特定的 application.properties 中,以免有特定于此特定的代码仅用于解决基础设施问题的案例。

有人有想法吗?

spring spring-security configuration
1个回答
0
投票

如果您使用

spring.profiles.active
定义配置文件,则可以使用

注释配置类
@Profile("!dev")

由于您的目标是基于 Maven 配置文件禁用该 bean,因此您可以通过将以下内容添加到 POM 来向 Spring 提供其值:

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <property>
                <name>spring.profiles.active</name>
                <value>dev</value>
            </property>
        </activation>
    </profile>
</profiles>
© www.soinside.com 2019 - 2024. All rights reserved.