您的位置:首页 > 编程语言 > Java开发

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

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

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

下载地址:http://download.csdn.net/detail/dulei294948/6303313

来看一下关于ip的允许访问配置:

[html] view
plaincopy

<span style="font-size:10px">< intercept-url pattern = "/user/index.html" access = "hasRole('ROLE_ADMIN') and hasIpAddress('127.0.0.1')"/></span>

这样就可以把允许访问的ip放到这里了。

[align=left]这里有一个有意思的东西,自定义过滤器,我们以后要重写很多的自定义过滤器,所以就还是以过滤ip为例子自己写一个吧:[/align]

[align=left]看一下过滤器:[/align]

[html] view
plaincopy

<span style="font-size:10px">public class IPRoleAuthenticationFilter extends OncePerRequestFilter {

// 目标角色

private String role;

// 过滤ip

private List<String> ips;

@Override

protected void doFilterInternal(HttpServletRequest request,

HttpServletResponse response, FilterChain chain)

throws ServletException, IOException {

final Authentication authentication = SecurityContextHolder

.getContext().getAuthentication();

if (authentication != null & role != null) {

Collection<? extends GrantedAuthority> authorities = authentication

.getAuthorities();

// 是否权限验证可以通过

boolean hasAuthority = false;

// 对权限进行对比

for (GrantedAuthority grantedAuthority : authorities) {

// 如果对比的权限相同 ,那么就可以说明有权限

if (grantedAuthority.getAuthority().equals(getRole())) {

hasAuthority = true;

break;

}

}

// 是否ip验证可以通过

boolean hasIp = false;

// 对ip进行对比

if (ips.size() > 0 && hasAuthority) {

// 获取ip

String requestsIp = request.getRemoteAddr();

for (String ip : ips) {

if (ip.equals(requestsIp)) {

hasIp = true;

break;

}

}

if(!hasIp){

throw new AccessDeniedException("ip被拦截,您的ip是: " + requestsIp);

}

}

}

chain.doFilter(request, response);

}

// setter和getter方法

....

}</span>

然后配置此bean:

[html] view
plaincopy

<span style="font-size:10px"><bean id="ipFilter" class="com.dsun.security.IPRoleAuthenticationFilter">

<property name="role" value="ROLE_ADMIN" />

<property name="ips">

<list>

<value>192.168.0.0</value>

</list>

</property>

</bean></span>

当然我们这里配置的已经是一个过滤器了。 那spring security本身就是过滤器链组成的
那么我们就可以把它放到链中了:

[html] view
plaincopy

<span style="font-size:10px"><http auto-config="true" use-expressions="true">

<!-- 不拦截登录页面 -->

<intercept-url pattern="/login.html" access="permitAll"/>

<!-- 配置一个登录标签 -->

<form-login username-parameter="username"

password-parameter="password" login-processing-url="/dologin"

default-target-url="/user/index.html" login-page="/login.html" />

<!-- 配置关于ip和角色的自定义拦截器 并且他们要在可以访问之前(对应过滤器:FILTER_SECURITY_INTERCEPTOR) -->

<custom-filter ref="ipFilter" before="FILTER_SECURITY_INTERCEPTOR"/>

</http></span>

然后我们就是测试一下了,他允许通过的ip是192.168.0.0 很明显 咱们不是。
我使用127.0.0.1进行登陆:



好的 那我们成功了。

下载地址:http://download.csdn.net/detail/dulei294948/6305711
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: