예전부터 보안에 관심이 많았다. 혼자 일을 해보고 싶은데 해킹당해서 엄청 털리면 어떻게 하나 하는 생각을 많이해서, 학회에서 지원을 해줘서 강의를 들을 수 있던 기회가 있었는데 그 때 깊은 Level보다 당시 spring공부를 하고 있었어서 Spring Security강의를 들었다.

1. Security Config & Filter 2. Authentication & Authorization 3. Access Control 4. Filter

요렇게 4개의 챕터로 구성을 해놓았는데 최근에 Security가 조금 바뀌어서 요걸 잠깐만 정리하고 가보려고한다.

당시 환경은 아래와 같다.

- Java 17 (OpenJDK recommended)

- Junit : 4.13.1
- spring-boot : 3.1.3
- spring-integration : 6.1.2
- spring-security : 6.1.3

이전에는 아래와 같이 SecurityConfig를 정의해서 url Matcher를 만들고 이에 따라서 접근을 허용하기도 하고 인증을 하기도 했다.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends ~~WebSecurityConfigurerAdapter~~ {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .mvcMatchers("/","info").permitAll()
                .mvcMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}

하지만 최근에 나온 Spring Security는 SecurityFilterChain을 구현함으로써 SecurityConfig를 대체한다. 곧 decriped된다고 하니 코드가 바뀌어야 할 여지가 많을 것 같다.

조금 신기 했던 부분은 이전에는 chain을하면서 url matching을 정의했던 것 같은데 이번에는 lambda를 통해서 requestMatcher라는 걸로

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
         http
                 .csrf(AbstractHttpConfigurer::disable)
                 .headers(header ->{
                     header.frameOptions(frameOptionsConfig -> {
                        frameOptionsConfig.sameOrigin();
                     });
                 })
                .authorizeHttpRequests((authz) -> authz
                        .requestMatchers(new AntPathRequestMatcher("/uri/")).permitAll()
                        .requestMatchers(new AntPathRequestMatcher("/uri2/")).hasAnyRole("USER","ADMIN")
                        .requestMatchers(new AntPathRequestMatcher("/uri3/")).hasAnyRole("USER_A")
                        .requestMatchers(new AntPathRequestMatcher("/uri4/")).hasAnyRole("USER_B")
                        .requestMatchers(new MvcRequestMatcher(introspector,"/h2-console/**")).permitAll()
                        .anyRequest().authenticated()
                ).exceptionHandling(exception ->{
                     exception.authenticationEntryPoint(jwtAuthenticationEntryPoint);
                     exception.accessDeniedHandler(jwtAccessDeniedHandler);
                 })
                 .apply(new JwtSecurityConfig(tokenProvider));
        return http.build();
    }