복붙노트

[SPRING] 보안 된 엔드 포인트에만 스프링 보안 필터를 적용하는 방법은 무엇입니까?

SPRING

보안 된 엔드 포인트에만 스프링 보안 필터를 적용하는 방법은 무엇입니까?

다음과 같은 스프링 보안 구성이 있습니다.

    httpSecurity
            .csrf()
            .disable()
            .exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/api/**").fullyAuthenticated()
            .and()
            .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

authenticationTokenFilterBean ()은 / api / ** 표현식과 일치하지 않는 끝점에서도 적용됩니다. 또한 다음 구성 코드를 추가하려고 시도했습니다.

@Override
public void configure(WebSecurity webSecurity) {
    webSecurity.ignoring().antMatchers("/some_endpoint");
}

그러나 이것은 여전히 ​​내 문제를 해결하지 못했습니다. 보안 된 URI 표현과 일치하는 엔드 포인트에서만 필터를 적용하도록 스프링 보안에 지시하려면 어떻게해야합니까? 고맙습니다

해결법

  1. ==============================

    1.나는 동일한 요구 사항을 가진 응용 프로그램을 가지고 있으며이를 해결하기 위해 기본적으로 Spring Security를 ​​antMatcher를 사용하여 주어진 ant match pattern으로 제한했다.

    나는 동일한 요구 사항을 가진 응용 프로그램을 가지고 있으며이를 해결하기 위해 기본적으로 Spring Security를 ​​antMatcher를 사용하여 주어진 ant match pattern으로 제한했다.

    http.antMatcher("/api/**").authorizeRequests() //
            .anyRequest().authenticated() //
            .and()
            .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    

    다음과 같이 읽을 수 있습니다. http는 ant 패턴 / api / **와 일치하는 요청에서만 이러한 구성을 호출하여 인증 된 사용자에게 요청을 인증하고 UsernamePasswordAuthenticationFilter 앞에 authenticationTokenFilterBean () 필터를 추가합니다. 다른 모든 요청의 경우이 구성은 효과가 없습니다.

  2. ==============================

    2.일부 특정 엔드 포인트에 대해 스프링 보안을 바이 패스하려면 다음을 수행하십시오.

    일부 특정 엔드 포인트에 대해 스프링 보안을 바이 패스하려면 다음을 수행하십시오.

    httpSecurity
         .authorizeRequests()
         .antMatchers("/some_endpoints").permitAll()
         .anyRequest().authenticated()
         .and()
         ...
    
  3. ==============================

    3.귀하가 .addFilterBefore (jwtAuthenticationFilter (), UsernamePasswordAuthenticationFilter.class);

    귀하가 .addFilterBefore (jwtAuthenticationFilter (), UsernamePasswordAuthenticationFilter.class);

    생성자에서 적용 할 특정 경로를 정의 할 수 있습니다.

    public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    
        public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
            super("/api/**");
            this.setAuthenticationManager(authenticationManager);
        }
    
        @Override
        protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
            return super.requiresAuthentication(request, response);
        }
    

    requiresAuthentication 메소드를 사용하여 해당 끝점에 인증이 필요한지 여부를 확인합니다.

  4. from https://stackoverflow.com/questions/36795894/how-to-apply-spring-security-filter-only-on-secured-endpoints by cc-by-sa and MIT license