spring security3.x学习(22)_关于ip的过滤器

看到电子书的第六章了,我粗略的看了一下,发现第六章的知识很乱,需要前期的基础知识要很好才可以看懂,
所以从这次开始,我自己开始动手写一些例子进行练习(其实基础知识基本上已经学完了,剩下的都是高级配置了)

我先写好了一个模板。以后我们学习就可以根据这个模板进行修改了。(spring mvc + spring security)


来看一下关于ip的允许访问配置:
< intercept-url pattern = "/user/index.html" access = "hasRole('ROLE_ADMIN') and hasIpAddress('
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security提供了IP地址白名单的功能,可以限制只有特定IP地址的用户才能访问应用程序。以下是实现IP白名单的步骤: 1. 创建一个自定义过滤器,继承自AbstractAuthenticationProcessingFilter。 2. 在该过滤器中实现处理请求的代码,并在其中获取请求的IP地址。 3. 将IP地址与白名单中的IP地址进行比较,如果匹配,则允许访问;否则,拒绝访问。 4. 将自定义过滤器添加到Spring Security过滤器链中。 以下是一个示例代码,演示如何实现IP地址白名单: ``` public class IPWhiteListFilter extends AbstractAuthenticationProcessingFilter { private List<String> whitelist; public IPWhiteListFilter(List<String> whitelist) { super("/**"); this.whitelist = whitelist; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String ipAddress = request.getRemoteAddr(); if (whitelist.contains(ipAddress)) { return new UsernamePasswordAuthenticationToken(ipAddress, null, Collections.emptyList()); } else { throw new AuthenticationServiceException("IP address is not white-listed"); } } } ``` 在上述代码中,IPWhiteListFilter类继承自AbstractAuthenticationProcessingFilter,实现了请求处理的方法attemptAuthentication。该方法中,首先获取请求的IP地址,然后与白名单中的IP地址进行比较,如果匹配,则返回一个UsernamePasswordAuthenticationToken对象,表示认证通过;否则,抛出一个AuthenticationServiceException异常,表示认证失败。 最后,将该过滤器添加到Spring Security过滤器链中: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { List<String> whitelist = Arrays.asList("127.0.0.1", "localhost"); IPWhiteListFilter ipWhiteListFilter = new IPWhiteListFilter(whitelist); http.addFilterBefore(ipWhiteListFilter, UsernamePasswordAuthenticationFilter.class); } } ``` 在上述代码中,SecurityConfig类继承自WebSecurityConfigurerAdapter,重写了configure方法,将IPWhiteListFilter过滤器添加到了过滤器链中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值