59

I want to use Spring Security for JWT authentication. But it comes with default authentication. I am trying to disable it, but the old approach of doing this - disabling it through application.properties - is deprecated in 2.0.

This is what I tried:

@Configuration
public class StackWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable();
        // http.authorizeRequests().anyRequest().permitAll(); // Also doesn't work.
    }
}

How can I simply disable basic security?

UPDATE
It might be nice to know that I am not using web mvc but web flux.

Screenshot:
Basic login form

Makoto
  • 104,088
  • 27
  • 192
  • 230
Jan Wytze
  • 3,307
  • 5
  • 31
  • 51
  • Did you try to exclude the package as you can see [here](https://stackoverflow.com/questions/23894010/spring-boot-security-disable-security) – Novy Nov 13 '17 at 21:30
  • @Y.Colin Yes I tried that. I can only disable it by removing the whole dependency.. – Jan Wytze Nov 13 '17 at 21:35
  • Could you explain a bit more? What is now secured that wasn't previously? What is your security configuration? Could you provide an example of request+response? – Brian Clozel Nov 14 '17 at 08:28
  • @BrianClozel At the moment it is just an empty application, I just want to use spring security without the basic authentication. You can duplicate this by creating a spring boot 2.0 web application and use `@EnableWebFlux`. – Jan Wytze Nov 14 '17 at 17:20
  • Adding `@EnableWebFlux` effectively disables all the WebFlux auto-configuration. Is that what you intend to do? – Brian Clozel Nov 14 '17 at 17:22
  • @BrianClozel No sorry I expected that `@EnableWebFlux` would enable webflux... But I see that by removing it the web server is still started but basic security is still enabled. – Jan Wytze Nov 14 '17 at 17:34
  • Does this answer your question? [Spring boot Security Disable security](https://stackoverflow.com/questions/23894010/spring-boot-security-disable-security) – Dupinder Singh Nov 03 '20 at 12:40
  • FYI - Spring Security for the Servlet application recommends adding @EnableWebSecurity to any custom configuration. – Irshad Aug 11 '21 at 18:56

17 Answers17

69

According to the new updates in Spring 2.0, if Spring Security is on the classpath, Spring Boot will add @EnableWebSecurity.So adding entries to the application.properties ain't gonna work (i.e it is no longer customizable that way). For more information visit the official website Security changes in Spring Boot 2.0

Albeit not sure about your requirement exactly, I could think of one workaround like the following:-

@Configuration
@EnableWebSecurity
public class SecurityConfiguration  extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests().antMatchers("/").permitAll();
    }
}

Hope this helps.

Sen
  • 1,308
  • 12
  • 12
  • 1
    This question is about configuring security in Spring Boot for Spring WebFlux; `@EnableWebSecurity` is for Spring MVC. – Brian Clozel Dec 17 '18 at 20:34
  • 1
    @BrianClozel when I answered to this question, this update about WebFlux was not there I guess. – Sen Dec 19 '18 at 18:55
  • BrianClozel, how do disable @EnableWebSecurity. It seems to be there by default and prevents my application from starting up when I define reactive spring security – DBS Mar 28 '19 at 16:22
  • 2
    IMO this really isn't any better than just removing the spring security dependency from the class path. It would be better if the "http.httpBasic().disable().formLogin().disable();" actually worked. The documentation says "Spring Boot now has a single behavior that backs off as soon as you add your own WebSecurityConfigurerAdapter." but that seems to be a false statement. I have a WebSecurityConfigurerAdapter as well as "http.httpBasic().disable().formLogin().disable();" and I still get that stupid spring login page. its infuriating. – peekay Apr 08 '19 at 22:17
  • @peekay "Spring Boot now has a single behavior that backs off as soon as you add your own WebSecurityConfigurerAdapter." - this statement is entire true. Any auto configuration feature of Spring boot is non-invasive, i.e. it will back away once you add your own configuration. Disabling formLogin() doesn't let you access endpoints without userid, password, it rather disables/removes the form based authentication functionality.https://docs.spring.io/spring-security/site/docs/4.2.11.RELEASE/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html#formLogin-- – Sen Apr 09 '19 at 14:40
  • @Sen, Yes I understand that and I have my own auth provider that is handling the authentication, so there is no need for the login form or basic auth. So by adding the disable calls it should stop blocking me and actually back off, not continue to pop up and prevent my auth provider from doing its work. – peekay Apr 09 '19 at 14:46
  • @peekay could you paste the code snippet? I'll try to help you out, if I can. Do you have any web authentication provider or anything of that sort in your configuration file? – Sen Apr 10 '19 at 08:58
  • This answer didn't fix it entirely for me: it still gave me a 403 response on SOME of my integration tests. I managed to fix it with this SO-answer: https://stackoverflow.com/a/49261864/3149048 – Stephanie Feb 14 '20 at 09:08
47

From Spring Boot 2.1 on, if you include spring-boot-actuator, it does not suffice anymore to only exclude SecurityAutoconfiguration, you also need to exclude ManagementWebSecurityAutoConfiguration, like so:

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })
Integrating Stuff
  • 5,253
  • 2
  • 33
  • 39
  • Thanks! The suggestion in this answer worked, depending of course on the Spring Boot version (in my case 2.1.5). – octy May 17 '19 at 17:45
  • 2
    As long as I am using the @EnableWebSecurity annotation, this answer does not work for me (Spring Boot 2.1.5, spring-security-web 4.2.3.RELEASE). Did you have to do anything else? – Brandon May 21 '19 at 13:32
  • 2
    If you want to exclude AutoConfiguration I believe you will not be able to use @EnableWebSecurity and you will need to configure the required spring security beans yourself as with plain Spring/without Spring boot. – Integrating Stuff May 22 '19 at 08:25
  • The easiest way. Thank you – Frankie Drake Jul 18 '19 at 09:33
25

According to the reference documentation, the Security configuration for allowing all requests with WebFlux should look like this:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange().anyExchange().permitAll();
        return http.build();
    }
}
Brian Clozel
  • 56,583
  • 15
  • 167
  • 176
  • Thank! Everything configured in the configuration that extended `WebSecurityConfigurerAdapter` didn't seem to do anything. But when removing `@EnableWebSecurity` and using this configuration it finally works. – Jan Wytze Nov 14 '17 at 18:00
  • 1
    `@EnableWebSecurity` is for Spring MVC only. `@EnableWebFluxSecurity` is automatically applied if you've got spring security on classpath. See https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M4-Release-Notes#security-1 for more information – Brian Clozel Nov 14 '17 at 18:11
  • I have to explicitly mention `@EnableWebFluxSecurity` to `SecurityConfig`. – Sumit Ramteke Aug 10 '18 at 01:14
  • 8
    This does not work as it now complains about Missing Bean "ServerHttpSecurity " – user1428716 Dec 13 '18 at 04:36
  • 1
    I have tried it with spring boot 2.2.0 ServerHttpSecurity' could not be found – Christian Ibanibo Nov 05 '19 at 14:58
  • This worked for me after the following adjustment... I had to call http.csrf().disable(); before return – T.Thamilvaanan Jul 15 '21 at 07:23
19

This worked for me:

@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }
}
davo
  • 380
  • 2
  • 11
  • I don't think disabling csrf is needed, this could open the door for some attacks https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) – rvazquezglez Jul 18 '18 at 19:53
  • This one works. I removed .csrf().disable() though. Not a good idea to disable csrf. – zookastos Mar 14 '21 at 05:21
17

You can add/modify the following to your Application class:

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class MyApplication {

}
helmy
  • 9,068
  • 3
  • 32
  • 31
7

Adding some fresh answer, I assume all use actuator, if not I'd bet one class exclusion should be sufficient, I managed to disable through properties:

spring:
  autoconfigure:
    exclude: ${spring.autoconfigure.sac}, ${spring.autoconfigure.mwsas}
    sac: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
    mwsas: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration

I've referenced two auto-config classes through property to keep the length intact (note that IntelliJ Ultimate will cry if you reference it like that as it has no clue what are these placeholder values and if they are actually legit classes, so inline if that annoys you).

Application however does not fail to start as claimed by:

https://www.baeldung.com/spring-boot-security-autoconfiguration

if you just disable SecurityAutoConfiguration

If it did work, you will stop seeing auto generated password and it is a little bit less confusing than the accepted answer, as dev reading the log won't get confused by generated password for basic auth while security allows all.

Why just disabling main auto config class isn't enough is because of this fella:

@Configuration
class ManagementWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .requestMatchers(
                        EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class))
                .permitAll().anyRequest().authenticated().and().formLogin().and()
                .httpBasic();
    }

}

There was tons of work made to split actuator and security config which confused us all, now its more straightforward but artifacts like these still exist. Spring devs will correct me if I am wrong :-).

Aubergine
  • 5,862
  • 19
  • 66
  • 110
  • 1
    Ohh man this is the single answer between tons not worked suggestions. This answer definitely should be at the top of the thread. Thanks a lot! – Speise May 22 '20 at 19:22
  • For WebFlux, exclude: `org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration` and `org.springframework.boot.actuate.autoconfigure.security.reactive.ReactiveManagementWebSecurityAutoConfiguration` – Litash Mar 01 '21 at 05:58
3

I have leveraged @ConditionalOnProperty to load the following SecurityConfig.java class if I set spring.security.enabled property to false in my application.yml to disable spring security and it works like a charm.

@ConditionalOnProperty(name = "spring.security.enabled", havingValue = "false")
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests().antMatchers("/").permitAll();
    }
}
Ashraf Sarhan
  • 1,507
  • 16
  • 21
2

If anyone is struggling with this in a WebFlux based application, or a Spring Cloud Gateway application, the below worked for me:

@EnableWebFluxSecurity
public class InsecurityConfiguration {
    // @formatter:off
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
         http
              .authorizeExchange()
                   .anyExchange().permitAll();
         return http.build();
    }
}
odedia
  • 931
  • 2
  • 11
  • 27
2

To disable default security for Spring Boot Reactive Web applications, use the following excludes when you have actuator also in the classpath.

@SpringBootApplication(exclude = {ReactiveSecurityAutoConfiguration.class, ReactiveManagementWebSecurityAutoConfiguration.class })
Varesh
  • 1,648
  • 2
  • 14
  • 22
1

I think what you are looking for is to override the default authentication entry point which is set to BasicAuthenticationEntryPoint.

This entrypoint adds the

"WWW-Authenticate": "Basic realm=..."

header that tells your browser to use Basic Auth.

Marvin
  • 41
  • 1
  • 5
1

If you're extending WebSecurityConfigurerAdapter, you can pass in true to the super constructor to disable the defaults.
You may need to provide other beans if you do this.

    /**
     * Creates an instance which allows specifying if the default configuration should be
     * enabled. Disabling the default configuration should be considered more advanced
     * usage as it requires more understanding of how the framework is implemented.
     *
     * @param disableDefaults true if the default configuration should be disabled, else
     * false
     */
    protected WebSecurityConfigurerAdapter(boolean disableDefaults) {
        this.disableDefaults = disableDefaults;
    }

If you want to disable it just for testing purposes - Rather than completely disabling the auto-configuration, I create an "InsecurityConfiguration" in addition to "SecurityConfiguration", and activate it with either a Spring Profile or Property value.

Technically security is still configured, but wide open.

@Configuration
@ConditionalOnProperty(prefix = "security", value = "disabled", havingValue = "true")
public class InsecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final static Logger log = LoggerFactory.getLogger(InsecurityConfiguration.class);

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.warn("configuring insecure HttpSecurity");
        http.authorizeRequests().anyRequest().permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        log.warn("configuring insecure WebSecurity");
        web.ignoring().antMatchers("/**");
    }

}

Note This is for mvc, not webflux. For Webflux you should create a SecurityWebFilterChain like Bryan mentioned.

This is how I generally disable basic auth in webflux, when using JWT -

    @Bean
    public SecurityWebFilterChain configure(ServerHttpSecurity http) {

        http
        .authorizeExchange().anyExchange().authenticated().and()
            .httpBasic().disable()
            .formLogin().disable()
            .logout().disable()
            .oauth2ResourceServer()
            .jwt()
            .and()
                .and().exceptionHandling().accessDeniedHandler(problemSupport);
        return http.build();
    }
Jeremy
  • 2,970
  • 1
  • 26
  • 50
  • Not sure why this was marked down. It would be helpful to provide feedback if you mark something down please. – Jeremy Dec 15 '19 at 20:39
  • overriding configure method in web security adapter is enough to stop default login page @Override protected void configure(HttpSecurity http) throws Exception { log.warn("configuring insecure HttpSecurity"); http.authorizeRequests().anyRequest().permitAll(); } – Rajesh Hatwar Mar 18 '20 at 17:24
1

Only properties - works for me (sb2 - 2022):

spring:
  autoconfigure:
    exclude:
      - org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
      - org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration
Andrey D.
  • 31
  • 4
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 30 '22 at 17:29
1

Simple solution for Spring Boot 2.6

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class})
fire_Rising
  • 70
  • 1
  • 7
0

In Spring boot 2, there is no way to disable basic authentication by application.properties file. But the only thing is use annotation

@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})

in the main class. It works

Book Of Zeus
  • 49,509
  • 18
  • 174
  • 171
  • I was unable to get this to work. (Spring Boot 2.1.5, spring-security-web 4.2.3.RELEASE, spring-boot-starter-actuator). Did you have to do anything else? – Brandon May 21 '19 at 13:34
0

The problem is with org.springframework.security.web.server.authorization.ExceptionTranslationWebFilter

it has private ServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint();

so to fix it during ServerHttpSecurity initialization add:

http.exceptionHandling().authenticationEntryPoint(HttpStatusServerEntryPoint(HttpStatus.FORBIDDEN))

Looks like vanilla (servlet) spring uses org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer#createDefaultEntryPoint

private AuthenticationEntryPoint createDefaultEntryPoint(H http) {
        if (this.defaultEntryPointMappings.isEmpty()) {
            return new Http403ForbiddenEntryPoint();
        }
        if (this.defaultEntryPointMappings.size() == 1) {
            return this.defaultEntryPointMappings.values().iterator().next();
        }
        DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(
                this.defaultEntryPointMappings);
        entryPoint.setDefaultEntryPoint(this.defaultEntryPointMappings.values().iterator()
                .next());
        return entryPoint;
    }

Side note: mutable fields in builder style beans (like ExceptionTranslationWebFilter) make spring code hard to debug (too magic configuration as well)

ichaki5748
  • 1,993
  • 1
  • 14
  • 13
0

You should add @EnableWebSecurity to enable a custom security configuration. After that simply disable the form login

@Configuration
@EnableWebSecurity
public class StackWebSecurityConfigurerAdapter extends 
WebSecurityConfigurerAdapter {
 @Override
 protected void configure(HttpSecurity http) throws Exception {
    http.formLogin().disable();
 }

}

Irshad
  • 1,016
  • 11
  • 30
0

This worked for me

@SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
class SpringApplication{
 ...
}
Nishan B
  • 627
  • 7
  • 11