@Configuration
SecurityConfig은 설정 파일이니
@Configuration을 사용해서 스프링에게 설정 파일이라는 사실을 알려준다
-> @Configuration을 가진 클래스는 스프링 컨테이너에 의해 관리되며 @Bean정의와 구성요소를 제공하게 된다.
예전 버전에서는
WebSecurityConfigurerAdapter을 상속받아서 사용했지만 이제는 상속받아서 사용하는 것이 아닌 -> @EnableWebSecurity로 대체
아래와 같이 @Bean으로 등록한 후 filterChain method 을 설정해서 사용하게 된다.
filterChain(HttpSecurity http) 메소드에서 HttpSecurity을 통해서 http에 대한 설정을하고
SecurityFilterChain을 반환하게 된다면
특정 URL패턴이나 규칙에 따라 다른 필터들을 적용할 수 있도록 된다.
HttpSecurity
spring Security에서 사용되는 클래스로,
웹 기반 보안에 대해 설정을 구성하는데 사용된다.
-> filterChain : 인증 , 인가 , 세션 ,로그인 기능을 정의하는 메소드
Httpsecurity를 통해서 설정하는 여러가지 방법들이 있는데
1. 인증설정
FormLogin : Form 기반 인증을 구성한다.
- loginPage(/loginForm) : 사용자정의 로그인 페이지를 지정한다.
- loginProcessingurl("/login") : 로그인 양식이 제출되는 URL을 설정
- defaultSuccessUrl("/") : 로그인이 성공적으로 진행 되었다면 리디렉션할 URL
http
.formLogin() // 폼 기반 로그인 설정
.loginPage("/loginForm") // 로그인 페이지 경로
.loginProcessingUrl("/login") // 로그인 처리 URL
.defaultSuccessUrl("/") // 로그인 성공 후 이동할 URL
.and()
.httpBasic().disable(); // HTTP 기본 인증 비활성화
2.인가 설정
authorizeRequests() : 권한 부여 구성을 시작한다.
- requestMatchers : URL 경로를 입력해주고
- permitAll() , authenticated() , hasRole() 여러가지의 접근 제한 설정 가능
- 그 뒤에 해당하는 보안요소를 추가해준다 권한이 있다거나 , 모두 입장이 된다거나 , 아무도 못들어간다거나 ,,,,
- ex ) requestMatchers.hasAnyRole("ADMIN")
http
.authorizeRequests()
.requestMatchers("/public/**").permitAll() // 특정 URL 패턴에 대한 전체 접근 허용
.requestMatchers("/user/**").authenticated() // 인증된 사용자만이 접근 허용
.requestMatchers("/admin/**").hasRole("ADMIN") // "ADMIN" 역할을 가진 사용자만이 접근 허용
.anyRequest().permitAll(); // 나머지 URL에 대한 접근은 허용
3. CSRF 설정
CSRF : Cross-Site Request Forgery 공격
HttpBasic.disable() : HTTP기본 인증을 비활성화 한다.
http
.csrf().disable(); // CSRF 공격 방어 비활성화
4. 세션관리 설정
세션 생성 정책, 세션 고정 보호 ,최대 세션 허용등을 구성
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 세션 생성 정책 설정 (STATELESS: 세션 사용 안 함)
5.이외의 설정
permitAll()
커스텀 필터 적용 :
addFilterBefore() , addFilterAfter() 메소드를 사용해서 필터 적용 가능
특정 요청에 대한 추가적인 처리가 가능해진다.
http
.addFilterBefore(new MyCustomFilter(), BasicAuthenticationFilter.class);
spring 3.x 버전 SecurityConfig의 전체적인 모습
@Configuration
@EnableWebSecurity // -> 스프링 시큐리티 필터가 스프링 필터체인에 등록이 된다.
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {
//헤당 메서드의 리턴되는 오브젝트를 IOC로 등록해줌
//@Bean 어노테이션을 사용하면 다른 파일에서도 사용이 가능해 진다.
@Bean
public BCryptPasswordEncoder encoderPwd(){
return new BCryptPasswordEncoder();
}
//hasAnyRole에는 ROLE_ 이포함되면안되지만 User Entity에는 포함되어야한다.(ROLE_USER)
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http
.csrf().disable()
// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// .and()
.formLogin()
.loginPage("/loginForm")
.loginProcessingUrl("/login") // /login가 호출되면 시큐리티가 낚아채서 대신 로그인 진행
.defaultSuccessUrl("/") //성공하면 여기로 이동
.and()
.httpBasic().disable()
// .apply(new MyCustomDsl()) // 커스텀 필터 등록
// .and()
.authorizeRequests()
.requestMatchers("/user/**").authenticated()
.requestMatchers("/manager/**").hasAnyRole("MANAGER" , "ADMIN")
.requestMatchers("/admin/**").hasAnyRole( "ADMIN")
.anyRequest().permitAll();
return http.build();
}
}
결론
Spring Security에서 SecurityConfig class가 구성하는 방법
1. Security Configuration
애플리케이션이 시작 될때 Security Configuration 클래스가 로딩
@EnableWebSecurity 가 있다면 Spring Security가 활성화 된다.
2.SecurityFilterChain Bean 생성
SecurityConfig 에서 FilterChain Bean을 정의 -> IOC 컨테이너에 등록됨
3.FilterChain 구성
FilterChain 내에서 HttpSecurity 객체를 통해 필터 체인을 구성한다.
추가적인 기능들
BCryptPasswordEncoder
기본적으로 SecurityConfig class파일에서 @Bean으로 등록해서 사용한다.
BCryptPasswordEncoder : 비밀번호를 안전하게 해시화하는 기능을 제공하는 인코딩(암호화)class
BCrypt는 해시 함수의 일종 -> 결국 비밀번호 해시화해서 보안성 높임
BCrypt의 특징
- 각 비밀번호에 무작의 Salt값을 부여하여 동일한 비밀번호에 대해서 항상 다른 해시값을 사용 -> 레인보우 테이블 공격에 대해 방어가능
- 해쉬화 할때 여러번의 라운드를 통해 고도의 연산 비용을 요구 -> 브루트 포스 공격에 대한 보안성 높임
@Bean
public BCryptPasswordEncoder encoderPwd(){
return new BCryptPasswordEncoder();
}
@Bean을 등록햇으니
다른 클래스에서 이러한 형태로 사용이 가능해진다.
encode(CharSequence rawPassword) : 주어진 비밀번호를 해시화하여 반환
mathes(CharSequence rawPassword , String encodedPassword) : 주어진 비밀번호가 해당 해시 값과 일치하는지 확인
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@EnableWebSecurity
Spring Security의 웹 보안 설정을 활성화하는데 사용된다.
@EnableWebSecurity을 사용하면 WebSecurityConfigurerAdapter를 확장한 클래스를 생성할 수 있다.
이 어노테이션 안에 여러가지의 설정 class들이 포함되어있다
간단하게 이 어노테이션을 사용해서 웹 보안 설정을 시작할 수 있다.
@Import({ WebSecurityConfiguration.class, SpringWebMvcImportSelector.class, OAuth2ImportSelector.class,
HttpSecurityConfiguration.class })
@EnableGlobalAuthentication
public @interface EnableWebSecurity {
/**
* Controls debugging support for Spring Security. Default is false.
* @return if true, enables debug support with Spring Security
*/
boolean debug() default false;
}
@EnableMethodSecurity(securedEnabled = ture)
이 어노테이션을 사용하면 메소드 수준의 보안을 활성화 할 수 있다.
지금까지는 전체적인 것에 대해서 설정이엿다면
이 어노테이션을 선언해주고 해당 Controller의 메소드에 @Secured(접근 권한)을 설정해주면 메소드 단위로 접근제한 설정이 가능하다
@Secured("ROLE_ADMIN")
@GetMapping("/news")
public @ResponseBody String news(){
return "새로운 소식";
}
'Spring' 카테고리의 다른 글
[Spring][Spring Security] Filter로 어떤걸 할 수 있을까 (1) | 2024.03.07 |
---|---|
[Spring][SpringSecurity] UserDetails,UserDetailsService 사용하는 이유 (0) | 2024.03.05 |
[Spring] 벌크성 쿼리 주의점 (1) | 2024.01.13 |
[Spring] 스프링 데이터 JPA 페이징 (0) | 2024.01.12 |
[Spring] 스프링 JPA 메소드 설정 (0) | 2024.01.11 |