123

I added one custom Security Config in my application on Spring Boot, but the message about "Using default security password" is still there in LOG file.

Is there any to remove it? I do not need this default password. It seems Spring Boot is not recognizing my security policy.

@Configuration
@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {

    private final String uri = "/custom/*";

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().httpStrictTransportSecurity().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Authorize sub-folders permissions
        http.antMatcher(uri).authorizeRequests().anyRequest().permitAll();
    }
}
Carlos Alberto
  • 7,761
  • 13
  • 52
  • 72
  • 1
    Is this class in the correct package and thus can be found ? I made this mistake some months ago ... Would it be sufficient to set the password to a known value (I assume not ...) ? – Marged Jun 10 '15 at 15:56
  • Perhaps you have a similar problem like I had. I was lucky and Mr. Syer gave me the answer ;-) http://stackoverflow.com/questions/27981681/which-annotation-shall-i-use-to-keep-spring-boot-from-securing-my-controller-whe – Marged Jun 10 '15 at 15:57
  • There's another config class which import this security config @Import({ CustomSecurityConfig .class }). This class is scanned by Spring Boot, what I noticed in another case related to CAS security, Spring Boot only removed this message when I did @Inject public void configureGlobal(final AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { – Carlos Alberto Jun 10 '15 at 17:04
  • 3
    I tried adding security.basic.enabled=false and nothing has changed. – Carlos Alberto Jun 10 '15 at 17:07
  • Did you check- http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html – randominstanceOfLivingThing Jun 10 '15 at 17:47
  • Yes, read but I did not found a solution for my issue.. do you have any idea what I missing? – Carlos Alberto Jun 10 '15 at 17:59
  • 1
    Right answer is: wrong package. This bug raise when you copy folder and paste to you project. You can refactor folder to right package and done. – Nguyên Ngô Duy Nov 26 '20 at 02:12

26 Answers26

83

I found out a solution about excluding SecurityAutoConfiguration class.

Example:

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

    public static void main(String[] args) throws Exception {
        SpringApplication.run(MyApplication.class, args);
    }
}
Carlos Alberto
  • 7,761
  • 13
  • 52
  • 72
  • 1
    The only inconvenient with this solution it disables the ability to read security properties from application.properties, so you must control yourself after it. – Carlos Alberto Jun 11 '15 at 03:05
  • 47
    I wonder: What's the point of adding Spring Security to Boot which actually has a good auto configuration and than disabling everything? Even considering just turning off logging? Do you want security? I think so. Do you want a default generated password? Maybe no… So why don't you specify one? Just use those properties: security.user.name=user # Default user name. security.user.password= # Password for the default user name. A random password is logged on startup by default. Or run your own UserDetailsService… – Michael Simons Apr 10 '16 at 16:43
  • 5
    @MichaelSimons For example in my ongoing project we only use 3rd party user pool - AWS Cognito. So we don't need Spring's autoconfigured user service at all. We only use tokens provided by Cognito. So I just excluded the ReactiveUserDetailsServiceAutoConfiguration.class from Application (as we use webflux) – alexkov Aug 06 '19 at 12:34
  • 8
    A great example of a completely wrong answer which has millions of score points – amseager Nov 27 '20 at 13:27
  • 1
    This is opening a peanut with a hammer. Removing SecurityAutoConfig eliminates ALL security auto configuration, more than what was requested in the original question. See the other responses about providing your own InMemoryAuthentication provider, adding properties for user/password, or explicitly creating the AuthenticationManager bean, all of which focus on the default user. – Ken Krueger Feb 25 '22 at 20:11
74

Using Spring Boot 2.0.4 I came across the same issue.

Excluding SecurityAutoConfiguration.class did destroy my application.

Now I'm using @SpringBootApplication(exclude= {UserDetailsServiceAutoConfiguration.class})

Works fine with @EnableResourceServer and JWT :)

Benjamin M
  • 23,599
  • 32
  • 121
  • 201
  • 2
    Can you explain where to write this code please? and what you mean by "works fine with @EnableResourceServer and JWT" (Im new to spring boot and jwt) Thanks! – Gel Jun 06 '19 at 16:31
  • 1
    To me it worked with this exclusion in @EnableAutoConfiguration instead of @SpringBootApplication (SpringBoot 2.3.0): `@SpringBootApplication @EnableAutoConfiguration(exclude={UserDetailsServiceAutoConfiguration.class}) public class MainAppClassName { ... }` – Felipe de Alvarenga Leite Jul 29 '20 at 16:02
  • `@EnableAutoConfiguration` is part of `@SpringBootApplication`. – jumping_monkey Aug 21 '20 at 08:53
  • solve the problem – ahmed Feb 05 '23 at 12:22
41

Although it works, the current solution is a little overkill as noted in some comments. So here is an alternative that works for me, using the latest Spring Boot (1.4.3).

The default security password is configured inside Spring Boot's AuthenticationManagerConfiguration class. This class has a conditional annotation to prevent from loading if a AuthenticationManager Bean is already defined.

The folllowing code works to prevent execution of the code inside AuthenticationManagerConfiguration because we define our current AuthenticationManager as a bean.

@Configuration
@EnableWebSecurity
public class MyCustomSecurityConfig extends WebSecurityConfigurerAdapter{

[...]

@Override
protected void configure(AuthenticationManagerBuilder authManager) throws Exception {
    // This is the code you usually have to configure your authentication manager.
    // This configuration will be used by authenticationManagerBean() below.
}

@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    // ALTHOUGH THIS SEEMS LIKE USELESS CODE,
    // IT'S REQUIRED TO PREVENT SPRING BOOT AUTO-CONFIGURATION
    return super.authenticationManagerBean();
}

}
Stefan
  • 506
  • 4
  • 8
  • `@EnableWebSecurity` is not required to make it work – pierrefevrier Jan 18 '18 at 10:25
  • Works for me using Spring Boot 2.5.2 by adding that `authenticationManagerBean()` method override. There was no need to use `@EnableWebSecurity`. – Wim Deblauwe Jul 19 '21 at 13:27
  • In current versions of spring `WebSecurityConfigurerAdapter` is deprecated. Could you please suggest solution having that in mind? :) – denu Nov 14 '22 at 15:22
  • You could just setup the bean in any configuration class (without the need to extend the adapter) and return the authenticationManager from the authenticationConfiguration or any other authentificationManager `@Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); }` – gemorra Jan 06 '23 at 21:21
37

Adding following in application.properties worked for me,

security.basic.enabled=false

Remember to restart the application and check in the console.

Lucky
  • 16,787
  • 19
  • 117
  • 151
30

So most of the answers to this question recommend either:

  • excluding some auto-configuration
  • setting up a user and/or password

However excluding auto-configuration is hardly ever the answer. And if your application does not have any users the second solution is not great either.

Instead we should work with Spring Boot.

The log message is generated by UserDetailsServiceAutoConfiguration to let us know Spring Boot put in a sensible default. And looking at the source and documentation for UserDetailsServiceAutoConfiguration we see:

/**
 * {@link EnableAutoConfiguration Auto-configuration} for a Spring Security in-memory
 * {@link AuthenticationManager}. Adds an {@link InMemoryUserDetailsManager} with a
 * default user and generated password. This can be disabled by providing a bean of type
 * {@link AuthenticationManager}, {@link AuthenticationProvider} or
 * {@link UserDetailsService}.
 *
 * @author Dave Syer
 * @author Rob Winch
 * @author Madhura Bhave
 * @since 2.0.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(AuthenticationManager.class)
@ConditionalOnBean(ObjectPostProcessor.class)
@ConditionalOnMissingBean(
        value = { AuthenticationManager.class, AuthenticationProvider.class, UserDetailsService.class,
                AuthenticationManagerResolver.class },
        type = { "org.springframework.security.oauth2.jwt.JwtDecoder",
                "org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector",
                "org.springframework.security.oauth2.client.registration.ClientRegistrationRepository" })
public class UserDetailsServiceAutoConfiguration {

We can see that the UserDetailsServiceAutoConfiguration is disabled when any of these beans are provided: AuthenticationManager, AuthenticationProvider, UserDetailsService, or AuthenticationManagerResolver.

This means that when tell Spring Boot how we want to authenticate our users, Spring Boot will not auto-configure a sensible default. Since we don't want to authenticate any users we can provide:

@Configuration
public class ApplicationConfiguration {

    @Bean
    public AuthenticationManager noopAuthenticationManager() {
        return authentication -> {
            throw new AuthenticationServiceException("Authentication is disabled");
        };
    }
}
M.P. Korstanje
  • 10,426
  • 3
  • 36
  • 58
16

For Reactive Stack (Spring Webflux, Netty) you either need to exclude ReactiveUserDetailsServiceAutoConfiguration.class

@SpringBootApplication(exclude = {ReactiveUserDetailsServiceAutoConfiguration.class})

Or define ReactiveAuthenticationManager bean (there are different implementations, here is the JWT one example)

@Bean
public ReactiveJwtDecoder jwtDecoder() {
    return new NimbusReactiveJwtDecoder(keySourceUrl);
}
@Bean
public ReactiveAuthenticationManager authenticationManager() {
    return new JwtReactiveAuthenticationManager(jwtDecoder());
}
alexkov
  • 435
  • 2
  • 7
  • 13
14

You only need to exclude UserDetailsServiceAutoConfiguration.

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration
Nick
  • 235
  • 2
  • 7
12

We should exclude UserDetailsServiceAutoConfiguration.class from spring boot autoconfiguration to fix this

example:

@SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class })
public class MyClass {

public static void main(String[] args) {
    SpringApplication.run(MyClass.class, args);
}
Nikhil Kamani
  • 850
  • 9
  • 12
10

To remove the default user you need to configure authentication manager with no users for example:

@configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication();
    }
}

this will remove default password message and default user because in that case you are configuring InMemoryAuthentication and you will not specify any user in next steps

Ivonet
  • 2,492
  • 2
  • 15
  • 28
  • It will work for in-memory auth, as it *overwrites* the `InMemoryUserDetailsManager`, but for other auth, such as ldap, that does not work. – jumping_monkey Sep 30 '22 at 01:31
6

Just use the rows below:

spring.security.user.name=XXX
spring.security.user.password=XXX

to set the default security user name and password at your application.properties (name might differ) within the context of the Spring Application.

To avoid default configuration (as a part of autoconfiguration of the SpringBoot) at all - use the approach mentioned in Answers earlier:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })

or

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class })
5

In a Spring Boot 2 application you can either exclude the service configuration from autoconfiguration:

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

or if you just want to hide the message in the logs you can simply change the log level:

logging.level.org.springframework.boot.autoconfigure.security=WARN

Further information can be found here: https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/boot-features-security.html

mguser
  • 59
  • 1
  • 4
3

Look up: http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html

From AuthenticationManagerConfiguration.java looking at code, I see below. Also the in-memory configuration is a fallback if no authentication manager is provided as per Javadoc. Your earlier attempt of Injecting the Authentication Manager would work because you will no longer be using the In-memory authentication and this class will be out of picture.

@Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        if (auth.isConfigured()) {
            return;
        }
        User user = this.securityProperties.getUser();
        if (user.isDefaultPassword()) {
            logger.info("\n\nUsing default security password: " + user.getPassword()
                    + "\n");
        }
        Set<String> roles = new LinkedHashSet<String>(user.getRole());
        withUser(user.getName()).password(user.getPassword()).roles(
                roles.toArray(new String[roles.size()]));
        setField(auth, "defaultUserDetailsService", getUserDetailsService());
        super.configure(auth);
    }

If you use inmemory authentication which is default, customize your logger configuration for org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration and remove this message.

randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72
  • I have overwritten my configure method as you said, and Spring message stills shows. What's funny in one simple Spring MVC application not using Boot it works fine. The problem is related to Spring Boot, take a look at code added to my CustomSecurityConfig to override the method: @Override public void configure(AuthenticationManagerBuilder auth) throws Exception {} – Carlos Alberto Jun 10 '15 at 21:24
3

When spring boot is used we should exclude the SecurityAutoConfiguration.class both in application class and where exactly you are configuring the security like below.

Then only we can avoid the default security password.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
@EnableJpaRepositories
@EnableResourceServer
public class Application {

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

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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;

    @Configuration
    @EnableWebSecurity
    @EnableAutoConfiguration(exclude = { 
            org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class 
        })
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.authorizeRequests().anyRequest().authenticated();
            httpSecurity.headers().cacheControl();
        }
    }
Sasidhar
  • 111
  • 1
  • 1
  • 7
3

I came across the same problem and adding this line to my application.properties solved the issue.

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

It's one of the Spring's Automatic stuffs which you exclude it like excluding other stuffs such as actuators. I recommend looking at this link

Eric
  • 460
  • 6
  • 15
3

If you use Spring Security with spring cloud gateway, you can exclude the ReactiveUserDetailsServiceAutoConfiguration.class.

Like this

@SpringBootApplication(exclude = ReactiveUserDetailsServiceAutoConfiguration.class)
public class SpringClientApplication {

Amrut Prabhu
  • 1,161
  • 11
  • 11
3

A lot of answers here are actually trying to work against Spring Boot instead of working with the framework.

If you don't have any local users - because for example authentication is managed exclusively with JWT tokens - just tell Spring Boot so.

Declare an empty UserDetailsService as part of your SecurityConfiguration instead of trying to exclude parts of the auto configuration, or setting an unnecessary default user/password in application.properties:

@Configuration
@EnableWebSecurity
class SecurityConfiguration {

   @Bean
   UserDetailsService emptyDetailsService() {
       return username -> { throw new UsernameNotFoundException("no local users, only JWT tokens allowed"); };
   }

   // rest of your security config

}
Stefan Haberl
  • 9,812
  • 7
  • 72
  • 81
2

Check documentation for org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration there are conditions when autoconfig will be halt.

In my case I forgot to define my custom AuthenticationProvider as bean.

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(getAuthenticationProvider());
    }

    @Bean
    AuthenticationProvider getAuthenticationProvider() {
        return new CustomAuthenticationProvider(adminService, onlyCorporateEmail);
    }
}
2

It didn't work for me when I excluded SecurityAutoConfiguration using @SpringBootApplication annotation, but did work when I excluded it in @EnableAutoConfiguration:

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class })
adlerer
  • 1,010
  • 11
  • 14
2

If you have enabled actuator feature (spring-boot-starter-actuator), additional exclude should be added in application.yml:

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration

Tested in Spring Boot version 2.3.4.RELEASE.

Jerry Shang
  • 25
  • 1
  • 6
2

Password generation is done by

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({AuthenticationManager.class})
@ConditionalOnBean({ObjectPostProcessor.class})
@ConditionalOnMissingBean(
    value = {AuthenticationManager.class, AuthenticationProvider.class, UserDetailsService.class},
    type = {"org.springframework.security.oauth2.jwt.JwtDecoder", "org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector", "org.springframework.security.oauth2.client.registration.ClientRegistrationRepository"}
)
public class UserDetailsServiceAutoConfiguration {

if following beans are missing(JwtDecoder,OpaqueTokenIntrospector,ClientRegistrationRepository) - then we see password generation been invoked

so in our case also we came across this issue then we

@SpringBootApplication(exclude = {FlywayAutoConfiguration.class, UserDetailsServiceAutoConfiguration.class})

Added UserDetailsServiceAutoConfiguration.class to exclusion then we did not see the password generation in logs

Community
  • 1
  • 1
0

If you are using Spring Boot version >= 2.0 try setting this bean in your configuration:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http.authorizeExchange().anyExchange().permitAll();
    return http.build();
}

Reference: https://stackoverflow.com/a/47292134/1195507

rvazquezglez
  • 2,284
  • 28
  • 40
0

If you are declaring your configs in a separate package, make sure you add component scan like this :

@SpringBootApplication
@ComponentScan("com.mycompany.MY_OTHER_PACKAGE.account.config")

    public class MyApplication {

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



    }

You may also need to add @component annotation in the config class like so :

  @Component
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

.....
  1. Also clear browser cache and run spring boot app in incognito mode
KHAN
  • 105
  • 2
  • 10
0

On spring boot 2 with webflux you need to define a ReactiveAuthenticationManager

nekperu15739
  • 3,311
  • 2
  • 26
  • 25
0

It is also possible to just turn off logging for that specific class in properties :

logging.level.org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration=WARN

WaBayang
  • 199
  • 1
  • 6
0

Just Adding below property to application.properties

spring.security.user.name=xyz
spring.security.user.password=xxxxxxx
Dr Mido
  • 2,414
  • 4
  • 32
  • 72
Suresh
  • 1
0

If you did not implement UserDetailsService interface, you need to exclude SecurityAutoConfiguration

Implement UserDetailsService interface

@Component
public class UserDetailsServiceImpl implements UserDetailsService{

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // TODO Auto-generated method stub
    return null;
}

Exclude SecurityAutoConfiguration

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
Ali-Alrabi
  • 1,515
  • 6
  • 27
  • 60