728x90
Custom DSLs - HttpSecurity.with(AbstractHttpConfigurer)
- Spring Security는 사용자 정의 DSL을 구현할 수 있도록 지원
- DSL(Domain Specific Language)을 구성하면 필터, 핸들러, 메서드, 속성 등을 한 곳에 정의하여 처리할 수 있는 편리함을 제공
AbstractHttpConfigurer<AbstractHttpConfigurer, HttpSecurityBuilder>
- 사용자 DSL을 구현하기 위해서 상속 받는 추상 클래스로서 구현 클래스는 두 개의 메서드를 오버라이딩
- init(B builder) → HttpSecurity 의 구성요소를 설정 및 공유하는 작업 등..
- configure(B builder) → 공통 클래스를 구성 하거나 사용자 정의 필터를 생성하는 작업 등..
API
- HttpSecurity.with(C configurer, Customizer<C> customizer)
- configurer는 AbstractHttpConfigurer을 상속하고 DSL을 구현한 클래스
- customizer는 DSL 구현 클래스에서 정의한 여러 API를 커스터 마이징
- 동일한 클래스를 여러 번 설정하더라도 한 번만 적용
코드 구현
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
http
.authorizeHttpRequests(authorize -> authorize
.anyRequest().authenticated()
)
.formLogin(withDefaults());
http.with(new MyCustomDsl(), dsl -> dsl.flag(true));
// MyCustomDsl 을 비활성화 한다
http.with(new MyCustomDsl(), dsl -> dsl.disabled());
return http.build();
}
public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
private boolean flag;
@Override
public void init(HttpSecurity http) throws Exception {
super.init(http);
}
@Override
public void configure(HttpSecurity http) throws Exception {
AuthenticationManager manager = http.getSharedObject(AuthenticationManager.class);
MyAuthFilter myAuthFilter = new MyAuthFilter(manager);
myAuthFilter.setFlag(flag);
http.addFilterAfter(myAuthFilter, SecurityContextHolderAwareRequestFilter.class);
}
public MyCustomDsl flag(boolean value) {
this.flag = value;
return this;
}
public static MyCustomDsl customDsl() {
return new MyCustomDsl();
}
}
추가 내용
- 인증과 인가에 필요한 Filter와 Filter가 필요로 하는 클래스, 각 클래스마다의 설정하는 등의 초기화 작업을 할 때 SecurityBuilder, SecurityConfigurer가 필요
- SecurityBuilder → HttpSecurity 생성
- SecurityConfigurer → HttpSecurity를 통해 생성되는 많은 설정 클래스
- FormLoginConfigurer, LogoutConfigurer 등등
- DSL은 사용자가 만든 커스텀 클래스를 위와 같이 초기 설정을 할 때 추가를 하고 보다 직관적으로 보안 구성을 정의할 수 있도록 함
728x90
'Language > Spring Security' 카테고리의 다른 글
[PasswordEncoder] BCryptPasswordEncoder (0) | 2024.08.28 |
---|---|
Redis를 활용한 이중화 설정 - @EnableRedisHttpSession (0) | 2024.08.03 |
다중 보안 설정 (0) | 2024.08.03 |
Spring MVC 비동기 통합 - WebAsyncManagerIntergrationFilter (0) | 2024.08.03 |
Spring MVC 통합 - @AuthenticationPrincipal (0) | 2024.08.03 |