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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30761253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:08:16  来源:igfitidea点击:

Remove "Using default security password" on Spring Boot

javaspringspring-bootspring-security

提问by Carlos Alberto

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

采纳答案by Carlos Alberto

I found out a solution about excluding SecurityAutoConfigurationclass.

我找到了一个关于排除SecurityAutoConfiguration类的解决方案。

Example:

例子:

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

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

回答by randominstanceOfLivingThing

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

AuthenticationManagerConfiguration.java看代码,我看到下面。如果没有按照Javadoc提供身份验证管理器,则内存中配置也是一种后备。您之前尝试注入身份验证管理器会起作用,因为您将不再使用内存中身份验证,并且此类将无法使用。

@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 自定义记录器配置并删除此消息。

回答by Lucky

Adding following in application.propertiesworked for me,

添加以下application.properties对我有用,

security.basic.enabled=false

Remember to restart the application and check in the console.

请记住重新启动应用程序并检查控制台。

回答by Stefan

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 AuthenticationManagerConfigurationclass. This class has a conditional annotation to prevent from loading if a AuthenticationManager Bean is already defined.

默认安全密码在 Spring Boot 的AuthenticationManagerConfiguration类中配置。如果已经定义了 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();
}

}

回答by Sasidhar

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

回答by Vova Perebykivskyi

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

检查org.springframework.boot.autoconfigure.security.servlet.UserDetailsS​​erviceAutoConfiguration 的文档,有条件自动配置将停止。

In my case I forgot to define my custom AuthenticationProvideras 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);
    }
}

回答by adlerer

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

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

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class })

回答by rvazquezglez

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

回答by Benjamin M

Using Spring Boot 2.0.4 I came across the same issue.

使用 Spring Boot 2.0.4 我遇到了同样的问题。

Excluding SecurityAutoConfiguration.classdid destroy my application.

排除SecurityAutoConfiguration.class确实破坏了我的应用程序。

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

现在我正在使用 @SpringBootApplication(exclude= {UserDetailsServiceAutoConfiguration.class})

Works fine with @EnableResourceServerand JWT :)

@EnableResourceServer与 JWT一起工作正常:)

回答by KHAN

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 :

您可能还需要在 config 类中添加 @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
  1. 还要清除浏览器缓存并在隐身模式下运行 spring boot 应用程序