복붙노트

[SPRING] 스프링 부트 : accessDeniedHandler가 작동하지 않습니다.

SPRING

스프링 부트 : accessDeniedHandler가 작동하지 않습니다.

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

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/private/**", "/app/**").authenticated();
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");
        http.exceptionHandling().accessDeniedPage("/403"); //.accessDeniedHandler(accessDeniedHandler);
    }
}

나는 다음과 같은 논리를 기대한다. 인증 된 사용자는 / 403으로 리다이렉트되지 않을 것이다. 대신 Spring은 기본 Tomcat 403 페이지를 표시합니다. 나는 또한 어떤 성공에도 불구하고 custom accessDeniedHandler를 시도했다.

어떻게 액세스 실패시 사용자 정의 논리를 구현할 수 있습니까?

해결법

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

    1.AccessDeniedHandler는 인증 된 사용자에게만 적용됩니다. 인증되지 않은 사용자의 기본 동작은 로그인 페이지 (또는 사용중인 인증 메커니즘에 적합한 모든 것)로 리디렉션하는 것입니다.

    AccessDeniedHandler는 인증 된 사용자에게만 적용됩니다. 인증되지 않은 사용자의 기본 동작은 로그인 페이지 (또는 사용중인 인증 메커니즘에 적합한 모든 것)로 리디렉션하는 것입니다.

    이 값을 변경하려면 인증되지 않은 사용자가 보호 자원에 액세스하려고 할 때 호출되는 AuthenticationEntryPoint를 구성해야합니다. 당신은 사용할 수 있어야합니다.

    http.exceptionHandling().authenticationEntryPoint(...)
    

    네가 가진 것 대신에. 자세한 내용은 API 문서를 확인하십시오.

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

    2.이 질문에 대해 생각해 보면, 내 문제를 해결하는 데 도움이되었다. 아래 코드는 다음과 같다.

    이 질문에 대해 생각해 보면, 내 문제를 해결하는 데 도움이되었다. 아래 코드는 다음과 같다.

    public class CustomHttp403ForbiddenEntryPoint implements AuthenticationEntryPoint {
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
            response.getWriter().print("You need to login first in order to perform this action.");
        }
    
    }
    
    public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException arg2)
                throws IOException, ServletException {
            response.getWriter().print("You don't have required role to perform this action.");
        }
    
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler()).and()
            .exceptionHandling().authenticationEntryPoint(new CustomHttp403ForbiddenEntryPoint());
    }
    

    희망이 도움이됩니다.

  3. ==============================

    3.일반적인 스프링 보안 동작은 인증되지 않은 사용자를 아래와 같이 로그인 페이지로 리디렉션하는 것입니다. 승인되지 않은 사용자 (ADMIN 역할 없음)가 액세스 거부 페이지로 연결됨을 인증합니다.

    일반적인 스프링 보안 동작은 인증되지 않은 사용자를 아래와 같이 로그인 페이지로 리디렉션하는 것입니다. 승인되지 않은 사용자 (ADMIN 역할 없음)가 액세스 거부 페이지로 연결됨을 인증합니다.

    http.authorizeRequests().antMatchers("/admin/**")
        .access("hasRole('ADMIN')")
        .and().formLogin().loginPage("/login")
        .and().exceptionHandling().accessDeniedPage("/403");
    

    자신의 인증 메커니즘을 구현했고 인증되지 않은 사용자를 로그인 페이지로 전달하기 위해 스프링 보안 설정을 신뢰하지 않는다면 다음과 같이 스프링 보안 구성을 게임 할 수 있습니다 - 실제 로그인 페이지 대신 사용자 정의 403 페이지를 제공합니다 :

    http.authorizeRequests().antMatchers("/admin/**")
        .access("hasRole('ADMIN')")
        .and().formLogin().loginPage("/403")
        .and().exceptionHandling().accessDeniedPage("/403");
    
  4. from https://stackoverflow.com/questions/28057592/spring-boot-accessdeniedhandler-does-not-work by cc-by-sa and MIT license