[java] disabling spring security in spring boot app

I have a spring boot web app with spring security configured. I want to disable authentication for a while (until needed).

I add this to the application.properties:

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

Here is some part of my

But I still have a basic security included : There is a default security password generated at startup and I am still getting HTTP Authentication prompt box.

My 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>

The security is configured in WebSecurityConfig.java (I have commented the annotation to disable it) :

//@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);
        }
    }

}

The answer is


I think you must also remove security auto config from your @SpringBootApplication annotated class:

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

Use @profile("whatever-name-profile-to-activate-if-needed") on your security configuration class that extends WebSecurityConfigurerAdapter

security.ignored=/**

security.basic.enable: false

NB. I need to debug to know why why exclude auto configuration did not work for me. But the profile is sot so bad as you can still re-activate it via configuration properties if needed


Try this. Make a new class

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

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

}

Basically this tells Spring to allow access to every url. @Configuration tells spring it's a configuration class


This was the only thing that worked for me, I added the following annotation to my Application class and exclude SecurityAutoConfiguration

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

@EnableAutoConfiguration(exclude = {
        SecurityAutoConfiguration.class
})

The accepted answer didn't work for me.

If you have a multi configuration, adding the following to your WebSecurityConfig class worked for me (ensure that your Order(1) is lower than all of your other Order annotations in the class):

/* 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();
        }
    }*/

Change WebSecurityConfig.java: comment out everything in the configure method and add

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

This will allow any request to hit every URL without any authentication.


With this solution you can fully enable/disable the security by activating a specific profile by command line. I defined the profile in a file application-nosecurity.yaml

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

Then I modified my custom WebSecurityConfigurerAdapter by adding the @Profile("!nosecurity") as follows:

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

To fully disable the security it's enough to start the application up by specifying the nosecurity profile, i.e.:

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

You could just comment the maven dependency for a while:

<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>

It worked fine for me

Disabling it from application.properties is deprecated for Spring Boot 2.0


Just add the following line to disable spring auto configuration in application.properties file

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

it works on spring 2.0.5 :)


security.ignored is deprecated since Spring Boot 2.

For me simply extend the Annotation of your Application class did the Trick:

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

just add

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)


For me only excluding the following classes worked:

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}) {
  // ... 
}

Since security.disable option is banned from usage there is still a way to achieve it from pure config without touching any class flies (for me it creates convenience with environments manipulation and possibility to activate it with ENV variable) if you use Boot

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-security

Two Page Login with Spring Security 3.2.x Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized Unsupported Media Type in postman How Spring Security Filter Chain works Spring security CORS Filter How to configure CORS in a Spring Boot + Spring Security application? Failed to load ApplicationContext (with annotation) disabling spring security in spring boot app When to use Spring Security`s antMatcher()? How to manage exceptions thrown in filters in Spring?

Examples related to spring-boot

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Why am I getting Unknown error in line 1 of pom.xml? Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured How to resolve Unable to load authentication plugin 'caching_sha2_password' issue ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName ERROR Source option 1.5 is no longer supported. Use 1.6 or later How to start up spring-boot application via command line? JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Examples related to spring-java-config

Are all Spring Framework Java Configuration injection examples buggy? disabling spring security in spring boot app How To Inject AuthenticationManager using Java Configuration in a Custom Filter