ip白名单+java,Spring Security - 白名单IP范围

A lot of resources and stackoverflow questions that I've viewed provide answers to using .xml files:

All that I would like to know is if it's possible to whitelist an IP address range using Spring Security without using XML configs?

Below is a simple method in my controller:

@RequestMapping(value = "/makeit", method = RequestMethod.GET)

@ResponseBody

//@PreAuthorize("hasIpAddress('192.168.0.0/16')")

public String requestData() {

return "youve made it";

}

I've created a separate class for the security config but it doesn't have much, I just created it for the EnableGlobalMethodSecurity annotation - so that I can use the @PreAuthorize annotation (from an answer here: @PreAuthorize annotation not working spring security).

@Configuration

@EnableWebSecurity

@EnableGlobalMethodSecurity(prePostEnabled = true)

public class SpringConfiguration extends WebSecurityConfigurerAdapter {

@Override

public void configure(HttpSecurity http) throws Exception {

http.csrf().disable();

http

.authorizeRequests()

.anyRequest().access("hasIpAddress('0.0.0.0/0')");

/*http

.authorizeRequests()

.anyRequest().hasIpAddress("0.0.0.0/0");*/

/*http

.authorizeRequests()

.antMatchers("/**").hasIpAddress("0.0.0.0/0");*/

/*http

.authorizeRequests()

.antMatchers("/**").access("hasIpAddress('0.0.0.0/0')");*/

/*http

.authorizeRequests()

.anyRequest().access("hasIpAddress('0.0.0.0/0')");*/

}

}

However, when I tried, it responded with (through POSTMAN):

{

"timestamp": 1486743507520,

"status": 401,

"error": "Unauthorized",

"message": "Full authentication is required to access this resource",

"path": "/makeit"

}

Additional facts:

My IP address is in this range. And I'm using Spring release 1.3.1 (Spring Security is 4.0.3, I believe).

解决方案

So with the help of @Dur, we were able to troubleshoot the issue. The issue isn't with Spring Boot (everything works fine above) but the issue is that when a user goes to the Spring App locally (localhost:8080), localhost uses an IPv6 address and the above code allows access for an IPv4 address.

You either need to change your SpringSecurityConfig file by changing the IPv4 address to a IPv6 (or whatever Tomcat defaults to) OR you can change how you access the app (by going to 127.0.0.1:8080).

Note - this is only for local testing. You'll need to test and obtain the IP addresses of the users/services that will be accessing your app.

In short, you can whitelist an IP range by using the above code without an AuthenticationManagerBuilder.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值