简体   繁体   English

删除 Spring Boot 上的“使用默认安全密码”

[英]Remove "Using default security password" on Spring Boot

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.我在 Spring Boot 的应用程序中添加了一个自定义安全配置,但是关于“使用默认安全密码”的消息仍然存在于 LOG 文件中。

Is there any to remove it?有什么可以删除的吗? I do not need this default password.我不需要这个默认密码。 It seems Spring Boot is not recognizing my security policy.似乎 Spring Boot 没有识别我的安全策略。

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

I found out a solution about excluding SecurityAutoConfiguration class.我找到了一个关于排除SecurityAutoConfiguration类的解决方案。

Example:例子:

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

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

Using Spring Boot 2.0.4 I came across the same issue.使用 Spring Boot 2.0.4 我遇到了同样的问题。

Excluding SecurityAutoConfiguration.class did destroy my application.排除SecurityAutoConfiguration.class确实破坏了我的应用程序。

Now I'm using @SpringBootApplication(exclude= {UserDetailsServiceAutoConfiguration.class})现在我正在使用@SpringBootApplication(exclude= {UserDetailsServiceAutoConfiguration.class})

Works fine with @EnableResourceServer and JWT :)@EnableResourceServer和 JWT 一起工作正常:)

Adding following in application.properties worked for me,application.properties添加以下内容对我有用,

security.basic.enabled=false

Remember to restart the application and check in the console.请记住重新启动应用程序并检查控制台。

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).所以这里有一个对我有用的替代方案,使用最新的 Spring Boot (1.4.3)。

The default security password is configured inside Spring Boot's AuthenticationManagerConfiguration class.默认安全密码在 Spring Boot 的AuthenticationManagerConfiguration类中配置。 This class has a conditional annotation to prevent from loading if a AuthenticationManager Bean is already defined.如果已经定义了 AuthenticationManager Bean,则此类具有条件注释以防止加载。

The folllowing code works to prevent execution of the code inside AuthenticationManagerConfiguration because we define our current AuthenticationManager as a bean.以下代码用于防止在 AuthenticationManagerConfiguration 中执行代码,因为我们将当前的 AuthenticationManager 定义为 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();
}

}

For Reactive Stack (Spring Webflux, Netty) you either need to exclude ReactiveUserDetailsServiceAutoConfiguration.class对于反应式堆栈(Spring Webflux,Netty),您需要排除 ReactiveUserDetailsS​​erviceAutoConfiguration.class

@SpringBootApplication(exclude = {ReactiveUserDetailsServiceAutoConfiguration.class})

Or define ReactiveAuthenticationManager bean (there are different implementations, here is the JWT one example)或者定义 ReactiveAuthenticationManager bean(有不同的实现,这里是 JWT 的一个例子)

@Bean
public ReactiveJwtDecoder jwtDecoder() {
    return new NimbusReactiveJwtDecoder(keySourceUrl);
}
@Bean
public ReactiveAuthenticationManager authenticationManager() {
    return new JwtReactiveAuthenticationManager(jwtDecoder());
}

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.在 Spring 应用程序的上下文中,在application.properties (名称可能不同)中设置默认的安全用户名和密码。

To avoid default configuration (as a part of autoconfiguration of the SpringBoot) at all - use the approach mentioned in Answers earlier:为了完全避免默认配置(作为 SpringBoot 自动配置的一部分) - 使用前面的 Answers 中提到的方法:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })

or或者

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class })

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这将删除默认密码消息和默认用户,因为在这种情况下,您正在配置 InMemoryAuthentication,并且您不会在后续步骤中指定任何用户

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

From AuthenticationManagerConfiguration.java looking at code, I see below.AuthenticationManagerConfiguration.java查看代码,我在下面看到。 Also the in-memory configuration is a fallback if no authentication manager is provided as per Javadoc .如果没有按照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.如果您使用默认的内存身份验证,请为 org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration 自定义记录器配置并删除此消息。

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.当使用 Spring Boot 时,我们应该在应用程序类中以及您正在配置安全性的确切位置排除 SecurityAutoConfiguration.class,如下所示。

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

In a Spring Boot 2 application you can either exclude the service configuration from autoconfiguration:在 Spring Boot 2 应用程序中,您可以从自动配置中排除服务配置:

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更多信息可以在这里找到: https ://docs.spring.io/spring-boot/docs/2.0.x/reference/html/boot-features-security.html

You only need to exclude UserDetailsServiceAutoConfiguration.您只需要排除 UserDetailsS​​erviceAutoConfiguration。

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

当我使用 @SpringBootApplication 注释排除 SecurityAutoConfiguration 时它对我不起作用,但是当我在 @EnableAutoConfiguration 中排除它时它确实起作用:

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class })

I came across the same problem and adding this line to my application.properties solved the issue.我遇到了同样的问题,并将这一行添加到我的 application.properties 解决了这个问题。

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.它是 Spring 的 Automatic 之一,您将其排除在外,就像排除执行器等其他东西一样。 I recommend looking at this link我建议查看此链接

If you have enabled actuator feature (spring-boot-starter-actuator), additional exclude should be added in application.yml:如果您启用了执行器功能(spring-boot-starter-actuator),则应在 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.在 Spring Boot 版本 2.3.4.RELEASE 中测试。

If you use Spring Security with spring cloud gateway, you can exclude the ReactiveUserDetailsServiceAutoConfiguration.class .如果您将 Spring Security 与 Spring Cloud Gateway 一起使用,则可以排除ReactiveUserDetailsServiceAutoConfiguration.class

Like this像这样

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

Check documentation for org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration there are conditions when autoconfig will be halt.检查org.springframework.boot.autoconfigure.security.servlet.UserDetailsS​​erviceAutoConfiguration的文档有自动配置停止的条件。

In my case I forgot to define my custom AuthenticationProvider as bean .在我的情况下,我忘记将我的自定义AuthenticationProvider定义为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);
    }
}

We should exclude UserDetailsServiceAutoConfiguration.class from spring boot autoconfiguration to fix this我们应该从 Spring Boot 自动配置中排除 UserDetailsS​​erviceAutoConfiguration.class 来解决这个问题

example:例子:

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

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

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.相反,我们应该使用 Spring Boot。

The log message is generated by UserDetailsServiceAutoConfiguration to let us know Spring Boot put in a sensible default.日志消息由UserDetailsServiceAutoConfiguration生成,让我们知道 Spring Boot 设置了合理的默认值。 And looking at the source and documentation for UserDetailsServiceAutoConfiguration we see:查看UserDetailsServiceAutoConfiguration的源代码和文档,我们看到:

/**
 * {@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 .我们可以看到,当提供以下任何 bean 时, UserDetailsServiceAutoConfiguration被禁用: AuthenticationManagerAuthenticationProviderUserDetailsServiceAuthenticationManagerResolver

This means that when tell Spring Boot how we want to authenticate our users, Spring Boot will not auto-configure a sensible default.这意味着当告诉 Spring Boot 我们想要如何验证我们的用户时,Spring Boot 不会自动配置一个合理的默认值。 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");
        };
    }
}

If you are using Spring Boot version >= 2.0 try setting this bean in your configuration:如果您使用的是 Spring Boot 版本 >= 2.0,请尝试在您的配置中设置此 bean:

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

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

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 注释,如下所示:

  @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同时清除浏览器缓存并在隐身模式下运行 Spring Boot 应用程序

在带有 webflux 的 spring boot 2 上,您需要定义一个ReactiveAuthenticationManager

也可以只在属性中关闭该特定类的日志记录:

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

Just Adding below property to application.properties只需将以下属性添加到 application.properties

spring.security.user.name=xyz
spring.security.user.password=xxxxxxx

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如果缺少以下 bean(JwtDecoder,OpaqueTokenIntrospector,ClientRegistrationRepository) - 然后我们看到密码生成被调用

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将 UserDetailsS​​erviceAutoConfiguration.class 添加到排除项,然后我们没有在日志中看到密码生成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM