토이 프로젝트 로컬환경 H2 Database 적용 (SpringBoot + H2)

고승현·2021년 8월 5일
0

Spring

목록 보기
1/1

H2란 무엇인가요?

H2는 자바 기반의 오픈소스 RDBMS입니다. Server모드, Embedded모드(In memoryDB)를 지원하며 디스크 기반 테이블을 생성할 수 있습니다. 브라우저 기반의 콘솔모드를 이용할 수 있으며 별도의 설치과정이 없고 매우 빠르며 용량도 2MB 이하로 저용량입니다.


  • 인메모리 DB로 사용 시 서버가 꺼지면 모든 내용이 날라갑니다.
  • 로컬환경과 테스트 환경에 가볍게 사용하기 위해 프로젝트에 적용하려 합니다.

Spring boot + H2 Database 로컬환경 적용

  1. build.gradle에 h2 database 의존성을 추가해줍니다.

  1. application.yml의 설정을 다음과 같이 변경합니다

  • h2.console.enabled : h2 database를 사용여부를 설정합니다
  • driver-class-name : org.h2.Driver를 적어줍니다.
  • url : h2:mem = 메모리 db를 사용하겠다는 의미고, h2:file로 변경시 file로 db를 관리하겠다는 뜻
  • username는 sa, password는 공백으로 둡니다.

SpringBoot에서 제공하는 기본 옵션입니다.

Using the H2 Database Console in Spring Boot with Spring Security

  1. 서버 구동 시 테이블이 생성됨을 확인할 수 있습니다.

  1. 웹 브라우저를 구동 후 해당 url로 접속합니다.

    http://localhost:8080/h2-console/

  • Spring Security를 사용하여 권한을 설정 시 403오류가 발생합니다. 이를 해결해주기 위해 권한을 추가해줍니다. (Spring Security를 아직 적용하지 않았다면 건너뛰어도 됩니다.)

  • 오류 페이지

  • 해당 페이지, favicon.ico의 권한을 추가해줍니다.

  1. 로그인 페이지가 정상적으로 접속되면 다음과 같이 url, 사용자명을 입력하고 연결을 눌러줍니다

  1. 로그인을 했는데 접속이 되지 않습니다. (Spring Security를 적용하지 않았으면 정상 작동합니다.)

  • 개발자 도구를 확인해보니 오류가 발생함을 확인할 수 있습니다.

Refused to display 'http://localhost:8080/' in a frame because it set 'X-Frame-Options' to 'deny'.

  • h2 database가 iframe을 사용하기 때문에 발생하는 오류입니다. security 설정 부분에 다음과 같이 추가해줍니다.

http.headers().frameOptions().sameOrigin();

  1. 적용 후 정상 작동함을 확인할 수 있습니다


Spring Security 설정 검색 중 Spring profile로 로컬설정, 그 외 설정으로 나누어 사용하는 글을 참고하여 동일하게 적용 하였습니다.

출처 : https://www.slipp.net/questions/546 (창천향로님)

private final Environment env;
public SecurityConfig(JwtTokenProvider jwtTokenProvider, Environment env) {
    this.jwtTokenProvider = jwtTokenProvider;
    this.env = env;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    if (isLocalMode()) {
        setLocalMode(http);
    } else {
        setProdMode(http);
    }
}
private boolean isLocalMode() {
    String profile = env.getActiveProfiles().length > 0 ? env.getActiveProfiles()[0] : "";
    return profile.equals("local");
}

private void setLocalMode(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .httpBasic().disable();

    http
            .headers()
            .frameOptions()
            .sameOrigin();

    http
            .authorizeRequests()
            .antMatchers("/h2-console/*","favicon.ico").permitAll()
            .antMatchers("/member/login").anonymous()
            .antMatchers("/member/regist").anonymous()
            .antMatchers("/member/validate/**").anonymous()
            .anyRequest().authenticated()
            .and()
            .formLogin().disable()
            .addFilterBefore(new JwtAuthFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);
}

private void setProdMode(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .httpBasic().disable();

    http
            .authorizeRequests()
            .antMatchers("/member/login").anonymous()
            .antMatchers("/member/regist").anonymous()
            .antMatchers("/member/validate/**").anonymous()
            .anyRequest().authenticated()
            .and()
            .formLogin().disable()
            .addFilterBefore(new JwtAuthFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);
}
  • org.springframework.core.env.Environment
    • Environment는 스프링 환경, 설정에 관련된 인터페이스 입니다. Profiles 설정과 Property 설정에 접근할 수 있지만 설정 값을 변경하는 것은 불가능하고, 접근해서 값을 가져올 수 있습니다.
    • isLocalMode 메소드가 실행되면 environment 인터페이스에서 profiles을 가져오고, 로컬이면 setLocalMode 메소드를 실행하고, 그 외의 Profile이면 setProdMode를 실행하여 로컬(H2 Database) 환경과 운영(Aws RDS [MariaDB])설정을 분리하여 적용할 수 있습니다.
profile
까먹지 말자

0개의 댓글