【问题标题】:disabling spring security in spring boot app [duplicate]在 Spring Boot 应用程序中禁用 Spring Security [重复]
【发布时间】:2016-07-16 18:22:11
【问题描述】:

我有一个配置了 Spring Security 的 Spring Boot Web 应用程序。我想暂时禁用身份验证(直到需要)。

我将此添加到application.properties

security.basic.enable: false   
management.security.enabled: false  

这是我的一部分

但我仍然有一个基本的安全性:启动时生成了一个默认的安全密码,我仍然得到 HTTP 身份验证提示框。

我的 pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>fr.test.sample</groupId>
    <artifactId>navigo</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
        <jsoup.version>1.8.3</jsoup.version>
        <guava.version>18.0</guava.version>
        <postgresql.version>9.3-1103-jdbc41</postgresql.version>
    </properties>

    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>${jsoup.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            </dependency>
    </dependencies>

    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <!-- Add Spring repositories -->
    <!-- (you don't need this if you are using a .RELEASE version) -->
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>

安全性在 WebSecurityConfig.java 中配置(我已经注释了注释以禁用它):

//@Configuration
//@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
//@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    UserService userService;

    @Autowired
    private DataSource datasource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // http.authorizeRequests().antMatchers("/bus/topologie", "/home")
        // http.authorizeRequests().anyRequest().authenticated()
        // .antMatchers("/admin/**").access("hasRole('ADMIN')").and()
        // .formLogin().failureUrl("/login?error")
        // .defaultSuccessUrl("/bus/topologie").loginPage("/login")
        // .permitAll().and().logout()
        // .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        // .logoutSuccessUrl("/login").permitAll().and().rememberMe()
        // .rememberMeParameter("remember-me")
        // .tokenRepository(persistentTokenRepository())
        // .tokenValiditySeconds(86400).and().csrf();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl();
        tokenRepositoryImpl.setDataSource(datasource);
        return tokenRepositoryImpl;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        PasswordEncoder encoder = new BCryptPasswordEncoder();

        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
        auth.jdbcAuthentication().dataSource(datasource);

        if (!userService.userExists("user")) {
            User userAdmin = new User("user", encoder.encode("password"), true);
            Set<Authorities> authorities = new HashSet<Authorities>();
            authorities.add(new Authorities(userAdmin,"ADMIN"));
            authorities.add(new Authorities(userAdmin,"CRIP"));
            authorities.add(new Authorities(userAdmin,"USER"));
            userAdmin.setAuthorities(authorities);

            userService.createUser(userAdmin);
        }
    }

}

【问题讨论】:

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


【解决方案1】:

使用security.ignored属性:

security.ignored=/**

security.basic.enable: false 只会禁用部分安全自动配置,但您的 WebSecurityConfig 仍将被注册。

启动时会生成一个默认的安全密码

尝试AutowiredAuthenticationManagerBuilder

@Override
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception { ... }

【讨论】:

【解决方案2】:

试试这个。新建一个类

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests().antMatchers("/").permitAll();
}

}

基本上,这告诉 Spring 允许访问每个 url。 @Configuration 告诉 spring 它是一个配置类

【讨论】:

  • 我通过在 antMatchers 上添加 autoconfigure.security 和 .permitAll() 的排除语句来实现它。
  • 在\@EnableWebSecurity 受保护的静态类SecurityConfiguration 中需要\@EnableWebSecurity
  • 您还可以使用 @Profile("nosecure") 之类的东西来注释这样的类,这样您就可以指定配置文件“nosecure”,直到您希望它打开为止。
  • 不是其他解决方案,但这在 SB v 2.0.0RELEASE 上对我有用。 security.ignored=/** 也不是必需的。就这门课就够了
【解决方案3】:

security.ignored 自 Spring Boot 2 起为 deprecated

对我来说,只需扩展您的 Application 类的 Annotation 即可:

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

【讨论】:

  • 对我来说这种方法有效,谢谢。
【解决方案4】:

我认为您还必须从 @SpringBootApplication 注释类中删除安全自动配置:

@EnableAutoConfiguration(exclude = {
    org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
    org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration.class})

【讨论】:

    【解决方案5】:

    使用此解决方案,您可以通过命令行激活特定配置文件来完全启用/禁用安全性。我在文件application-nosecurity.yaml中定义了配置文件

    spring:
      autoconfigure:
        exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
    

    然后我通过添加@Profile("!nosecurity") 来修改我的自定义WebSecurityConfigurerAdapter,如下所示:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
    @Profile("!nosecurity")
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {...}
    

    要完全禁用安全性,只需指定 nosecurity 配置文件即可启动应用程序,即:

    java -jar  target/myApp.jar --spring.profiles.active=nosecurity
    

    【讨论】:

    • 在应用程序 yml 中排除行的设置为我完成了这项工作。谢谢!
    【解决方案6】:

    由于 security.disable 选项被禁止使用,如果您使用 Boot,仍然有一种方法可以从纯配置中实现它而无需触及任何类苍蝇(对我来说,它通过环境操作和使用 ENV 变量激活它的可能性创造了便利)

    spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
    

    【讨论】:

      【解决方案7】:

      这是唯一对我有用的东西,我在我的 Application 类中添加了以下注释并排除了 SecurityAutoConfiguration

      import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
      import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
      
      @EnableAutoConfiguration(exclude = {
              SecurityAutoConfiguration.class
      })
      

      【讨论】:

      • 我做了类似的事情,但现在我想知道这个解决方案与仅仅拥有相比有哪些好处:http.authorizeRequests().antMatchers("/**").permitAll();
      【解决方案8】:

      对我来说,仅排除以下课程:

      import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
      
      @SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}) {
        // ... 
      }
      

      【讨论】:

        【解决方案9】:

        您可以暂时评论一下 maven 依赖项:

        <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-actuator</artifactId>
                </dependency>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-data-mongodb</artifactId>
                </dependency>
        <!--        <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-security</artifactId>
                </dependency>-->
        </dependencies>
        

        对我来说效果很好

        application.properties 禁用它已被 Spring Boot 弃用 2.0

        【讨论】:

          【解决方案10】:

          添加

          @SpringBootApplication(exclude = SecurityAutoConfiguration.class)

          【讨论】:

            【解决方案11】:

            在扩展 WebSecurityConfigurerAdapter 的安全配置类上使用 @profile("whatever-name-profile-to-activate-if-needed")

            security.ignored=/**
            
            security.basic.enable: false
            

            注意。我需要调试才能知道为什么排除自动配置对我不起作用。但是配置文件太糟糕了,如果需要,您仍然可以通过配置属性重新激活它

            【讨论】:

              【解决方案12】:

              更改WebSecurityConfig.java:注释掉configure方法中的所有内容并添加

              http.authenticateRequest().antMatcher("/**").permitAll();
              
              

              这将允许任何请求在没有任何身份验证的情况下访问每个 URL。

              【讨论】:

              • http.authorizeRequests 而不是。
              • 这是手动的,但为什么不呢。
              【解决方案13】:

              只需添加以下行即可在 application.properties 文件中禁用 spring 自动配置

              spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

              它适用于春季 2.0.5 :)

              【讨论】:

                【解决方案14】:

                接受的答案对我不起作用。

                如果您有多重配置,将以下内容添加到您的 WebSecurityConfig 类对我有用(确保您的 Order(1) 低于该类中的所有其他 Order 注释):

                /* UNCOMMENT TO DISABLE SPRING SECURITY */
                    /*@Configuration
                    @Order(1)
                    public static class DisableSecurityConfigurationAdapater extends WebSecurityConfigurerAdapter {
                        @Override
                        protected void configure(HttpSecurity http) throws Exception {
                            http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
                        }
                    }*/
                

                【讨论】:

                • 我们需要以编程方式完成(禁用/启用°配置
                • @AhmedRebai 该解决方案对您不起作用吗?对我来说没问题。
                猜你喜欢
                • 2015-08-17
                • 2017-03-06
                • 2019-05-08
                • 2020-03-17
                • 2016-08-26
                • 2021-06-26
                相关资源
                最近更新 更多