웹 애플리케이션에서 인증 및 인가를 구현하려고 하면 빠지지 않고 등장하는 것이 바로 Spring Security입니다. 이 글에서는 Spring Security가 무엇인지, 어떤 역할을 하는지, 그리고 이를 프로젝트에 어떻게 적용할 수 있는지 알아보겠습니다.
Spring Security
Spring Security는 인증과 인가를 처리하기 위해 제공되는 강력한 라이브러리로, 필터 체인(filter chain)을 기반으로 작동합니다. 이를 통해 사용자 인증 및 권한 부여를 관리할 뿐만 아니라 다양한 보안 공격으로부터 애플리케이션을 보호합니다.
Spring Security의 주요 특징은 다음과 같습니다:
- 인증 및 권한 부여에 대한 포괄적이고 확장 가능한 지원
- 세션 고정, 클릭재킹, 크로스 사이트 요청 위조(CSRF) 등의 보안 공격 방지
- 서블릿 API 통합
- Spring Web MVC와의 선택적 통합
인증과 인가의 차이
Spring Security를 이해하려면 먼저 인증과 인가의 차이를 명확히 알아야 합니다.
인증 (Authentication)
인증은 사용자가 "내 서비스에 등록된 회원인지"를 확인하는 절차입니다. 사용자가 회원임을 증명하는 과정으로, 흔히 아이디와 비밀번호, 혹은 OAuth 등을 통해 처리됩니다.
인가 (Authorization)
인가는 "이 사용자가 특정 작업이나 리소스에 접근할 권한이 있는지"를 결정하는 과정입니다. 예를 들어, 회사에서 CEO가 접근할 수 있는 정보와 신입 직원이 접근할 수 있는 정보는 다를 수 있습니다. 이러한 권한 관리를 인가라고 합니다.
필터(Filter)와 필터 체인(Filter Chain)
Spring Security는 필터 체인(filter chain)을 활용해 인증 및 인가 과정을 처리합니다. 여기서 필터는 클라이언트 요청이 서버에 도달하기 전에 미리 처리해야 할 기능을 수행합니다
Spring은 서블릿에서 제공하는 기본 필터를 확장해, 인증과 인가 시스템을 손쉽게 구현할 수 있도록 지원합니다. 이를 기반으로 Spring Security는 강력한 보안 기능을 제공합니다.
필터 체인을 간단히 그림으로 표현하면 다음과 같은 구조를 가집니다:
Security 설치하기
Gradle를 통해서 간단하게 라이브러리를 설치할 수 있습니다.
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.security:spring-security-test'
Security Config 설정하기
다음은 실제 프로젝트에서 사용한 Spring Security 설정 코드입니다. 코드를 보며 주요 구성 요소를 살펴보겠습니다.
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {
private final JwtProvider jwtProvider;
private final SecurityProperties securityProperties;
private final String develop = UserType.DEVELOP.name();
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.httpBasic(HttpBasicConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.formLogin(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
.requestMatchers("/develop/**").hasAuthority(develop)
.anyRequest().permitAll()
)
.addFilterBefore(new JwtAuthenticationFilter(jwtProvider, securityProperties),
UsernamePasswordAuthenticationFilter.class)
.build();
}
}
Config Annotation
@Configuration
- 이 클래스가 Spring 설정 클래스임을 나타냅니다. 또한, 메서드를 통해 Bean을 등록할 수 있습니다.
@EnableWebSecurity
- Spring Security를 활성화하고, 프로젝트에서 Security 설정을 적용하도록 합니다.
@RequiredArgsConstructor
- final 키워드가 붙은 필드를 초기화하는 생성자를 자동으로 생성합니다. 이를 통해 의존성을 간단히 주입할 수 있습니다.
@EnableMethodSecurity
- 메서드 단위로 Security 필터를 설정할 수 있도록 지원합니다. 예를 들어, 특정 메서드에만 인증/인가를 적용할 수 있습니다.
SecurityFilterChain 설정하기
주요 메서드 설명
- httpBasic(HttpBasicConfigurer::disable)
- Http Basic 인증을 비활성화합니다. 토큰 기반 인증을 사용할 경우 필요하지 않습니다.
- csrf(AbstractHttpConfigurer::disable)
- CSRF(Cross-Site Request Forgery) 방어를 비활성화합니다. API 서버에서는 일반적으로 필요하지 않기 때문에 비활성화합니다.
- sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
- 세션을 생성하지 않고 상태를 유지하지 않도록 설정합니다. JWT를 사용하여 인증/인가를 처리하기 때문에 세션이 필요 없습니다.
- formLogin(AbstractHttpConfigurer::disable)
- 폼 기반 로그인을 비활성화합니다. API 서버에서는 폼 로그인을 사용하지 않으므로 필요하지 않습니다.
- authorizeHttpRequests
- 요청 경로에 따른 권한 설정을 정의합니다.
- /develop/** 경로: develop 권한이 있는 사용자만 접근 가능
- 그 외 모든 요청: 인증 없이 접근 허용
- 요청 경로에 따른 권한 설정을 정의합니다.
- addFilterBefore(new JwtAuthenticationFilter(jwtProvider, securityProperties), UsernamePasswordAuthenticationFilter.class)
- Spring Security의 필터 체인에서 UsernamePasswordAuthenticationFilter 앞에 JwtAuthenticationFilter를 추가합니다.
- JwtAuthenticationFilter: JWT를 검증하고 인증을 처리하는 필터
- UsernamePasswordAuthenticationFilter: Spring Security의 기본 인증 필터
- Spring Security의 필터 체인에서 UsernamePasswordAuthenticationFilter 앞에 JwtAuthenticationFilter를 추가합니다.
마무리
Spring Security는 인증과 인가를 처리하기 위한 강력한 도구입니다. 이 글에서는 기본적인 개념과 설정 파일의 주요 구성 요소를 살펴보았습니다. 다음 글에서는 JWT 인증 필터를 직접 구현하며 Spring Security를 활용하는 방법을 자세히 알아보겠습니다.
혹시라도 틀린 내용이 있다면 댓글로 알려주시면 감사하겠습니다!!
참고 문헌
https://hello-judy-world.tistory.com/216
[Spring] Spring Security 개념과 처리 과정 👮♀️ (+근데 상황극을 곁들인)
오늘도 노드 마을에서 온.. 토끼는 낯선 기술에 울고 있다..(?) 그렇다.. 유저가 있는 서비스라면 인증과 인가 처리는 필수이다. Spring에서는 Spring Security라는 프레임워크로 관련 기능을 제공하고
hello-judy-world.tistory.com
https://spring.io/projects/spring-security
Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authoriz
spring.io
'Spring > Security' 카테고리의 다른 글
Spring에 Security 적용하기 2 (0) | 2024.12.12 |
---|