DevBoi

[Spring security] Authorization path 오류해결 본문

Develop/[Spring_Security]

[Spring security] Authorization path 오류해결

HiSmith 2023. 10. 28. 19:45
반응형

최근 진행 작업중, 특정 autorization path를 설정해도, 전체 path에 적용되어 

모든 인가처리를 하게 되어 성능이 낮아지고 오류가 난적이있다.

 

그래서 해결한 방법 중 하나를 기록하려고한다.

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        return http
                .authorizeHttpRequests((authorize) -> authorize
                    .requestMatchers("/api/public").permitAll()
                    .requestMatchers("/api/private").authenticated()
                    .requestMatchers("/api/private-scoped").hasAuthority("SCOPE_read:messages")
                )
                .cors(withDefaults())
                .oauth2ResourceServer(oauth2 -> oauth2
                    .jwt(withDefaults())
                )
                .build();
    }
}

 

쉽게 말하면 위와 같이 해당 인증이 필요한 경로에 대해 설정한다.

하지만, oauth2ResourceServer에 동작하는 소스는 전체 url 에 진행이 되었다.

그래서 해결 하기 위해 아래와 같이 바꿨다.

 

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        return http
                .authorizeHttpRequests((authorize) -> authorize
                	.securityMatcher("/securityapi")
                    .requestMatchers("/api/public").permitAll()
                    .requestMatchers("/api/private").authenticated()
                    .requestMatchers("/api/private-scoped").hasAuthority("SCOPE_read:messages")
                )
                .cors(withDefaults())
                .oauth2ResourceServer(oauth2 -> oauth2
                    .jwt(withDefaults())
                )
                .build();
    }
}

차이는 단순히 securityMatcher에 대한 추가이다.

 

requestMatcher와 securityMatcher의 차이는 무엇일까?

외국인들도 이 차이에 대해서 많은 문의를 가진다.

테스트를 해본 결과, 시큐리티 적용에 대한 범위가 달라지는듯 하다.

 

이건 시큐리티의 신규 기능인데, 시큐리티에서 전체 애플리케이션에 대한 시큐리티 적용이 맘에 들지않아서

멀티플하게 컨피규레이션을 적용할 수있게 했다고 한다.

즉 시큐리티 적용하면 전체 다 적용되던것을 나눠서 분리해서 시큐리티 경로에 대한 지정을 하여, 해당 경로 하위부터 시큐리티 적용을 할 수 있게 했다고 한다.

 

그게 securityMatcher이고, 해당 경로로 분리가 가능하다.

 

Dan vega 할아버지의 설명은 아래 링크에서 확인이 가능하다.

https://www.youtube.com/watch?v=PczgM2L3w60

 

 

 

해당 직접 경로를 가면 아래와 같이 확인이 가능하다.

 

패턴이 일치할때만 시큐리티 적용을 설정할 수 있다.

 

6개월 전에 나온 내용으로, 해당 기능으로 전체 시큐리티에 대한 적용이 아닌, 부분 적용을 할 수있다.

즉 빈을 멀티플 하게 쪼갤수 있는 것이다. 

 

잘 활용하도록 하자.

반응형

'Develop > [Spring_Security]' 카테고리의 다른 글

[Spring_Security] 스프링 시큐리티의 이해  (0) 2022.02.20