Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

DS's TechBlog

[Spring Security] authorizeHttpRequests 우선순위 적용하기 본문

Java & Spring

[Spring Security] authorizeHttpRequests 우선순위 적용하기

dsjo 2024. 5. 17. 17:33

Spring Security로 인증/인가를 구현하였는데, 문제가 생겼습니다.

특정 엔드포인트의 권한이 제대로 설정되지 않았습니다.

문제 상황

        http
                .authorizeHttpRequests((auth) -> auth
                        .requestMatchers("/login", "/", "/join/**", "/reissue", "/swagger-ui/**", "/v3/api-docs/**", "/users/**").permitAll()
                        .requestMatchers("/admin/**", "/users/inactive").hasAnyRole("WEB_MASTER", "ADMIN")
                        .anyRequest().authenticated());

 

/users/inactive 엔드포인트는 관리자만 액세스 할 수 있도록 구성하고자 했습니다.

하지만, Swagger로 테스트해보니 관리자가 아닌 사용자의 요청에도 200번 응답을 반환하고 있습니다.

문제 원인

AuthorizationFilter processes these pairs in the order listed, applying only the first match to the request.
(AuthorizationFilter는 나열된 순서대로 이러한 쌍을 처리하여 요청에 첫 번째 일치 항목만 적용합니다.)

 

Spring 공식 문서에서 원인을 찾을 수 있었습니다. 

users/** 엔드포인트에 대해서 permitAll로 먼저 설정한 후에 users/inactive 엔드포인트에 특정 권한을 설정한 것이 문제였습니다.

 

Authorize HttpServletRequests :: Spring Security

While using a concrete AuthorizationManager is recommended, there are some cases where an expression is necessary, like with or with JSP Taglibs. For that reason, this section will focus on examples from those domains. Given that, let’s cover Spring Secu

docs.spring.io

해결 방법

        http
                .authorizeHttpRequests((auth) -> auth
                        .requestMatchers("/admin/**", "/users/inactive").hasAnyRole("WEB_MASTER", "ADMIN")
                        .requestMatchers("/login", "/", "/join/**", "/reissue", "/swagger-ui/**", "/v3/api-docs/**", "/users/**").permitAll()
                        .anyRequest().authenticated());

위와 같이 특정 권한이 필요한 엔드포인트에 대해서 먼저 작성해 줍니다.

Swagger로 다시 요청해 보면, 관리자가 아닌 사용자의 요청에 403번 에러를 반환하는 것을 볼 수 있습니다.

 

이런 상황을 피하기 위해서는 authorizeHttpRequests로 권한을 설정해 줄 때, 포괄적인 URL보다 구체적인 URL에 대해서 먼저 권한을 부여하는 습관이 필요해 보입니다.