Spring Security는 Spring 기반 애플리케이션에서 인증(Authentication)과 권한 부여(Authorization)를 처리하기 위한 보안 프레임워크입니다.
주요 기능으로는 사용자 인증, 권한 관리, CSRF 방지, 세션 관리 등이 포함됩니다.
Filter Chain
AuthenticationManager
Security Context
Access Decision
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");
}
}
인증(Authentication)
권한 부여(Authorization)
@PreAuthorize나 @Secured 애너테이션으로 세부적인 권한 관리를 설정할 수 있다. @PreAuthorize("hasRole('ADMIN')")
public void adminOnlyMethod() {
// 관리자만 실행 가능한 로직
}
CSRF 방지
http.csrf().disable(); // 개발 단계에서만 사용
Password Encoding
BCryptPasswordEncoder를 사용하여 암호화를 처리한다. @Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
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);
}
}
Spring Security를 통해 애플리케이션의 보안을 체계적으로 관리할 수 있었습니다.
인증과 권한 부여를 기본적으로 제공하면서도 다양한 커스터마이징이 가능하다는 점이 매력적이었습니다.
특히 Filter Chain과 Authentication Provider를 이해하면서 보안의 흐름을 학습할 수 있었습니다.
하지만 설정이 다소 복잡하고 디버깅이 어려운 부분이 있어, 실습과 문서 읽기를 병행해야 했습니다.