Spring Security란?
Spring Security는 웹 애플리케이션의 인증 및 권한 관리를 간편하게 처리할 수 있는 프레임워크이다. 이를 통해 개발자들은 보안에 대한 고민을 최소화하고, 실제 비즈니스 로직에 집중할 수 있다.
예시
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}password").roles("USER", "ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").hasAnyRole("USER", "ADMIN")
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/login");
}
}
기본 설정
Spring Boot는 Spring Security를 자동으로 구성해 준다. 그러나 프로젝트에 맞는 보안 설정을 적용하기 위해서는 다음과 같은 어노테이션과 클래스를 사용한다.
- @EnableWebSecurity: 웹 보안을 활성화하고, Spring Security 설정을 사용하도록 지정한다
- WebSecurityConfigurerAdapter: 클래스를 상속받아 사용자 정의 보안 설정을 구성한다.
사용자 저장소의 종류
- Spring Security는 다양한 사용자 저장소를 지원.
- 인메모리: 테스트 목적이나 간단한 시나리오에 사용.
- JDBC: 데이터베이스에 저장된 사용자 정보를 사용.
- LDAP: LDAP 서버에 저장된 사용자 정보를 사용.
사용자 저장소 구성 방법
사용자 저장소를 구성하는 방법은 선택한 저장소에 따라 다르다. 아래 예제는 인메모리 사용자 저장소를 구성하는 방법을 보여준다.
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("admin").password("{noop}adminpassword").roles("USER", "ADMIN");
}
비밀번호 인코딩 및 저장 방법
비밀번호 인코딩은 사용자의 비밀번호를 안전하게 저장하고 관리하기 위한 방법이다. 예를 들어, BCryptPasswordEncoder를 사용하여 비밀번호를 인코딩할 수 있다.
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("user").password(passwordEncoder().encode("password")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("adminpassword")).roles("USER", "ADMIN");
}
인가
권한 기반 접근 제어 (Role-Based Access Control, RBAC)
Spring Security는 권한 기반 접근 제어를 통해 사용자에게 허용된 리소스에만 접근하도록 할 수 있다. 예를 들어, ADMIN 역할을 가진 사용자만 관리자 페이지에 접근할 수 있도록 설정할 수 있다.
아래는 URL 패턴 및 메서드 보안을 통한 접근 제어 설정 방법 예시이다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").hasAnyRole("USER", "ADMIN")
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/login");
}
표현식 기반 접근 제어 (SpEL)
Spring Security는 SpEL을 사용하여 표현식 기반의 접근 제어를 구현할 수 있다. 특정 사용자가 다른 사용자의 데이터에 접근하려고 할 때, 이를 허용할지 거부할지 결정하는 데 사용할 수 있다.
http.authorizeRequests()
.antMatchers("/user/**").access("hasRole('USER') and authentication.name == principal.username")
.anyRequest().authenticated();
로그아웃 및 세션 관리
로그아웃 처리 및 성공 시 이동할 URL 설정 방법
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").hasAnyRole("USER", "ADMIN")
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/login");
}
세션 관리 전략 설정 (고정 세션, 마이그레이션, 변경 등)
http.sessionManagement()
.sessionFixation()
.migrateSession()
.maximumSessions(1)
.maxSessionsPreventsLogin(true);
기타 기능
OAuth2, OpenID Connect 등의 외부 인증 서비스 연동 방법 Spring Security는 OAuth2 및 OpenID Connect와 같은 외부 인증 서비스와의 연동을 지원한다. 이를 통해 서드파티 인증 공급자를 사용하여 인증을 처리할 수 있다.
- 의존성 추가: 프로젝트에 OAuth2 클라이언트 및 관련 의존성을 추가한다.
- application.properties 파일에 인증 공급자에 관한 정보를 설정한다.
- SecurityConfig 클래스에서 OAuth2 로그인을 활성화하고, 사용자 정보를 처리하는 방법을 구성한다.
CSRF (Cross-Site Request Forgery) 보호 기능 사용 방법
Spring Security는 기본적으로 CSRF 공격을 방어하기 위한 기능을 제공한다. 이 기능은 폼 기반 인증을 사용할 때 활성화되어 있다. 필요에 따라 이 기능을 비활성화하거나 특정 URL 패턴에 대해서만 적용할 수 있다.
http.csrf()
.ignoringAntMatchers("/api/**");
CORS (Cross-Origin Resource Sharing) 설정 방법
CORS는 다른 도메인 간 리소스 공유를 허용하는 기능이다. Spring Security는 이 기능을 쉽게 구성할 수 있도록 지원한다.
- CorsConfigurationSource 빈을 정의하고 원하는 CORS 설정을 구성한다.
- SecurityConfig 클래스에서 CORS 필터를 활성화한다.
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
// 기타 보안 설정
}
'Develop > Java' 카테고리의 다른 글
[Java] javax.crypto.BadPaddingException: Given final block not properly padded 오류 (0) | 2023.01.06 |
---|