프로젝트에서 스프링 웹 시큐리티를 이용해 암호화를 적용해 본 적이 있다.
스프링 웹 시큐리티
자바 기반의 스프링 애플리케이션에서 보안을 강화하기 위한 것이다.
주요 기능으로는 인증, 인가, CSRF보호, 세션 관리, 비밀번호 암호화 등이 있다.
주요 개념으로는 SecurityFilterChain, AuthenticationManager, UserDetailsService, GrantedAuthority가 있다.
주요 기능
- 인증(Authentication)
사용자 인증을 통해 애플리케이션에 접근할 수 있는 사용자를 확인
다양한 인증 방식을 지원 - 인가(Authorization)
인증된 사용자가 특정 자원에 접근할 수 있는지를 결정
역할 기반 접근 제어 및 권한 기반 접근 제어를 지원 - CSRF 보호
크로스 사이트 요청 위조 공격으로부터 애플리케이션을 보호 - 세션 관리
사용자의 세션을 관리하고, 세션 고정 공격을 방지 - 비밀번호 암호화
사용자의 비밀번호를 안전하게 저장하기 위해 다양한 암호화 알고리즘을 지원 - 커스터마이징
필터, 인터셉터 등을 통해 보안 기능을 커스터마이즈
주요 개념
- SecurityFilterChain
요청을 처리하는 필터 체인으로, 각 필터는 요청을 가로채고 특정 작업을 수행 - AuthenticationManager
인증 요청을 처리하는 컴포넌트로, 사용자 정보를 확인하고 인증 토큰을 생성 - UserDetailsService
사용자 정보를 제공하는 서비스 인터페이스로, 데이터베이스에서 사용자 정보를 로드하는 데 사용 - GrantedAuthority
사용자의 권한을 나타내는 인터페이스로, 특정 권한을 가진 사용자인지를 확인하는 데 사용
구현 과정
- 환경 설정
- Maven이나 Gradle을 통해 spring-security-core, spring-security-web, spring-security-config를 시큐리티 관련 의존성 추가
- web.xml 파일에 필터를 설정하여 시큐리티 필터가 작동하도록 함 - 보안 설정 XML 또는 Java 구성
- 보안 설정을 XML 파일 또는 Java 클래스를 통해 구성
1) XML을 설정하면 spring-security.xml 파일에 설정을 정의
2) Java 클래스를 사용하면 WebSecurityConfigurerAdapter 를 확장하여 설정 - 사용자 인증 설정
1) XML 설정
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="password" authorities="ROLE_USER"/>
<security:user name="admin" password="admin" authorities="ROLE_ADMIN"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
2) Java 설정 : AuthenticationManagerBuilder를 사용해 메모리 기반 인증을 설정 - HTTP 보안 설정
1) XML 설정
<security:http>
<security:intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<security:intercept-url pattern="/" access="permitAll" />
<security:intercept-url pattern="/**" access="isAuthenticated()" />
<security:form-login login-page="/login" permit-all="true" />
<security:logout permit-all="true" />
</security:http>
2) Java 설정
HttpSercurity를 사용하여 요청에 대한 접근 권한을 설정. URL 패턴에 따라 권한을 부여하고, 폼 로그인 및 로그아웃 기능을 추가 - 로그인 및 로그아웃 설정
로그인 페이지를 설정하고, 사용자가 로그인을 할 수 있도록 함. 로그아웃 기능을 통해 사용자가 세션을 종료할 수 있도록 설정 - 종합적인 접근 제어
anyRequest().authenticated()와 같은 메소드를 사용하여 인증된 사용자만 접근할 수 있도록 모든 요청에 대한 기본 보안을 설정
기본 설정 예시
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
예시에 사용된 코드 설명
@Configuration
→ 해당 클래스가 하나 이상의 @Bean 메소드를 포함하고 있으며, Spring IoC 컨테이너에 의해 처리되어야 함을 나타냄. 즉 이 클래스는 스프링의 설정 클래스
@EnableWebSecurity
→ 스프링 시큐리티를 활성화함. 스프링 시큐리티 관련 구성 요소들이 자동으로 설정되고 기본적인 보안 필터가 적용됨
SecurityConfig extends WebSecurityConfigurerAdapter
→ 웹 애플리케이션의 보안 구성을 정의하는 데 사용
configure(AuthenticationManagerBuilder auth) throws Exception
→ 사용자 인증을 설정하는 데 사용. AuthenticationManagerBuilder를 통해 인증 관련 설정을 정의
웹 시큐리티의 주요 기능이 무엇인가에 대해서 물어본다면 비밀번호 암호화 말고는 떠오르지 않는데 여러 기능이 있다는 것을 알게 되었다. 구현을 하기엔 사실 좀 복잡하다... 최근에 한 게시판 프로젝트에 암호화를 한 번 적용시켜도록 하자.
'organize > 스프링' 카테고리의 다른 글
스프링 웹 프로젝트 2 (0) | 2024.12.28 |
---|---|
스프링 웹 프로젝트 1 (3) | 2024.12.27 |
프레임워크, Spring과 Spring Boot (1) | 2024.10.04 |
redirect, redirect와 RequestDispatcher (0) | 2024.10.03 |
페이지 처리 (0) | 2024.10.02 |