0

安全配置不允许我在某些页面上使用 antMatchers()。下面是一个配置代码,我试图让未登录的用户访问“/”、“/entries”、“/signup”。使用“/signup”没有问题,它可以让我访问该页面,但如果我尝试访问“/”或“/entries”,它会不断将我重定向到登录页面。我试图在单独的 antMatchers() 和切换顺序中编写每个 uri,但到目前为止还没有运气。

@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) {
        };
      }
    };
  }

}
4

1 回答 1

0

显然我有一个带有注释@ControllerAdvice(basePackages = "myproject.web.controller") 的 UserHandler 类。这意味着它适用于提供的包的所有类。我的 addUser() 正在尝试将 User 添加为属性,如果没有用户,它会抛出同一类中定义的异常之一,从而导致重定向。因此,我在为 @ControllerAdvice 提供的包之外创建了单独的 GuestController 并处理其中的来宾的所有逻辑。这解决了我的问题。将不胜感激对我的方法的任何见解,如果它的好做法与否。

@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");
        }
    }
}    
于 2017-12-17T01:48:16.780 回答