Junit Test Application-6-SecurityConfig 세팅

jaegeunsong97·2023년 8월 3일
0
post-thumbnail

Junit Bank Application 깃허브

Junit Bank Application 기록 노션

시큐리티가 되어있지 않은 상태

package shop.mtcoding.bank.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import shop.mtcoding.bank.domain.user.UserEnum;

@Configuration
public class SecurityConfig {

     private final Logger log = LoggerFactory.getLogger(getClass()); // @slf4j -> JUnit 테스트 문제 발생

     @Bean // IOC에 BCryptPasswordEncoder 객체 등록, @Configuration 붙어있는 곳만
     public BCryptPasswordEncoder bCryptPasswordEncoder() {
          log.debug("디버그 : BCryptPasswordEncoder 빈 등록됨");
          return new BCryptPasswordEncoder();
     }

     // JWT 등록이 필요함!!

     // JWT 서버 -> 세션 사용 X(무상태 서버)
     @Bean
     public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
          http.headers().frameOptions().disable(); // iframe 허용 X
          http.csrf().disable(); // 자바스크립트 공격 막기
          http.cors().configurationSource(configurationSource()); // cross-origin-resource-sharing 에서 특정 IP만 허용하기

          // jSessionId 서버쪽에서 관리 안하겠다는 것
          http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
          // react, app 요청 예정
          http.formLogin().disable();
          // 브라우저가 팝업창을 이용해서 사용자 인증을 진행
          http.httpBasic().disable();
          http.authorizeRequests()
                    .antMatchers("/api/s/**").authenticated()
                    .antMatchers("/api/admin/**").hasRole("" + UserEnum.ADMIN) // ROLE_
                    .anyRequest().permitAll();

          return http.build();
     }

     public CorsConfigurationSource configurationSource() {
          CorsConfiguration configuration = new CorsConfiguration();
          configuration.addAllowedHeader("*"); // 모든 헤더 받기
          configuration.addAllowedMethod("*"); // GET, POST, DELETE, PUT 전부 허용
          configuration.addAllowedOriginPattern("*"); // 모든 IP 주소 허용 (FE IP만 허용)
          configuration.setAllowCredentials(true); // 클라이언트쪽에서 쿠키 요청 허용(클라이언트쪽에서 보내는게 가능)

          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          source.registerCorsConfiguration("/**", configuration); // 모든 주소요청에 위에 설정을 넣기
          return source;
     }
}

logger 부분은 @Slf4j를 사용해도 되지만 이럴 경우에는 JUnit 테스트를 할 때 문제가 발생한다.

@Bean을 등록하면 IOC에 등록이 된다. 따라서 BCryptPasswordEncoder를 객체로 등록을 한다. 단 @Configuration이 붙어있는 클래스 내부의 Bean만 등록이 된다.

우리는 JWT 서버, 즉 무상태 서버를 만들것이기 때문에 jSessionId를 사용하지 않는다.

hasRole 부분은 ROLE_ 가 내장되어있기 때문에 그냥 작성하면 된다.

CORS 설정은 모든 헤더를 받아야하고(받지 않으면 FE의 요청을 전부 받지 못한다.) 메소드를 전부 받고 모든 IP도 허용을 한다. 그리고 Credential을 허용해서 Client쪽에서 쿠키값을 보낼 수 있게 만든다.

source 부분에서는 요청하는 모든 CORS에는 우리가 설정한 것 처럼 만든다.

profile
블로그 이전 : https://medium.com/@jaegeunsong97

0개의 댓글