강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

bae jewoo님의 프로필 이미지
bae jewoo

작성한 질문수

스프링 시큐리티 완전 정복 [6.x 개정판]

RequestMatcherDelegatingAuthorizationManager 로 인가 설정 응용하기

구조 개선하기

작성

·

134

·

수정됨

0

@EnableWebSecurity
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception{
        http
                .addFilterAt(authorizationFilter(introspector), AuthorizationFilter.class)
                .formLogin(Customizer.withDefaults())
                .csrf(AbstractHttpConfigurer::disable);
        return http.build();
    }
    @Bean
    public AuthorizationFilter authorizationFilter(HandlerMappingIntrospector introspector){
        List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings = new ArrayList<>();

        RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> requestMatcherEntry1
                = new RequestMatcherEntry<>(
                        new MvcRequestMatcher(introspector, "/user"),
                        AuthorityAuthorizationManager.hasAuthority("ROLE_USER"));

        RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> requestMatcherEntry2
                = new RequestMatcherEntry<>(
                        new MvcRequestMatcher(introspector, "/db"),
                        AuthorityAuthorizationManager.hasAuthority("ROLE_DB"));

        RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> requestMatcherEntry3
                = new RequestMatcherEntry<>(
                        new MvcRequestMatcher(introspector, "/admin"),
                        AuthorityAuthorizationManager.hasAuthority("ROLE_ADMIN"));

        RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> requestMatcherEntry4
                        = new RequestMatcherEntry<>(
                                AnyRequestMatcher.INSTANCE,
                                // default strategy = AuthenticatedAuthorizationStrategy
                                new AuthenticatedAuthorizationManager<>());

        mappings.add(requestMatcherEntry1);
        mappings.add(requestMatcherEntry2);
        mappings.add(requestMatcherEntry3);
        mappings.add(requestMatcherEntry4);

        RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
                .mappings(maps -> maps.addAll(mappings)).build();
        return new AuthorizationFilter(manager);
    }

    @Bean
    public UserDetailsService userDetailsService(){
        UserDetails user = User.withUsername("user").password("{noop}1111").roles("USER").build();
        UserDetails db = User.withUsername("db").password("{noop}1111").authorities("ROLE_DB").build();
        UserDetails admin = User.withUsername("admin").password("{noop}1111").roles("ADMIN","SECURE").build();
        return  new InMemoryUserDetailsManager(user, db, admin);
    }
}

필터에 직접 RequestMatcherDelegatingAuthorizationManager를 넣는 방식으로 개선해 봤습니다

처음에는 RequestMatcherDelegatingAuthorizationManager -> RequestMatcherDelegatingAuthorizationManager 구조로 바꾸려고 했는데
access()에는 AuthorizationManager<RequestAuthorizationContext>만 가능해서
AuthorizationManager<HttpServletRequest>인
RequestMatcherDelegatingAuthorizationManager를 바로 못 넣더라구요

그래서 필터를 생성하고 필터 생성자로 RequestMatcherDelegatingAuthorizationManager를 넣는 방식을 사용했습니다

답변 1

0

안녕하세요, 인프런 AI 인턴입니다. bae jewoo님께서 스프링 시큐리티의 필터 구성에 대해 구조를 개선하신 것 같네요. 필터에 직접 RequestMatcherDelegatingAuthorizationManager를 사용하여 요청 매처 기반 접근 제어를 구성하신 방법이 인상적입니다.

이 방식은 각 URL 패턴에 대해 개별 권한을 정의하고 AuthorizationFilter를 통해 효과적으로 이를 적용할 수 있는 유용한 방법입니다. 각 RequestMatcherEntry를 사용하여 특정 역할 권한 검사를 설정하셨고, 마지막에 모든 요청에 대해 기본적으로 인증된 사용자만 접근하도록 설정하신 것으로 보입니다.

관련 논의는 아래 URL에서 찾아보실 수 있습니다:

위 링크에서는 Spring Security 6 버전 이상의 다중 보안 설정에 관한 내용을 논의하고 있으며, 새로운 보안 설정 기법에 대해 자세한 설명을 제공하고 있습니다. 이러한 방법을 적용하면, 스프링의 최신 보안 기능들을 활용하여 보다 견고한 보안 설정을 할 수 있습니다.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.

bae jewoo님의 프로필 이미지
bae jewoo

작성한 질문수

질문하기