Конфигурация безопасности не позволяет мне использовать antMatchers() на некоторых страницах

Конфигурация безопасности не позволяет мне использовать antMatchers() на некоторых страницах. Ниже приведен код конфигурации, в котором я пытаюсь разрешить незарегистрированным пользователям доступ "/", "/ records", "/ signup". С "/ signup" нет проблем, он позволяет мне посещать эту страницу, но он продолжает перенаправлять меня на страницу входа, если я пытаюсь получить доступ к "/" или "/ records". Я пытался записать каждый URI в отдельные antMatchers() и переключать ордера, но пока не повезло.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
  @Autowired
  DetailService userDetailsService;

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(User.PASSWORD_ENCODER);
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/", "/entries","/signup").permitAll()
        .antMatchers("/adminpanel/**")
        .access("hasRole('ROLE_ADMIN')")
        .and()
        .formLogin()
        .loginPage("/login")
        .permitAll()
        .successHandler(loginSuccessHandler())
        .failureHandler(loginFailureHandler())
        .and()
        .logout()
        .permitAll()
        .logoutSuccessUrl("/clearConnection")
        .and()
        .csrf();

    http.headers().frameOptions().disable();
  }

  public AuthenticationSuccessHandler loginSuccessHandler() {
    return (request, response, authentication) -> response.sendRedirect("/");
  }

  public AuthenticationFailureHandler loginFailureHandler() {
    return (request, response, exception) -> {
      response.sendRedirect("/login");
    };
  }

  @Bean
  public EvaluationContextExtension securityExtension() {
    return new EvaluationContextExtensionSupport() {
      @Override
      public String getExtensionId() {
        return "security";
      }

      @Override
      public Object getRootObject() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return new SecurityExpressionRoot(authentication) {
        };
      }
    };
  }

}

1 ответ

Очевидно, у меня был класс UserHandler с аннотацией @ControllerAdvice(basePackages = "myproject.web.controller"). Это означает, что это относится ко всем классам для предоставленного пакета. Мой addUser() пытается добавить пользователя в качестве атрибута и, если пользователя нет, выдает одно из исключений, определенных в том же классе, которые вызывают перенаправление. Итак, я создал отдельный GuestController вне пакета, предоставленного для @ControllerAdvice, и обработал всю логику для гостя в нем. Это решило мою проблему. Буду признателен за любые идеи о моем подходе, если это хорошая практика или нет.

@ControllerAdvice(basePackages = "myproject.web.controller")
public class UserHandler {
    @Autowired
    private UserService users;

    @ExceptionHandler(AccessDeniedException.class)
    public String redirectNonUser(RedirectAttributes attributes) {
        attributes.addAttribute("errorMessage", "Please login before accessing website");
        return "redirect:/login";
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public String redirectNotFound(RedirectAttributes attributes) {
        attributes.addAttribute("errorMessage", "Username not found");
        return "redirect:/login";
    }

    @ModelAttribute("currentUser")
    public User addUser() {
        if(SecurityContextHolder.getContext().getAuthentication() != null) {
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            User user = users.findByUsername(username);
            if(user != null) {
                return user;
            } else {
                throw new UsernameNotFoundException("Username not found");
            }
        } else {
            throw new AccessDeniedException("Not logged in");
        }
    }
}    
Другие вопросы по тегам