安全配置不允许我在某些页面上使用antMatchers()

时间:2017-12-16 23:31:44

标签: security spring-security spring-config websecurity httpconfiguration

安全配置不允许我在某些页面上使用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) {
        };
      }
    };
  }

}

1 个答案:

答案 0 :(得分:0)

显然我有一个UserHandler类,它有注释@ControllerAdvice(basePackages =“myproject.web.controller”)。这意味着它适用于提供的包的所有类。我的addUser()正在尝试添加User作为属性,如果没有用户,它会抛出在同一个类中定义的异常之一导致重定向。因此,我在为@ControllerAdvice提供的包之外创建了单独的GuestController,并为其中的guest虚拟机处理所有逻辑。这解决了我的问题。如果有好的做法,我会很感激我的方法。

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