25.01.21 TIL Spring Security

신성훈·2025년 1월 21일

TIL

목록 보기
123/162

1. Spring Security란?

Spring Security는 Spring 기반 애플리케이션에서 인증(Authentication)권한 부여(Authorization)를 처리하기 위한 보안 프레임워크입니다.
주요 기능으로는 사용자 인증, 권한 관리, CSRF 방지, 세션 관리 등이 포함됩니다.

Spring Security의 주요 구성 요소

  • Authentication: 사용자 인증 처리
  • Authorization: 리소스에 대한 접근 권한 부여
  • Filter Chain: 요청에 대한 보안 필터 처리
  • Security Context: 인증된 사용자 정보 관리

2. Spring Security의 동작 원리

  1. Filter Chain

    • 요청(Request)이 애플리케이션으로 들어오면 여러 보안 필터를 거친다.
    • 필터 체인은 인증/권한 검사를 담당하며, 각 필터는 특정 보안 작업을 수행한다.
  2. AuthenticationManager

    • 인증 요청을 처리하고 결과를 반환한다.
    • 사용자 인증이 성공하면 Authentication 객체를 생성하여 Security Context에 저장
  3. Security Context

    • 인증된 사용자 정보를 저장하여 애플리케이션 전반에서 사용할 수 있도록 제공
  4. Access Decision

    • 요청한 리소스에 접근할 권한이 있는지 확인하여 요청을 허용하거나 거부한다.

3. 주요 설정

Spring Security는 보안 설정을 Java Config 또는 XML로 구성할 수 있다.
SecurityConfig 클래스에 설정을 추가하여 애플리케이션의 보안 규칙을 정의

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests() // 권한 설정
                .antMatchers("/public/**").permitAll() // 공개 URL
                .antMatchers("/admin/**").hasRole("ADMIN") // 관리자만 접근 가능
                .anyRequest().authenticated() // 그 외 요청은 인증 필요
            .and()
            .formLogin() // 로그인 설정
                .loginPage("/login") // 커스텀 로그인 페이지
                .defaultSuccessUrl("/") // 로그인 성공 시 이동 페이지
            .and()
            .logout() // 로그아웃 설정
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login?logout");
    }
}

4. 주요 기능

  1. 인증(Authentication)

    • 사용자의 신원을 확인
    • 기본적으로 UsernamePasswordAuthenticationFilter를 사용
  2. 권한 부여(Authorization)

    • 사용자 요청에 대해 접근 가능한 리소스를 제한한다.
    • @PreAuthorize@Secured 애너테이션으로 세부적인 권한 관리를 설정할 수 있다.
    @PreAuthorize("hasRole('ADMIN')")
    public void adminOnlyMethod() {
        // 관리자만 실행 가능한 로직
    }
  3. CSRF 방지

    • CSRF 공격을 방지하기 위해 기본적으로 활성화 되어 있다.
    http.csrf().disable(); // 개발 단계에서만 사용
  4. Password Encoding

    • 사용자의 비밀번호는 평문이 아닌 해시 값으로 저장
    • BCryptPasswordEncoder를 사용하여 암호화를 처리한다.
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
  5. Custom Authentication Provider

    • 기본 인증 방식을 커스터마이징할 수 있다.
    @Component
    public class CustomAuthenticationProvider implements AuthenticationProvider {
    
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            String username = authentication.getName();
            String password = authentication.getCredentials().toString();
    
            // 사용자 인증 로직 추가
            if ("user".equals(username) && "password".equals(password)) {
                return new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());
            } else {
                throw new BadCredentialsException("Authentication failed");
            }
        }
    
        @Override
        public boolean supports(Class<?> authentication) {
            return authentication.equals(UsernamePasswordAuthenticationToken.class);
        }
    }

5. 마무리

Spring Security를 통해 애플리케이션의 보안을 체계적으로 관리할 수 있었습니다.
인증과 권한 부여를 기본적으로 제공하면서도 다양한 커스터마이징이 가능하다는 점이 매력적이었습니다.
특히 Filter ChainAuthentication Provider를 이해하면서 보안의 흐름을 학습할 수 있었습니다.
하지만 설정이 다소 복잡하고 디버깅이 어려운 부분이 있어, 실습과 문서 읽기를 병행해야 했습니다.

profile
조급해하지 말고, 흐름을 만들고, 기록하면서 쌓아가자.

0개의 댓글