【问题标题】:Security Configuration doesn't let me use antMatchers() on some pages安全配置不允许我在某些页面上使用 antMatchers()
【发布时间】:2018-05-30 18:14:55
【问题描述】:

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

}

【问题讨论】:

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


    【解决方案1】:

    显然我有一个带有注释 @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");
            }
        }
    }    
    

    【讨论】:

      猜你喜欢
      • 2016-02-24
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      相关资源
      最近更新 更多