목차
1. 의존 라이브러리 추가(build.gradle)
dependencies {
...
implementation 'org.springframework.boot:spring-boot-starter-security'
...
}
2. Spring Security Configuration 적용
기본 구조
package com.springboot.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SecurityConfiguration {
// 여기에 Spring Security의 설정 진행
}
3. HTTP 보안 구성
- HttpSecurity를 파라미터로 가지고, SecurityFilterChain을 리턴하는 형태의 메서드를 정의하면 HTTP 보안 설정 구성 가능
- SecurityFilterChain을 Bean으로 등록해서 HTTP 보안 설정을 구성하는 방식 권장
기본 구조
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// HttpSecurity를 통해 HTTP 요청에 대한 보안 설정 구성
}
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("won@gmail.com")
.password("1111")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
SecurityFilterChain
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.formLogin() // 기본 인증 방법을 폼 로그인으로 지정
.loginPage("/auths/login-form") // 커스텀 로그인 페이지로 연결
.loginProcessingUrl("/process_login") // 로그인 인증 요청을 수행할 요청 URL 지정
.failureUrl("/auths/login-form?error") // 로그인 실패 시 리다이렉트할 화면 지정
.and()
// 클라이언트의 요청에 대한 접근 권한 확인
.authorizeHttpRequests() // 클라이언트 요청이 들어오면 접근 권한을 확인하겠다고 정의
.anyRequest().permitAll(); // 모든 요청에 대해 접근 허용
return http.build();
}
Request URI에 접근 권한 부여
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.formLogin()
.loginPage("/auths/login-form")
.loginProcessingUrl("/process_login")
.failureUrl("/auths/login-form?error")
.and()
// exceptionHandling() - Exception 처리 메서드
.exceptionHandling().accessDeniedPage("/auths/access-denied") // 403(Forbidden) 에러 처리를 위한 페이지로 설정
.and()
.authorizeHttpRequests(authorize -> authorize // request URI에 대한 접근 권한 부여
// anyMatchers는 순서 주의! 구체적 -> 덜 구체적 순으로
.antMatchers("/orders/**").hasRole("ADMIN") // "ADMIN"만 /orders로 시작하는 모든 URL에 접근 가능
.antMatchers("/members/my-page").hasRole("USER")
.antMatchers("/**").permitAll() // 앞에서 지정한 URL 이외의 나머지 모든 URL은 Role에 상관없이 접근 가능
);
return http.build();
}
로그아웃 기능 추가
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.formLogin()
.loginPage("/auths/login-form")
.loginProcessingUrl("/process_login")
.failureUrl("/auths/login-form?error")
.and()
.logout() // 로그아웃 호출, 로그아웃 설정을 위한 LogoutConfigurer 리턴
.logoutUrl("/logout") // 로그아웃을 수행하기 위한 request URL 지정
.logoutSuccessUrl("/") // 로그아웃을 성공적으로 수행한 이후 리다이렉트 할 URL 지정
.and()
.exceptionHandling().accessDeniedPage("/auths/access-denied")
.and()
.authorizeHttpRequests(authorize -> authorize
.antMatchers("/orders/**").hasRole("ADMIN")
.antMatchers("/members/my-page").hasRole("USER")
.antMatchers("/**").permitAll()
);
return http.build();
}
728x90
'Backend Development > SPRING' 카테고리의 다른 글
| [Spring] 비동기 환경에서 컨텍스트 정보 전달 방법 (0) | 2025.10.20 |
|---|---|
| [Spring Security] 인증/인가 프로세스 (0) | 2025.09.29 |
| [Batch] BatchConfig 틀 (0) | 2025.09.06 |
| [Batch] Spring Batch 이론 (0) | 2025.09.06 |
| [Spring 안정성] 7-1. Spring Actuator (1) | 2025.08.13 |