Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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.

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

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

@SpringBootApplication(exclude={SecurityAutoConfiguration.class})

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

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

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

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

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

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

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

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

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

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })

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.

Without WebSecurityConfigurerAdapter

Kotlin

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top