Как исправить переопределение по умолчанию AccessDeniedHandler (AccessDeniedHandlerImpl) в конфигурации Spring Security (Java)? - PullRequest
0 голосов
/ 15 апреля 2019

У меня небольшое веб-приложение на основе Spring MVC и Spring Security .У меня возникают трудности с настройкой собственной AccessDeniedHandler, которая должна перенаправлять неавторизованных пользователей на мою страницу ошибок.

Я использую http.exceptionHandling().accessDeniedHandler(accessDeniedHandler) в своем классе конфигурации, который расширяет WebSecurityConfigurerAdapter.Значение по умолчанию AccessDeniedHandler продолжает вызываться, несмотря на настройку (я отлаживал ExceptionTranslationFilter).В результате отображается страница ошибки, определенная контейнером, вместо моей пользовательской.

У вас есть идея, чего мне здесь не хватает?В чем может быть проблема?Спасибо за вашу помощь.

Выдержка из моего Суперкласса WebSecurityConfigurerAdapter :

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/static/**", "/login/*", "/login").permitAll()
                .antMatchers("/site/admin*").hasRole("ADMIN")
                .anyRequest().authenticated()
            .and().formLogin()
                .loginPage("/login")
                .usernameParameter("user-name")
                .passwordParameter("password")
                .defaultSuccessUrl("/site/welcome", true)
                .loginProcessingUrl("/process-login")
                .failureUrl("/login?login_error=1")
            .and().logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
            .and().sessionManagement()
                .invalidSessionUrl("/login")
            .and().csrf()
            .and().exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}

Мой пользовательский AccessDeniedHandler Реализация:

@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    private static Logger LOG = Logger.getLogger(CustomAccessDeniedHandler.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
            AccessDeniedException accessDeniedException) throws IOException, ServletException {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            LOG.warn(String.format("User [%s] attempted to access the protected URL [%s]!", authentication.getName(), request.getRequestURI()));
        }

        response.sendRedirect(request.getContextPath() + "/site/403");
    }
}

1 Ответ

0 голосов
/ 16 апреля 2019

Я забыл назначить параметр конструктора autowired для поля! Прошу прощения за то, что опубликовал здесь такую ​​тривиальную проблему, но после того, как я потратил полдня на поиски решения, я был слеп и пропустил это ...

public SpringSecurityConfiguration(
            AccessDeniedHandler accessDeniedHandler, ...) {
        this.accessDeniedHandler = accessDeniedHandler; // This line was missing.
        ...
}
...