Spring Boot Security-无需身份验证即可

时间:2020-09-17 10:41:11

标签: java spring spring-boot web spring-security

Spring Boot安全性允许匿名用户

我正在尝试配置Spring Boot Security以允许匿名用户访问除一个以外的所有URL。默认情况下,用户和Spring生成的安全密码。 维护申请只需要一页 我已经尝试了很多技巧和教程。

1 2 3 4

还有其他人。

但是Spring仍然需要对所有页面进行身份验证。
我当前的安全配置

@EnableWebSecurity
@Configuration
public class SecurityConf extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
        .csrf()
        .disable()
        .authorizeRequests()
        .anyRequest()
        .anonymous()
        .antMatchers("/secure")
        .authenticated();
    }
}

网络配置

@Configuration
@EnableWebMvc
@EnableAsync
public class WebConf implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        WebMvcConfigurer.super.addResourceHandlers(registry);
        registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/**");
    }   
    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("Asynchronous Process-");
        executor.initialize();
        return executor;
    }   
}

和主要方法

@ComponentScan
@SpringBootApplication
@EnableScheduling
public class MainServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainServiceApplication.class, args);
    }
}

我尝试过

.permitAll()
.anonymous()

没有成功。

编辑1


项目结构

Project structure

编辑2


Project structure

@ComponentScan()
@SpringBootApplication
@EnableScheduling
public class MainServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainServiceApplication.class, args);
    }

}

Login page

由移动配置包解决。 Spring没有扫描配置包。

1 个答案:

答案 0 :(得分:1)

您可能需要更改顺序。可能的问题是antMatchers("/secure").authenticated()无效,因为在anyRequest()中将考虑 / secure 端点。还要确保SecurityConf装在扫描所需的正确包装中。

@EnableWebSecurity
@Configuration
public class SecurityConf extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/secure").authenticated()
            .anyRequest().anonymous();
    }
}

OR

@EnableWebSecurity
@Configuration
public class SecurityConf extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .disable()
            .authorizeRequests()
            .antMatchers("/secure").authenticated()
            .anyRequest().permitAll();
    }
}

更新

您需要在cz.lh.main_serviceSecurityConf内创建一个 configs 包,并且WebConf应该是cz.lh.main_service.configs

的一部分

OR

您可以使用@ComponentScan并指定包含SecurityConfWebConf的当前软件包

@ComponentScan(“your-config-package”)