Spring Security hasIpAddress导致错误

时间:2016-10-06 13:20:43

标签: spring spring-security spring-boot

在我的配置中,我已经定义了:

@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)

使用以下代码:

    http.exceptionHandling()
            .authenticationEntryPoint(authEntryPoint)
            .and()
            .authorizeRequests()
            .antMatchers("/api/payment").permitAll()
            //.antMatchers("/api/payment").hasIpAddress("XXX.XXX.X.XX")
...

现在,当我将所有流量限制在' / api / payment'时,一切都会被执行。

但是,如果我尝试启用IP验证:

    http.exceptionHandling()
            .authenticationEntryPoint(authEntryPoint)
            .and()
            .authorizeRequests()
            //.antMatchers("/api/payment").permitAll()
            .antMatchers("/api/payment").hasIpAddress("XXX.XXX.X.XX")
...

从给定IP地址发送的请求收到以下响应:

{"errorMessage":"Not Found","errorId":"6ae34aa3-9195-42d6-8906-996906988ce0","errorDetails":null} 

我做错了什么?

修改

这是我调用的方法:

@RequestMapping(value = "/payment", method = POST)
public String saveOrder(@ModelAttribute PaymentDto paymentDto) {
    paymentService.savePayment(paymentDto);
    return "OK";
}

因为我总是发送请求数据(例如,帖子位于以下网址:api/payment?id=123&whatever

我已添加:

.antMatchers("/api/payment?**").access("hasIpAddress('XXX.XXX.X.XX')")

但这并没有奏效。

更新2

我已经改变了我的antMatcher的位置:

http.exceptionHandling()
        .authenticationEntryPoint(authEntryPoint)
        .and()
        .authorizeRequests()
        .antMatchers("/", "/app/**", "/assets/**", "/fonts/**", "/images/**").permitAll()
        .antMatchers("/authentication/login", "/login.html").anonymous()
        .antMatchers("/api/products/**").permitAll()
        .antMatchers("/api/cities/**").permitAll()
        .antMatchers("/api/order/**").permitAll()
        .antMatchers("/api/payment").hasIpAddress("XXX.XXX.X.XX")
        .anyRequest().authenticated()
        .and()
        .csrf().requireCsrfProtectionMatcher(new CsrfRequestMatcher())
        .and()
        .formLogin()
        .loginPage("/login.html")
        .loginProcessingUrl("/authentication/login")
        .successHandler(authSuccessHandler)
        .failureHandler(authFailureHandler)
        .and()
        .logout()
        .logoutUrl("/authentication/logout")
        .logoutSuccessHandler(logoutSuccessHandler)
        .deleteCookies(JSESSIONID_COOKIE, CSRF_COOKIE)
        .invalidateHttpSession(true)
        .permitAll();

当我尝试从给定的IP地址发帖时,现在只是将我重定向到登录页面

1 个答案:

答案 0 :(得分:0)

因此,当我结束时,我通过nginx的代理接收请求,该请求未传递请求者的原始IP地址。我不得不添加一些额外的nginx配置,现在,我可以像这样验证IP地址:

@RequestMapping(value = "/payment", method = POST)
public String saveOrder(PaymentDto paymentDto, HttpServletRequest request) {
    if (request.getHeader("X-Forwarded-For").equals("XXX.XXX.X.XX")){
      DO STUFF
    }
}