59

I'm using spring-boot-starter-security dependency, to make use of several classes that come with spring-security. But as I want to integrate it in an existing vaadin application, I only want to make use of the classes, and not of the default login/auth screen of spring.

How can I disable this screen?

I cannot make any configurations by extending WebSecurityConfigurerAdapter as my main entry class already extends SpringBootServletInitializer. Also, vaadin applications basically run on the same URL path all the time and use internal navigation.

@EnableAutoConfiguration
public class MyApp extends SpringBootServletInitializer { 

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(MyApp.class);
        }

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

So, what could I do to disable the login screen, but though make use of spring security features?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

16 Answers16

103

you can use java based configuration like this :

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity security) throws Exception
    {
     security.httpBasic().disable();
    }
}

and restart your application if it's refresh automatically.

noobdev
  • 1,213
  • 2
  • 8
  • 6
  • I like your solution. Thanks! – Dosi Bingov Feb 21 '19 at 09:47
  • 1
    This config does not change anything as far as I can tell. I thought that providing your own config took precedence over spring config? – peekay Apr 08 '19 at 20:06
  • 16
    You can add `.formLogin().disable()` as well to remove the login screen – Guillaume F. Oct 03 '19 at 11:24
  • This actually works on the current latest version of `Spring Boot 2.2.1.BUILD-SNAPSHOT`. – wonsuc Nov 11 '19 at 14:31
  • 1
    Ok if i use above solution, login page is gone. But still getting 403 from POST requests. Anyone know how to solve this ? – user771 Sep 08 '20 at 11:27
  • Above did work only for GET http calls. For POST review my comments below – Prashant S Sep 27 '21 at 18:44
  • 1
    In version 5.7.0-M2, [the use of WebSecurityConfigurerAdapter has been deprecated](https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter). Now it should be done by registering a SecurityFilterChain component. – alexdefelipe Jul 18 '22 at 16:47
33

The default security in Spring Boot is Basic. You could disable it by setting security.basic.enabled=false. More about this here and here.

Andrei Stefan
  • 51,654
  • 6
  • 98
  • 89
17

Disable the default spring security by excluding it from the autoconfiguration. Add SecurityAutoConfiguration.class to the exclude property of the @SpringBootApplication annotation on your main class. Like follows:

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
Michiel Haisma
  • 786
  • 6
  • 17
  • 2
    Disabling Spring Security is a bad solution. Applications should be secure! – Amir Kost Oct 28 '18 at 12:34
  • OP requests only to have certain classes available on the classpath, not to enable spring security. Spring Boot will enable Spring security automatically when it finds the jars on the classpath. My solution will make sure that this does not happen. – Michiel Haisma Oct 29 '18 at 12:22
10

On the main spring-boot application class (the class which has @SpringBootApplication annotation)

@SpringBootApplication(exclude={SecurityAutoConfiguration.class})
Semir Umut Kurt
  • 485
  • 5
  • 12
7

There seems to be a simpler solution.

Simply put this annotationabove your main class or the same place as your SpingBootApplication annotation

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

Fangming
  • 24,551
  • 6
  • 100
  • 90
6

You can use this code in new versions of spring boot (3.0.0-m4) and reactive model ( webflux )

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
   @Bean
    public SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
    return http
            .httpBasic().disable()
            .build();
}
}
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
Pouya
  • 71
  • 1
  • 1
4

To completely disable the login route use Spring Security configuration object

The following snippet uses org.springframework.boot:2.1.6.RELEASE

@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
  override fun configure(security: HttpSecurity) {
    super.configure(security)

    security.httpBasic().disable()

    security.cors().and().csrf().disable().authorizeRequests()
      .anyRequest().authenticated()
      .and().formLogin().disable() // <-- this will disable the login route
      .addFilter(JWTAuthorizationFilter(authenticationManager()))
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  }

  @Bean
  fun corsConfigurationSource(): CorsConfigurationSource {
    val source = UrlBasedCorsConfigurationSource()
    val config = CorsConfiguration().applyPermitDefaultValues()
    config.addExposedHeader("Authorization")
    source.registerCorsConfiguration("/**", config)
    return source
  }
}
nilobarp
  • 3,806
  • 2
  • 29
  • 37
4

This worked for me

            @Configuration
            @EnableWebSecurity
            public class SecurityConfig extends WebSecurityConfigurerAdapter {
                @Override
                protected void configure(HttpSecurity security) throws Exception
                {
                 //security.httpBasic().disable(); // Did work only for GET     
                 security.csrf().disable().authorizeRequests().anyRequest().permitAll(); // Works for GET, POST, PUT, DELETE
                }
            }          
Prashant S
  • 349
  • 4
  • 14
1

This is to help anyone else struggling to remove the default Spring Boot login screen and have some secured paths. This worked for me with Spring Boot 2.3.4 and the spring-boot-security starter and this article: https://www.toptal.com/spring/spring-security-tutorial helped me. This config allows a GET to /api/config-props and /actuator/health but requires auth on any other actuator path or any other api path. Then finally allows a GET for any other bit that might be served static content in /resources or /public etc.

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity security) throws Exception {
    // Enable CORS and disable CSRF
    security = security.cors().and().csrf().disable();

    // Set session management to stateless
    security = security
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and();

    // Set permissions on endpoints
    security.authorizeRequests()
            // Our public endpoints, secured endpoints and then open everything else that is static resource stuff
            .antMatchers(HttpMethod.GET, "/api/config-props").permitAll()
            .antMatchers(HttpMethod.GET, "/actuator/health").permitAll()
            .antMatchers("/actuator**").authenticated()
            .antMatchers("/api/**").authenticated()
            .antMatchers(HttpMethod.GET, "/**").permitAll();
  }
}
Noah Overcash
  • 121
  • 3
  • 14
Randy
  • 729
  • 5
  • 14
1

Please note that the use of WebSecurityConfigurerAdapter has been deprecated in the recent Spring versions instead you should be using the SecurityFilterChain as per Spring Documentation https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

sharing the below code for the same

    @Configuration
    public class SecurityConfiguration {
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http
                .authorizeHttpRequests((authz) -> authz
                    .anyRequest().authenticated()
                )
                .httpBasic(withDefaults());
            return http.build();
        }
    
        @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers("/*");
    }
    }

In the RequestMatchers I have allowed all endpoints without Spring Security whereas you can specify the only endpoints which needs to be exposed without Spring Security

1

Example that works using Spring 6, Boot 3, Java 17.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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
@EnableWebFluxSecurity
public class WebConfig {
    @Bean
    public SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
        return http
                .httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
                .build();
    }
}

Also don't forget to add your required modules if you haven't already.

    requires spring.webflux;
    requires spring.security.config;
    requires spring.security.web;

You should of course replace your basic HTTP authentication with something more secure.

0

If someone still needs the solution, put a method in the REST controller like this:

@RestController
public class myRestController{

    @GetMapping("/login")
    public String redirectTo(){
        return "yourRedirectLink";
    }

}

This solution is very good to work with spring and react packed in a jar

JeremyW
  • 5,157
  • 6
  • 29
  • 30
0

Just remove/comment out below Dependencies from your Project's POM.xml files:

    <!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-security</artifactId>-->
<!--        </dependency>-->

and

    <!--        <dependency>-->
<!--            <groupId>org.springframework.security</groupId>-->
<!--            <artifactId>spring-security-test</artifactId>-->
<!--            <scope>test</scope>-->
<!--        </dependency>-->

0

This code perfectly worked for me, just add it to the main Class of your project

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
0

For me .httpBasic().disable() was not working, in browser, if unauthorised it still showed login form.

What helped for me (webflux):

security.exceptionHandling().authenticationEntryPoint { exchange, ex ->
    exchange.response.statusCode = HttpStatus.UNAUTHORIZED
    exchange.response.setComplete()
}

Behind the scene, WWW-Authenticate http header causes it, and Spring adds it in HttpBasicServerAuthenticationEntryPoint class.

martin195
  • 21
  • 3
  • Where is this code implemented ? And how does security.exceptionHandling().authenticationEntryPoint disables the login form ? Any links? – Himmels DJ Jan 21 '23 at 12:49
0

Without WebSecurityConfigurerAdapter

Kotlin

@Configuration
class SecurityConfiguration {
    @Bean
    @Throws(Exception::class)
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        return http
            .httpBasic().disable()
            .build()
    }
}

Diana
  • 935
  • 10
  • 31