Nice programing

Spring Boot에서 "기본 보안 암호 사용"제거

nicepro 2021. 1. 9. 11:36
반응형

Spring Boot에서 "기본 보안 암호 사용"제거


Spring Boot의 애플리케이션에 하나의 사용자 정의 보안 구성을 추가했지만 "기본 보안 비밀번호 사용"에 대한 메시지는 여전히 LOG 파일에 있습니다.

제거 할 것이 있습니까? 이 기본 암호는 필요하지 않습니다. 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();
    }
}

SecurityAutoConfiguration 클래스 제외에 대한 해결책을 찾았습니다 .

예:

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

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

다음을 추가하면 application.properties나를 위해 일했습니다.

security.basic.enabled=false

응용 프로그램을 다시 시작하고 콘솔에서 확인하십시오.


작동하지만 현재 솔루션은 일부 의견에서 언급했듯이 약간 과잉입니다. 그래서 여기에 최신 Spring Boot (1.4.3)를 사용하는 대안이 있습니다.

기본 보안 비밀번호는 Spring Boot의 AuthenticationManagerConfiguration 클래스 내에 구성됩니다 . 이 클래스에는 AuthenticationManager Bean이 이미 정의 된 경우로드되지 않도록하는 조건부 주석이 있습니다.

다음 코드는 현재 AuthenticationManager를 빈으로 정의하기 때문에 AuthenticationManagerConfiguration 내부에서 코드 실행을 방지하기 위해 작동합니다.

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

}

Spring Boot 2.0.4를 사용하여 동일한 문제가 발생했습니다.

제외하면 SecurityAutoConfiguration.class내 응용 프로그램이 파괴되었습니다.

이제 사용하고 있습니다 @SpringBootApplication(exclude= {UserDetailsServiceAutoConfiguration.class})

@EnableResourceServerJWT 와 잘 작동합니다.:)


조회 : http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html

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

기본값 인 메모리 내 인증을 사용하는 경우 org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration에 대한 로거 구성을 사용자 정의하고이 메시지를 제거하십시오.


@SpringBootApplication 주석을 사용하여 SecurityAutoConfiguration을 제외하면 작동하지 않았지만 @EnableAutoConfiguration에서 제외하면 작동했습니다.

@EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class })

구성을 별도의 패키지로 선언하는 경우 다음과 같이 구성 요소 스캔을 추가해야합니다.

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

    public class MyApplication {

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



    }

다음과 같이 구성 클래스에 @component 주석을 추가해야 할 수도 있습니다.

  @Component
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

.....
  1. 또한 브라우저 캐시를 지우고 시크릿 모드에서 스프링 부트 앱을 실행하십시오.

Reactive Stack (Spring Webflux, Netty)의 경우 ReactiveUserDetailsServiceAutoConfiguration.class를 제외해야합니다.

@SpringBootApplication(exclude = {ReactiveUserDetailsServiceAutoConfiguration.class})

또는 ReactiveAuthenticationManager bean을 정의하십시오 (다른 구현이 있습니다. 여기에 JWT 하나의 예가 있습니다)

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

스프링 부트를 사용할 때 우리는 애플리케이션 클래스와 정확히 아래와 같이 보안을 구성하는 위치 모두에서 SecurityAutoConfiguration.class를 제외해야합니다.

그러면 우리만이 기본 보안 암호를 피할 수 있습니다.

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

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

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


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


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

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


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

ReferenceURL : https://stackoverflow.com/questions/30761253/remove-using-default-security-password-on-spring-boot

반응형