Spring boot Security Disable security
Asked Answered
P

29

135

When I use security.basic.enabled=false to disable security on a Spring Boot project that has the following dependencies:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

I see the following Exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration$ManagementWebSecurityConfigurerAdapter': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setObjectPostProcessor(org.springframework.security.config.annotation.ObjectPostProcessor); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

In order to fix this exception I had to add the property - management.security.enabled=false . My understanding is that when the actuator is in the classpath, both security.basic.enabled=false and management.security.enabled=false should be set to disable the security.

Could someone please let me know if my understanding is wrong?

Purvey answered 27/5, 2014 at 16:3 Comment(4)
Why do you need security on your classpath if you just want to disable everything? Anyway, your stack trace is incomplete so there is no way to know what was preventing the app from starting. I would expect it would start, but the actuator endpoints should stay secure until you explicitly open them up.Aluminous
@DaveSyer I would like to disable security temporarily and also my application code refers security jars to work.Cuddy
You still haven't posted enough information to see why the app isn't starting. A full stack trace would be a start.Aluminous
@DaveSyer One reason would be a microservice managing spring-sec-oauth2 ClientDetails. You'll have a transitive import of spring-security but maybe don't want basic auth in your service.Catarrhine
C
123

In case you have spring-boot-actuator in your package, you should add the following

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

With older Spring-boot, the class was called ManagementSecurityAutoConfiguration.

In newer versions this has changed to

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

UPDATE

If for reactive application you are having the same issue, you can exclude the following classes

@SpringBootApplication(exclude = {ReactiveSecurityAutoConfiguration.class, ReactiveManagementWebSecurityAutoConfiguration.class })
Cartage answered 9/12, 2014 at 22:7 Comment(4)
Two more auto configurations that need to be excluded as well: SecurityFilterAutoConfiguration.class, SecurityRequestMatcherProviderAutoConfiguration.classFideliafidelio
Thanks for the new version one. I have lost an hour until I found your answer :)Dorkas
What does excluding ManagementWebSecurityAutoConfiguration do? Excluding SecurityAutoConfiguration seems to have removed login prompts from my app, which is all I wanted. I'm using Spring Boot 3.Dorset
It is to not autoconfigure the login page. Spring works with wise default.... so if you do not configure anything, it just picks up the default setup it assumes that you would need. This is just to say do nothing and then you are free to configure what you want.Cartage
C
87

What also seems to work fine is creating a file application-dev.properties that contains:

security.basic.enabled=false
management.security.enabled=false

If you then start your Spring Boot app with the dev profile, you don't need to log on.

Contemplation answered 8/12, 2015 at 7:48 Comment(4)
security.basic.enabled=false is not needed if you disable security with management.security.enabled=falseCommend
I also added security.ignored=/** then worked. https://mcmap.net/q/168672/-disabling-spring-security-in-spring-boot-app-duplicatePhotostat
This is now deprecated!Mal
Indeed. See spring.io/blog/2017/09/15/… for more info on the deprecation that happened in Spring Boot 2Contemplation
K
63

For Spring Boot 2 following properties are deprecated in application.yml configuration

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

To disable security for Sprint Boot 2 Basic + Actuator Security following properties can be used in application.yml file instead of annotation based exclusion (@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}))

  spring:
    autoconfigure:
      exclude[0]: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
      exclude[1]: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration

For application.properties syntax would be like

spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Katinakatine answered 9/10, 2019 at 7:52 Comment(4)
Thanks! I temporarily applied this with an environment variable to a springboot 2+ app in a docker container using: SPRING_APPLICATION_JSON='{"spring":{"autoconfigure":{"exclude[0]":"org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration","exclude[1]":"org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration"}}}'Space
Two more auto configurations that need to be excluded as well: SecurityFilterAutoConfiguration.class, SecurityRequestMatcherProviderAutoConfiguration.classFideliafidelio
@Space I tried your snippet but I got: java.lang.IllegalArgumentException: Cannot parse JSON Any ideas why?Nabonidus
Still getting authorization error? What could be the reason?Undertrick
P
43

If you need security as a dependency but don't want Spring Boot to configure it for you, you can use this exclusion:

    @EnableAutoConfiguration(exclude = { 
        org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class 
    })
Persona answered 5/8, 2014 at 12:33 Comment(1)
Two more auto configurations that need to be excluded as well: SecurityFilterAutoConfiguration.class, SecurityRequestMatcherProviderAutoConfiguration.classFideliafidelio
E
29

For the spring boot 2 users it has to be

@EnableAutoConfiguration(exclude = {
    org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class
})
Espresso answered 4/4, 2018 at 11:3 Comment(6)
What happened to ManagementWebSecurityAutoConfiguration in spring boot 2.0Ecumenism
You might still have to comment your @EnableWebSecurity annotationMargetmargette
Two more auto configurations that need to be excluded as well: SecurityFilterAutoConfiguration.class, SecurityRequestMatcherProviderAutoConfiguration.classFideliafidelio
@EugeneMaysyuk "SecurityRequestMatcherProviderAutoConfiguration" <- I am not finding this!Sectionalize
@Sectionalize let me take a lookFideliafidelio
@Sectionalize What Spring Boot version are you using? It is possible that those classes have different names. It depends on Spring Boot version.Fideliafidelio
T
13

Step 1: Comment annotation @EnableWebSecurity in your security config

//@EnableWebSecurity

Step 2: Add this to your application.properties file.

security.ignored=/**
spring.security.enabled=false
management.security.enabled=false
security.basic.enabled=false

For more details look here: http://codelocation.com/how-to-turn-on-and-off-spring-security-in-spring-boot-application/

Traveller answered 17/9, 2017 at 9:34 Comment(2)
Sadly, this doesn't work. Once I start spring-boot, it will create the default security filter chain: 2020-11-29 18:48:58.095 INFO 30744 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@7c9e4dd, org.springframework.security.web.context.SecurityContextPersistenceFilter@1d14d528, org.springframework.security.web.header.HeaderWriterFilter@3fc159ad, org.springframework.security.web.csrf.CsrfFilter@71b72226, org.springframework.security....Kraken
This worked for me I'm using Spring Boot 1.7.4. I didn't need to comment @EnableWebSecurity.Oscillator
C
11

Add following class into your code

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author vaquar khan
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated().and().csrf().disable();
    }

}

And insie of application.properties add

security.ignored=/**
security.basic.enabled=false
management.security.enabled=false
Cosmos answered 23/3, 2019 at 6:49 Comment(0)
P
8

Answer is to allow all requests in WebSecurityConfigurerAdapter as below.

you can do this in existing class or in new class.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
    }

Please note : If ther is existing GlobalMethodSecurityConfiguration class, you must disable it.

Pipes answered 9/4, 2020 at 11:52 Comment(3)
Not worked. But this one worked for me #23894510Zacek
Hi ravi, as per your solution, it is not recommended to disable csrf in production as "http.csrf.disable()". did you get CSRF issue for POST,etc calls?Pipes
@U_R_NaveenUR_Naveen I wrote the same code snippet but it didn't work. The login page still appears when I run the spring boot app. How can I fix it?Quijano
C
6

If you are using @WebMvcTest annotation in your test class

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })
@TestPropertySource(properties = {"spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration"})

doesn't help you.

You can disable security here

@WebMvcTest(secure = false)
Corgi answered 10/2, 2020 at 14:48 Comment(0)
L
5

The easiest way for Spring Boot 2 without dependencies or code changes is just:

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Lapstrake answered 6/12, 2019 at 12:31 Comment(3)
This is not working with Spring Boot v2.2.2.RELEASEDeedee
would be helpful if you say where to put this code...Union
This works in springboot version 2.7.5. ThanksLaurilaurianne
O
4

Permit access to everything using antMatchers("/")

     protected void configure(HttpSecurity http) throws Exception {
            System.out.println("configure");
                    http.csrf().disable();
                    http.authorizeRequests().antMatchers("/").permitAll();
        }
Overlive answered 1/1, 2018 at 16:10 Comment(1)
Problem with this is, access and security are not the same thing. You might be able to permit access to everything, but that does not set security off. For example, malicious looking strings still are catched.Kraken
A
4

The only thing that worked for me:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }

and

security.ignored=/**

Could be that the properties part is redundant or can be done in code, but had no time to experiment. Anyway is temporary.

Asoka answered 14/11, 2019 at 14:0 Comment(0)
O
4

With Spring Boot 3, the configuration syntax has changed. The following did the trick for me -

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

    @Configuration
    public class SecurityConfig {
    
        @Bean
        SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests().anyRequest().permitAll();
            return http.build();
        }
    }

More details in my blog post Spring Boot 3 + Security - Disable Authentication

Oogenesis answered 29/5, 2023 at 14:31 Comment(0)
B
3

I simply added security.ignored=/**in the application.properties,and that did the charm.

Blinker answered 16/5, 2018 at 9:45 Comment(1)
so that means automatic security mechanism is still in place but is just ignoring the all paths. I wouldn't be comfortable in keeping the things that are not requiredTeleran
D
1

In order to avoid security you can use annotations. Use this annotation on top of configure class:

@EnableWebSecurity

For example:

@EnableWebSecurity
@Configuration
public class AuthFilter{
   // configured method 
}
Direction answered 1/6, 2016 at 9:37 Comment(2)
Why should @EnableWebSecurity disable Web Security?Cholecalciferol
At least, it disables the default security configuration in Spring BootDuffy
A
1

You need to add this entry to application.properties to bypass Springboot Default Security

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

Then there won't be any authentication box. otrws, credentials are:- user and 99b962fa-1848-4201-ae67-580bdeae87e9 (password randomly generated)

Note: my springBootVersion = '1.5.14.RELEASE'

Ataractic answered 16/7, 2018 at 19:5 Comment(1)
without this,security.basic.enabled=false management.security.enabled=false security.ignored=/** is not enough is it normal?Lobation
S
1

You can configure to toggle spring security in your project by following below 2 steps:

STEP 1: Add a @ConditionalOnProperty annotation on top of your SecurityConfig class. Refer below:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity (prePostEnabled = true)
@ConditionalOnProperty (name = "myproject.security.enabled", havingValue = "true", matchIfMissing = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   // your security config
}

STEP 2: Add following config to your application.properties or application.yml file.

application.properties

security.ignored=/**
myproject.security.enabled=false

OR

application.yml

security:
  ignored: /**

myproject:
  security:
    enabled: false
Symbolize answered 8/8, 2018 at 4:41 Comment(3)
Is it possible to use only one property?Pontificals
@Pontificals your comment seems cryptic, could you please elaborate?Symbolize
I mean that security.ignored=/** is not necessaryPontificals
G
1

As previously multiple solutions mentioned to disable security through commenting of

@EnableWebSecurity

annotation and other is through properties in application.properties or yml. But those properties are showing as deprecated in latest spring boot version.

So, I would like to share another approach to configure default username and password in your application-dev.properties or application-dev.yml and use them to login into swagger and etc in development environment.

spring.security.user.name=admin
spring.security.user.password=admin

So, this approach will also provides you some kind of security as well and you can share this information with your development team. You can also configure user roles as well, but its not required in development level.

Gabbro answered 21/9, 2019 at 16:20 Comment(0)
T
1

As of Spring Boot 2.7.3 using @EnableAutoConfiguration(exclude = {}) generated an error, suggesting the exclude property be used in the @SpringBootApplication annotation.

Here is what worked for me when disabling Spring Security completely.

@SpringBootApplication(
        exclude = {
                SecurityAutoConfiguration.class,
                ManagementWebSecurityAutoConfiguration.class
        })
public class GeoServiceApplication {

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

}

I tried excluding only SecurityAutoConfiguration.class, but I got an error for no HttpSecurity bean defined for ManagementWebSecurityAutoConfiguration.class.

Tungstate answered 30/8, 2022 at 15:54 Comment(0)
V
1

Latest spring 2.7.x, create two class, set DISABLE_KEYCLOAK_AUDIT_PROPERTY = 'your key' in application profile for enable/disable security:

    public static final String DISABLE_KEYCLOAK_AUDIT_PROPERTY = "enable_security";
    @EnableAutoConfiguration(exclude =
            {org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class,
                    org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration.class
            })
    @Configuration
    @ConditionalOnProperty(name = DISABLE_KEYCLOAK_AUDIT_PROPERTY, havingValue = "true")
    static
    class DisableSecurityConfig {
    }

    @Configuration
    @ConditionalOnProperty(name = DISABLE_KEYCLOAK_AUDIT_PROPERTY, havingValue = "false")
    @Import({KeycloakSecurityConfig.class, KeycloakConfig.class})
    static
    class EnableSecurityConfig {
    }

for example use in application.yml:

enable_security: true

Volturno answered 15/12, 2022 at 12:47 Comment(0)
H
1
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // disable CSRF, http basic, form login
                .csrf().disable() 
                .httpBasic().disable() 
                .formLogin().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
                .and().exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
        return http.build();
    }
}
Huckster answered 28/2, 2023 at 21:19 Comment(0)
C
0

Add the below lines to your main app.

Remove org.activiti.spring.boot.SecurityAutoConfiguration.class if you're not using activiti.

Similarly, remove the one for actuator if you're not using spring-boot-actuator.

@EnableAutoConfiguration(exclude = {
org.activiti.spring.boot.SecurityAutoConfiguration.class,
org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration.class,
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class })
Chopping answered 31/8, 2017 at 13:1 Comment(0)
V
0

With Gradle and Spring boot v2.4.4, you can exclude spring security completely by adding this config in your build.gradle

configurations.all {
    exclude group:"org.springframework.boot", module: "spring-boot-starter-security"
}
Vibrations answered 9/6, 2021 at 3:53 Comment(0)
K
0

With Spring 2.6.0 this helped in my case:

@EnableAutoConfiguration(exclude = {
        org.springframework.boot.autoconfigure.security.SecurityDataConfiguration.class
})

And additional I had to remove the dependency in the pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Kilogram answered 14/10, 2022 at 6:24 Comment(0)
F
0

In Spring Security 5.7.0-M2 WebSecurityConfigurerAdapter was deprecated. Spring Security team encourages users to move towards a component-based security configuration.

package com.may.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").permitAll(); // config to permit all requests
        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager() { // to delete default username and password that is printed in the log every time, you can provide here any auth manager (InMemoryAuthenticationManager, etc) as you need
        return authentication -> {
            throw new UnsupportedOperationException();
        };
    }
}

More examples here:

https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

Fideliafidelio answered 29/11, 2022 at 0:1 Comment(0)
D
0

For a reactive webflux springboot application (in my case it is not a controller application, but a scheduler application) with out any http requests, none of the application.properties examples or exclude annotations worked. The only way worked for me is by adding a filter class.

I am using springboot 2.6.5, and have the below artifacts mainly besides some kafka and db related artifacts

pom.xml

<artifactId>spring-boot-starter-webflux</artifactId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<artifactId>spring-boot-starter-actuator</artifactId>
<artifactId>spring-boot-starter-security</artifactId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>

application.proeprties:

I did not add spring.main.web-application-type=reactive

Filter class:

NOTE: I did not even added @EnableWebFluxSecurity OR @EnableReactiveMethodSecurity, but it is still works.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
public class ActuatorSecurityFilter {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        return http.authorizeExchange().pathMatchers("/actuator/**").permitAll().and().build();
    }
}
Dhar answered 16/7, 2023 at 2:32 Comment(0)
D
0

Use

@Configuration
public class ApplicationNoSecurity {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
            .antMatchers("/**");
    }
}

https://www.baeldung.com/spring-security-disable-profile

Discontinuation answered 4/10, 2023 at 9:22 Comment(0)
K
0
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class HttpSecurityConfiguration {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .csrf(AbstractHttpConfigurer::disable)
                .build();
    }
}

I'm using

id 'org.springframework.boot' version '3.2.4'

and

implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '3.2.4'
Koball answered 2/4 at 5:14 Comment(0)
A
-3

I added below settings in application.yml and worked fine.

security:
    route-patterns-to-be-skipped:
      - /**/*

this can be converted as security.route-paterns-to-be-skipped=/**/* for application.properties

Audile answered 21/11, 2018 at 9:3 Comment(1)
This property doesn't exist at all.Crackdown

© 2022 - 2024 — McMap. All rights reserved.