programing

Spring Boot / h2-console 403과 Spring Security 1.5.2

javajsp 2023. 2. 28. 23:14

Spring Boot / h2-console 403과 Spring Security 1.5.2

Spring Boot 1.4.1, 1.5.2, Spring Boot 1.4.1, Spring Boot 1.4.2, Spring Boot 1.4.1, Spring Boot 1.5.2. 중 auth.1.5.2에 입니다.에에 the the the the the the the 에 접속할 수 없습니다./h2-console기본 인증 후에도 마찬가지입니다. 403을 던집니다.

application.yml:

spring:
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:file:../app-db/app_db;AUTO_SERVER=TRUE
    username: sa
    password: sa
    initialize: false
  jpa:
    hibernate:
      ddl-auto: validate
    show-sql: true
    database-platform: org.hibernate.dialect.H2Dialect
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
  allowed:
    resources: /h2-console/**

는 심지어 했다./h2-console/**

 httpSecurity.authorizeRequests()
                .antMatchers(allowedResources)                  
                .permitAll()

에 이 계속 .localhost:8080/h2-console 퍼팅도 시도했습니다. 여러 가지 설정을 시도하고 다음을 입력했습니다.

management.security.enabled=true
security.basic.enabled=true

하지만 h2-console에 접속할 수 없습니다.

H2에는 자체 인증 공급자가 있으므로 정적 콘텐츠와 마찬가지로 H2 콘솔 경로에 대한 Spring Security를 건너뛸 수 있습니다.

에서 "Spring" Configuration" "Configuration" 을 방식을 .org.springframework.security.config.annotation.web.builders.WebSecurity「」를 가 아닌 org.springframework.security.config.annotation.web.builders.HttpSecurity

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/h2-console/**");
    }

실제 환경에서 h2를 사용하는 경우 h2 콘솔에 대해 적절한 보안 조치(불확실 경로 설정, 양호한 비밀번호, IP 화이트리스트 등)를 설정해야 합니다.

스프링 보안은 H2 데이터베이스의 /h2-console(또는 application.yaml에서 설정한 경로) 경로를 차단합니다.

H2 콘솔에 액세스하려면 Web SecurityConfigurerAdapter에 다음 코드를 추가하십시오.

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/h2-console/**").permitAll();

        http.csrf().disable();
        http.headers().frameOptions().disable();
    }
}

프로덕션 환경에서는 이 구성을 사용하지 마십시오.=)

@argoth에서 제안한 것과 유사한 구성을 제공하고자 합니다만, 실제 가동 준비가 좀 더 되어 있습니다.

@Profile("h2") // to make sure it is active only if h2 profile is active
@Configuration
@ConditionalOnProperty( //to make sure it is active if console is enabled
    value="spring.h2.console.enabled", 
    havingValue = "true", 
    matchIfMissing = false)
public class H2SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // this may not be required, depends on your app configuration
        http.authorizeRequests()
                // we need config just for console, nothing else             
                .antMatchers("/h2_console/**").permitAll();
        // this will ignore only h2-console csrf, spring security 4+
        http.csrf().ignoringAntMatchers("/h2-console/**");
        //this will allow frames with same origin which is much more safe
        http.headers().frameOptions().sameOrigin();
    }
}

실제로 부트 1.3에서는 H2 Console Security Configuration이라고 불리는 유사한 설정이 이루어졌지만 현재는 없어졌습니다.올드 클래스

기트허브 토론

업데이트. 매우 중요한 주의사항입니다!여러 개를 가지고 있는 경우WebSecurityConfigurerAdapter수 있기 에, 만약 또 다른 것이 , 서로 충돌할 수 있습니다.WebSecurityConfigurerAdapter당신의 코드에서, 당신은 어떻게든 그것들을 합칠 필요가 있을 것입니다.경합이 발생하는 이유에 대한 자세한 내용은 각 어댑터가 자체 필터 체인을 설정하기 때문에 발생합니다.모든 요구는 양쪽 필터 체인을 통과해야 합니다.체인 중 하나가 frameOptions를 금지하고 다른 체인이 frameOptions를 금지하지 않으면 요청은 첫 번째 체인을 통과하지 않습니다.,, 여여 、 여구 、 여십십오오 。

디버깅 로깅을 활성화하면 다음과 같이 표시됩니다.

o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /h2-console/; Attributes: [hasAnyRole('ROLE_USER','ROLE_ACTUATOR')]
2017-05-05 13:16:09.304 DEBUG 90365 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@33d2af72: Principal: org.springframework.security.ldap.userdetails.LdapUserDetailsImpl@7371d5f4: Dn: cn=XYZ,ou=XYZ,ou=Active,ou=ABC_USERS,dc=internal,dc=organization,dc=com; Username: uname; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; CredentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 86EF50EF548ED4DBCE4D661AEC93F88C; Granted Authorities: ROLE_ADMIN
2017-05-05 13:16:09.305 DEBUG 90365 --- [nio-8080-exec-2] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@51d3d69, returned: -1
2017-05-05 13:16:09.305 DEBUG 90365 --- [nio-8080-exec-2] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is not anonymous); delegating to AccessDeniedHandler

사용자에게는 다음 기능이 없다는 것을 알고 있습니다.ROLE_USER제 생각엔ROLE_ADMIN>ROLE_USER그래도 좀 더 잘 이해해야 할 것 같아요

설정을 다음과 같이 업데이트했습니다.

security:
  basic:
    enabled: true
    authorize-mode: NONE

에 액세스 할 수 있습니다./h2-console/**지금이다.

@Configuration
@ConditionalOnClass(WebSecurityConfigurerAdapter.class)
@ConditionalOnBean(ObjectPostProcessor.class)
@ConditionalOnProperty(prefix = "security.basic", name = "enabled", matchIfMissing = true)
static class H2ConsoleSecurityConfiguration 

spring boot에서 볼 수 있듯이 basic을 활성화하면 spring boot에서 spring 보안 설정이 로드됩니다.H2ConsoleSecurityConfigurer질서 있게SecurityProperties.BASIC_AUTH_ORDER - 10인증은 보안 설정을 기반으로 합니다.기본 보안 설정은 다음과 같습니다.

public void configure(HttpSecurity http) throws Exception {
            String path = this.console.getPath();
            String antPattern = path.endsWith("/")?path + "**":path + "/**";
            HttpSecurity h2Console = http.antMatcher(antPattern);
            h2Console.csrf().disable();
            h2Console.httpBasic();
            h2Console.headers().frameOptions().sameOrigin();
            // the default role is `USER` and `management.security.roles`
            String[] roles = (String[])this.security.getUser().getRole().toArray(new String[0]);
           // this value is base `security.basic.authorize-mode`, `role`, 'authenticated' and `none`
            SecurityAuthorizeMode mode = this.security.getBasic().getAuthorizeMode();
            if(mode != null && mode != SecurityAuthorizeMode.ROLE) {
                if(mode == SecurityAuthorizeMode.AUTHENTICATED) {
                    ((AuthorizedUrl)http.authorizeRequests().anyRequest()).authenticated();
                }
            } else {
                ((AuthorizedUrl)http.authorizeRequests().anyRequest()).hasAnyRole(roles);
            }

        }

또한 기본 구성을 덮어쓰도록 새 구성을 만들 수도 있습니다.

@Configuration
// before the default configuration
@Order(SecurityProperties.BASIC_AUTH_ORDER - 11)
class CustomH2ConsoleSecurityConfigurer extends WebSecurityConfigurerAdapter {

        @Autowired
        private H2ConsoleProperties console;

        @Override
        public void configure(HttpSecurity http) throws Exception {
            String path = this.console.getPath();
            String antPattern = (path.endsWith("/") ? path + "**" : path + "/**");
            HttpSecurity h2Console = http.antMatcher(antPattern);
            h2Console.csrf().disable();
            h2Console.httpBasic();
            h2Console.headers().frameOptions().sameOrigin();
            // config as you like
            http.authorizeRequests().anyRequest().permitAll();
        }

    }

스프링 보안을 사용할 때도 같은 문제가 발생했습니다.application.properties에서 다음 구성에 유의하십시오.

spring.h2.console.enabled=true
spring.h2.console.path=/h2

spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

구성 방식의 보안 구성에 다음 항목이 포함되어 있으며 h2 콘솔에 액세스할 수 있습니다.

        .antMatchers( "/h2/**").permitAll()

에 대해서WebSecurityConfigurerAdapter샘플 코드를 추가해서 h2콘솔뿐만 아니라 Swagger-UI에서도 문제없이 사용할 수 있다고 생각합니다.

private static final String[] AUTH_WHITELIST = {
        // -- Swagger UI v2
        "/v2/api-docs",
        "/swagger-resources",
        "/swagger-resources/**",
        "/configuration/ui",
        "/configuration/security",
        "/swagger-ui.html",
        "/webjars/**",
        // -- Swagger UI v3 (OpenAPI)
        "/v3/api-docs/**",
        "/swagger-ui/**",
        // other public endpoints
        "/h2-console/**",
 };
@Override
protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/hello").hasAuthority("USER")
                .and().authorizeRequests().antMatchers(AUTH_WHITELIST).permitAll().anyRequest().authenticated()
                .and().headers().frameOptions().sameOrigin()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);            
}

이것은 나에게도 도움이 된다.

  #H2 database
    datasource:
      url: jdbc:h2:mem:mytestdb;INIT=RUNSCRIPT FROM 'classpath:/data.sql'
      driverClassName: org.h2.Driver
      username: sa
      password: sa
    main:
        allow-bean-definition-overriding: true
    h2:
      console:
        enabled: true
        path: /h2-console
        settings:
          web-allow-others: true
    allowed:
      resources: /h2-console/**
    security:
      basic:
        enabled: true
        authorize-mode: NONE

비록 가장 많이 투표된 답은 맞지만.

현시점에서는 Web Security Configurer Adapter는 새로운 봄 보안 버전에서는 권장되지 않습니다.이 방법으로는 다음 용도의 Bean을 만듭니다.WebSecurityCustomizer보안 컨피규레이션클래스의 [Bean]아래에서 이 기능을 사용할 수 있습니다.

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().antMatchers("/h2-console/**");
}

다음 설정은 실제 가동 환경에 권장되지 않습니다.

스프링 보안으로 허용되지 않음h2 콘솔에 대한 접근을 이노블로 만들려면 다음 절차를 수행합니다.

  1. SecurityFilterChain bean에서 "/console/*" 요청을 허용합니다.
  2. 사이트 간 요청 위조 방지를 비활성화합니다.
  3. X-Frame-Options 를 디세블로 합니다.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
            .authorizeRequests()
                .antMatchers("/", "/**", "/console/**").permitAll()             
                .and()
                .csrf().disable()
                .headers().frameOptions().disable()             
                .build();
}

이는 보안상의 문제가 될 수 있습니다.응용 프로그램 중

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

이 부분을 이렇게 바꾸세요.

나는 네가 그것으로 이 문제를 해결하길 바란다.

언급URL : https://stackoverflow.com/questions/43794721/spring-boot-h2-console-throws-403-with-spring-security-1-5-2