Print
카테고리: [ Java ]
조회수: 38918

1. 목적

Spring Boot 2.0 에서 http로 들어오는 요청을 https로 redirection하기 위함

 

2. 방법

2-1. connector 설정

redirection을 원한다면 아래와 같이 connecter 설정을 해주면 제대로 동작한다.

예시)

@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
        @Override
        protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/path/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
        }
    }

    tomcat.addAdditionalTomcatConnectors(createSslConnector());
    return tomcat;
}

private Connector createSslConnector(){
    Connector connector = new Connector("org.apache.coyote.http11.HttpNioProtocol");
    connector.setProt(8080);
    connector.setScheme("http");
    connector.setSecure(false);
    connector.setRedirectPort(8443);
    return connector;
}

 

2-2. Security 설정을 통한 방법(정상 동작 확인 안됨 ㅜ)

앞선 포스팅(Security 접근제어 설정)에서 가져온 예시(아래)에서 자동으로 redirect를 시켜준다는 포스팅도 있었으나, 자동으로 되는 것은 확인하지 못하였고, 잘못된 접근으로 처리되는 것은 확인할 수가 있었다.

 

import org.springframework.stereotype.Component;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Component
public class Security extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests()
                    .antMatchers("/path/**").access("hasIpAddress('123.123.123.123') or hasIpAddress('123.123.123.0/24') or hasIpAddress('0:0:0:0:0:0:0:1')")
                    .antMatchers("/path1/paht2/**").access("hasIpAddress('123.123.123.456')");
    }
}
 

-. 위 예시에서 .requiresSecure()을 추가하면 선택한 URL에 HTTPS를 적용할 수 있다.

-. 위 예시에서 .requiresInsecure()을 추가하면 항상 HTTP로 적용이 된다.

http.requiresChannel().antMatchers("/").requiresSecure();

혹은

http.authorizeRequests()
    .antMatchers("/path/**").access("hasIpAddress('123.123.123.0/24')
    .and()
    .requiresChannel().antMatchers("/path/**").requiresSecure();