본문 바로가기

Language/Spring Security

프로젝트 생성 / 의존성 추가

728x90

해당 글은 인프런 정수원님의 동영상 강의를 기반으로 정리

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%8B%9C%ED%81%90%EB%A6%AC%ED%8B%B0-%EC%99%84%EC%A0%84%EC%A0%95%EB%B3%B5/dashboard

  • 프로젝트 구성
    • Spring Boot 3.x 버전 (강의 기준 3.2.2)
    • JDK 17
    • Gradle 빌드
  • 의존성 추가 : Spring Web, Spring Security

자동 설정에 의한 기본 보안 작동

  • 서버 기동 시 스프링 시큐리티의 초기화 작업 및 보안 설정이 이루어짐
  • 별도의 설정이나 코드를 작성하지 않더라도 기본적인 웹 보안 기능이 현재 시스템과 연동되어 작동
    1. 모든 요청에 대하여 인증 여부를 검증하고 인증이 승인되어야 자원 접근 가능
    2. 인증 방식은 폼 로그인 방식 / httpBasic 로그인 방식 제공
    3. 인증을 시도할 수 있는 로그인 페이지가 자동적으로 생성되어 렌더링
    4. 인증 승인이 이루어질 수 있도록 한 개의 계정이 기본적으로 제공
      • SecurityProperties 설정 클래스에서 생성
      • username : user
      • password : 문자열
  • SpringBootWebSecurityConfiguration : 자동 설정에 의한 기본 보안 클래스 생성
  • 문제점
    • 계정 추가나 권한 추가 시
    • 시스템에서 필요로 하는 더 세부적이고 추가적인 보안 기능이 필요할 때

Spring Security의 기본 값 확인

  • 프로젝트 생성 후 간단하게 다음과 같은 컨트롤러 생성하여 서버 실행
@RestController
public class IndexController {
    @GetMapping("/")
    public String index() {
        return "index";
    }
}

 

  • localhost:8080 접속 시 index 페이지가 아닌 로그인 페이지 접속
  • 스프링 시큐리티에 의한 자동 설정
  • 아이디는 user, 패스워드는 콘솔창에 출력
    • 검색창에서 SecurityProperties 클래스 검색
    • 내부에 User 클래스가 존재
      → 서버가 시작되면서 아이디(user)와 비밀번호(랜덤 UUID)를 생성
  • 아이디, 패스워드 입력 후 localhost:8080으로 다시 접속하면 인증이 이미 되어 로그인 페이지로 튕겨지지 않음
  • 위의 기본 인증 설정을 해주는 클래스가 SpringBootWebSecurityConfiguration의 defaultSercurityFliterChain() 메서드
@Configuration(proxyBeanMethods = false)
@ConditionalOnDefaultWebSecurity
static class SecurityFilterChainConfiguration {

    @Bean
    @Order(SecurityProperties.BASIC_AUTH_ORDER)
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
        http.formLogin(withDefaults());
        http.httpBasic(withDefaults());
        return http.build();
    }

}

 

  • defaultSecurityFilterChain() 메서드는 무조건 실행 되는 것이 아님
  • @ConditionalOnDefaultWebSecurity 어노테이션이 만족해야 함
  • @ConditionalOnDefaultWebSecurity안의 DefaultWebSecurityCondition 클래스에서 아래 두 조건이 만족
    → 아래 두 조건이 참일 경우 defaultSercurityFilterChain() 메서드가 실행되어 기본 보안 설정 실행
@ConditionalOnClass({ SecurityFilterChain.class, HttpSecurity.class }) 
// 위의 두 클래스가 존재하느냐? -> O -> Spring Security 의존성을 추가했기 때문
static class Classes {

}

@ConditionalOnMissingBean({ SecurityFilterChain.class })
// SecurityFilterChain이 생성되어 있지 않으면 참
// 생성한 적이 없기 때문에 만족
static class Beans {

}
728x90

'Language > Spring Security' 카테고리의 다른 글

폼 인증 - formLogin()  (0) 2024.07.15
사용자 정의 보안 설정하기  (0) 2024.07.15
DelegatingFilterProxy / FilterChainProxy  (0) 2024.07.15
WebSecurity / HttpSecurity  (0) 2024.07.15
SecurityBuilder / SecurityConfigurer  (0) 2024.07.15