programing

Spring Boot 2.0 기본 보안 비활성화

jooyons 2023. 3. 31. 22:01
반응형

Spring Boot 2.0 기본 보안 비활성화

JWT 스프링 시큐리티하다, 하다, 디디디디 디디디 있디다다있시키려고 시키려고 합니다. 시키려면 , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , .application.properties는 2.0또는 2.0에서 되지 않습니다.

내가 시도한 건 다음과 같다.

@Configuration
public class StackWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable();
        // http.authorizeRequests().anyRequest().permitAll(); // Also doesn't work.
    }
}

기본 보안을 해제하려면 어떻게 해야 합니까?


플럭스를 .

★★★★★★★★★★★★★★★★★★:
기본 로그인 폼

Spring 2.0의 새로운 업데이트에 따르면 Spring Security가 클래스 경로에 있는 경우 Spring Boot에 의해 @Enable Web Security가 추가됩니다.따라서 application.properties에 엔트리를 추가하는 것은 동작하지 않습니다(즉, 이러한 방법으로 커스터마이즈 할 수 없게 됩니다).자세한 내용은 공식 웹 사이트 Spring Boot 2.0의 보안 변경 사항을 참조하십시오.

고객의 요건에 대해서는 정확하게 알 수 없지만, 다음과 같은 회피책을 생각할 수 있습니다.

@Configuration
@EnableWebSecurity
public class SecurityConfiguration  extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests().antMatchers("/").permitAll();
    }
}

이게 도움이 됐으면 좋겠다.

Spring Boot 2.1 이후 spring-boot-actuator를 포함하면 보안만 제외하는 것만으로는 충분하지 않습니다.자동 설정. Management Web Security도 제외해야 합니다.다음과 같은 자동 구성:

@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class })

레퍼런스 매뉴얼에 따르면 WebFlux를 사용한 모든 요구를 허용하기 위한 보안 설정은 다음과 같습니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

@Configuration
public class SecurityConfig {

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

이 방법은 효과가 있었습니다.

@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }
}

응용 프로그램 클래스에 다음 항목을 추가/수정할 수 있습니다.

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

}

새로운 답변을 덧붙여서, 모두 액튜에이터를 사용하는 것 같습니다.그렇지 않으면 1개의 클래스 제외로 충분하다고 생각합니다만, 속성으로 무효로 할 수 있었습니다.

spring:
  autoconfigure:
    exclude: ${spring.autoconfigure.sac}, ${spring.autoconfigure.mwsas}
    sac: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
    mwsas: org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration

길이를 그대로 유지하기 위해 속성을 통해 두 개의 자동 구성 클래스를 참조했습니다(인텔리J Ultimate는 이러한 플레이스 홀더 값이 무엇인지, 그리고 실제로 정규 클래스인지 알 수 없기 때문에 참조하면 울음을 터뜨리므로 신경이 쓰이는 경우 인라인으로 합니다).

단, 어플리케이션은 다음 요구대로 기동하지 않습니다.

https://www.baeldung.com/spring-boot-security-autoconfiguration

「」를 디세블로 SecurityAutoConfiguration

정상적으로 동작했을 경우, 자동 생성 패스워드가 표시되지 않게 됩니다.또, 시큐러티가 모든 것을 허가하고 있는 한, 로그를 읽어내는 개발은, 기본적인 인증용으로 생성된 패스워드와 혼동하지 않기 때문에, 허가된 회답보다 조금 더 혼란스럽지 않습니다.

main auto config 클래스를 디세블로 하는 것만으로는 불충분한 이유는 다음과 같습니다.

@Configuration
class ManagementWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .requestMatchers(
                        EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class))
                .permitAll().anyRequest().authenticated().and().formLogin().and()
                .httpBasic();
    }

}

액튜에이터와 보안 구성을 분할하기 위해 많은 작업이 이루어졌고, 이제는 더욱 간단해졌지만, 이와 같은 아티팩트는 여전히 존재합니다.만약 내가 틀렸다면 봄철 데브스가 고쳐줄 것이다:-)

이용했습니다.@ConditionalOnProperty 짐을 싣다SecurityConfig.java를 설정하면)spring.security.enabled스프링 보안을 해제하기 위해 어플리케이션.yml에서 속성을 false로 설정합니다.이 기능은 매우 효과적입니다.

@ConditionalOnProperty(name = "spring.security.enabled", havingValue = "false")
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests().antMatchers("/").permitAll();
    }
}

WebFlux 기반 애플리케이션이나 Spring Cloud Gateway 애플리케이션에서 이 문제를 겪고 있는 사람은 다음과 같습니다.

@EnableWebFluxSecurity
public class InsecurityConfiguration {
    // @formatter:off
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
         http
              .authorizeExchange()
                   .anyExchange().permitAll();
         return http.build();
    }
}

Spring Boot Reactive Web 애플리케이션의 디폴트보안을 디세블로 하려면 클래스 패스에도 액튜에이터가 있는 경우 다음 제외를 사용합니다.

@SpringBootApplication(exclude = {ReactiveSecurityAutoConfiguration.class, ReactiveManagementWebSecurityAutoConfiguration.class })

BasicAuthenticationEntryPoint로 설정되어 있는 기본 인증 엔트리 포인트를 덮어쓰는 것이 목적이라고 생각합니다.

이 엔트리 포인트에 의해

"WW-Authenticate": "기본 영역=..."

[ Basic Auth ]를 사용하도록 브라우저에 지시하는 헤더입니다.

WebSecurityConfigurerAdapter , , , , , , , , 을 할 수 .true디폴트를 무효로 합니다.
이 경우 다른 원두를 제공해야 할 수 있습니다.

    /**
     * Creates an instance which allows specifying if the default configuration should be
     * enabled. Disabling the default configuration should be considered more advanced
     * usage as it requires more understanding of how the framework is implemented.
     *
     * @param disableDefaults true if the default configuration should be disabled, else
     * false
     */
    protected WebSecurityConfigurerAdapter(boolean disableDefaults) {
        this.disableDefaults = disableDefaults;
    }

테스트 목적으로만 비활성화하는 경우 자동 구성을 완전히 비활성화하는 것이 아니라 "Security Configuration" 외에 "Insecurity Configuration"을 생성하여 Spring Profile 또는 Property 값으로 활성화합니다.

기술적으로 보안은 아직 설정되어 있지만 완전히 개방되어 있습니다.

@Configuration
@ConditionalOnProperty(prefix = "security", value = "disabled", havingValue = "true")
public class InsecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final static Logger log = LoggerFactory.getLogger(InsecurityConfiguration.class);

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        log.warn("configuring insecure HttpSecurity");
        http.authorizeRequests().anyRequest().permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        log.warn("configuring insecure WebSecurity");
        web.ignoring().antMatchers("/**");
    }

}

주의: 이것은 mvc용이며 webflux용이 아닙니다.Webflux의 경우,SecurityWebFilterChain브라이언이 말한 것처럼요

JWT를 사용할 때 일반적으로 webflux의 기본 인증을 비활성화합니다.

    @Bean
    public SecurityWebFilterChain configure(ServerHttpSecurity http) {

        http
        .authorizeExchange().anyExchange().authenticated().and()
            .httpBasic().disable()
            .formLogin().disable()
            .logout().disable()
            .oauth2ResourceServer()
            .jwt()
            .and()
                .and().exceptionHandling().accessDeniedHandler(problemSupport);
        return http.build();
    }

속성만 - 내 기능(sb2 - 2022):

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

Spring Boot용 심플한 솔루션

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

스프링 부트 2에서는 application.properties 파일에 의한 기본 인증을 디세블로 할 수 없습니다.하지만 유일한 것은 주석을 사용하는 것이다.

@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})

본교에서그건 효과가 있다.

org.springframework에 문제가 있습니다.보안.web.server.허가.Exception Translation Web Filter

정말 그랬어요.private ServerAuthenticationEntryPoint authenticationEntryPoint = new HttpBasicServerAuthenticationEntryPoint();

ServerHttpSecurity 초기화 중에 수정하려면 다음 절차를 수행합니다.

http.exceptionHandling().authenticationEntryPoint(HttpStatusServerEntryPoint(HttpStatus.FORBIDDEN))

바닐라(서블릿) 스프링은 org.spring framework를 사용하는 것 같습니다.security.configuration.configuration.configuration.configuration.information.web.configors 를 참조해 주세요.Exception Handling Configr #create Default Entry Point

private AuthenticationEntryPoint createDefaultEntryPoint(H http) {
        if (this.defaultEntryPointMappings.isEmpty()) {
            return new Http403ForbiddenEntryPoint();
        }
        if (this.defaultEntryPointMappings.size() == 1) {
            return this.defaultEntryPointMappings.values().iterator().next();
        }
        DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(
                this.defaultEntryPointMappings);
        entryPoint.setDefaultEntryPoint(this.defaultEntryPointMappings.values().iterator()
                .next());
        return entryPoint;
    }

참고: 빌더 스타일의 콩(Exception Translation Web Filter 등)의 가변 필드에서는 스프링 코드를 디버깅하기 어렵습니다(너무 매직한 설정도 마찬가지).

추가하셔야 합니다.@EnableWebSecurity커스텀 시큐러티 설정을 유효하게 합니다.그 후, 폼 로그인을 무효로 합니다.

@Configuration
@EnableWebSecurity
public class StackWebSecurityConfigurerAdapter extends 
WebSecurityConfigurerAdapter {
 @Override
 protected void configure(HttpSecurity http) throws Exception {
    http.formLogin().disable();
 }

}

이건 내게 효과가 있었다.

@SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
class SpringApplication{
 ...
}

언급URL : https://stackoverflow.com/questions/47273691/spring-boot-2-0-disable-default-security

반응형