Подтвердить что ты не робот

Отключить spring безопасность в загрузочном приложении spring

У меня есть загрузочное веб-приложение spring с настройкой безопасности spring. Я хочу временно отключить проверку подлинности (до тех пор, пока это не понадобится).

Я добавляю это в application.properties:

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

Вот часть моего

Но у меня все еще есть базовая безопасность: во время запуска есть пароль безопасности по умолчанию, и я по-прежнему получаю приглашение HTTP Authentication.

Мой 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);
        }
    }

}
4b9b3361

Ответ 1

Используйте свойство security.ignored:

security.ignored=/**

security.basic.enable: false просто отключит часть автоконфигурации безопасности, но ваш WebSecurityConfig все еще будет зарегистрирован.

При запуске создается пароль безопасности по умолчанию

Попробуйте Autowired AuthenticationManagerBuilder:

@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 класс конфигурации

Ответ 3

Я думаю, вы также должны удалить автоматическую конфигурацию безопасности из вашего аннотированного класса @SpringBootApplication:

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

Ответ 4

Используйте @profile("whatever-name-profile-to-activate-if-needed") в вашем классе конфигурации безопасности, который расширяет WebSecurityConfigurerAdapter

security.ignored=/**

security.basic.enable: false

NB. Мне нужно отлаживать, чтобы узнать, почему почему исключить автоматическую настройку для меня не работало. Но профиль sot настолько плох, что вы можете снова активировать его с помощью свойств конфигурации, если необходимо

Ответ 5

Это единственное, что сработало для меня, я добавил следующую аннотацию к своему классу Application и исключил SecurityAutoConfiguration

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@EnableAutoConfiguration(exclude = {
        SecurityAutoConfiguration.class
})

Ответ 6

С помощью этого решения вы можете полностью включить/отключить защиту, активировав определенный профиль по командной строке. Я определил профиль в файле application-nosecurity.yaml

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

Затем я изменил свой пользовательский WebSecurityConfigurerAdapter, добавив @Profile("!nosecurity") следующим образом:

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

Чтобы полностью отключить защиту, достаточно запустить приложение, указав профиль nosecurity, то есть:

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

Ответ 7

Вы можете просто прокомментировать зависимость 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

Ответ 8

security.ignored устарел с Spring Boot 2.

Для меня просто расширьте аннотацию вашего класса приложения, сделал трюк:

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

Ответ 9

Поскольку опция security.disable запрещена к использованию, все еще есть способ добиться этого из чистого конфига, не касаясь мух классов (для меня это создает удобство при манипулировании средами и возможность активировать его с помощью переменной ENV), если вы используете Boot

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

Ответ 10

Просто добавьте следующую строку, чтобы отключить автоматическую настройку пружины в файле application.properties.

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

он работает на весну 2.0.5 :)