prosource

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

probook 2023. 7. 17. 21:14
반응형

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

다음과 같은 Spring Security 구성이 있습니다.

@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그 대신 봄에는 기본 Tomcat 403 페이지가 표시됩니다.나는 또한 커스텀을 시도했습니다.accessDeniedHandler아무런 성과도 없이

액세스 실패 시 사용자 지정 논리를 구현하려면 어떻게 해야 합니까?

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

변경하려면 다음을 구성해야 합니다.AuthenticationEntryPoint인증되지 않은 사용자가 보호된 리소스에 액세스하려고 할 때 호출됩니다.사용할 수 있어야 합니다.

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

당신이 가진 것 대신에.자세한 내용은 API 문서를 참조하십시오.

이 질문을 접하면 문제를 해결하는 데 도움이 됩니다. 아래는 제 코드입니다.

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());
}

이게 도움이 되길 바랍니다.

일반적인 Spring Security 동작은 아래 구성된 대로 인증되지 않은 사용자를 로그인 페이지로 리디렉션하는 것입니다.권한이 없는(ADMIN 역할이 없는) 사용자를 인증하면 액세스 거부 페이지로 이동합니다.

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

자체 인증 메커니즘을 구현했지만 인증되지 않은 사용자를 로그인 페이지로 전달하기 위해 Spring Security 구성을 사용하지 않을 경우, 실제 로그인 페이지 대신 사용자 지정 403 페이지를 제공하기 위해 다음과 같이 Spring Security 구성을 게임할 수 있습니다.

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

사용:-

@Configuration
public class ViewRegistryConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/403").setViewName("notAuth");
    }

}

템플릿 폴더에 notAuth.html 페이지를 만듭니다.

언급URL : https://stackoverflow.com/questions/28057592/spring-boot-accessdeniedhandler-does-not-work

반응형