读书人

《Spring Security3》第六章第部分翻译

发布时间: 2012-12-18 12:43:41 作者: rapoo

《Spring Security3》第六章第一部分翻译(自定义安全过滤器)

?

第六章??高级配置和扩展

package com.packtpub.springsecurity.security;// imports omittedpublic class IPRoleAuthenticationFilter extends OncePerRequestFilter {}

private String targetRole;private List<String> allowedIPAddresses;

@Override public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { // before we allow the request to proceed, we'll first get the user's role // and see if it's an administrator final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && targetRole != null) { boolean shouldCheck = false; // look if the user is the target role for (GrantedAuthority authority : authentication.getAuthorities()) { if(authority.getAuthority().equals(targetRole)) { shouldCheck = true; break; } } // if we should check IP, then check if(shouldCheck && allowedIPAddresses.size() > 0) { boolean shouldAllow = false; for (String ipAddress : allowedIPAddresses) { if(req.getRemoteAddr().equals(ipAddress)) { shouldAllow = true; break; } } if(!shouldAllow) { // fail the request throw new AccessDeniedException(“Access has been denied for your IP address: “+req.getRemoteAddr()); } } } else { logger.warn(“The IPRoleAuthenticationFilter should be placedafter the user has been authenticated in the filter chain.”); } chain.doFilter(req, res); }// accessors (getters and setters) omitted}

?你可以看到,代码很简单明了,使用SecurityContext来获得Authentication关于当前请求的信息,就像我们在前面的章节练习中所作的那样。你可能会意识到没有很多特定与Spring Security的东西,除了获取用户角色(GrantedAuthority)的方法以及使用了AccessDeniedException来标示访问被拒绝。

<bean id="ipFilter" value="ROLE_ADMIN"/> <property name="allowedIPAddresses"> <list> <value>1.2.3.4</value> </list> </property></bean>?

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

??需要记住的是我们的过滤器依赖于SecurityContext 和Authentication对象,来进行辨别用户的GrantedAuthority。所以,我们要将这个过滤器的位置放在FilterSecurityInterceptor之前,它(你可能会回忆起第二章:SpringSecurity起步)负责确定用户是否有正确的权限访问系统。在过滤器的这个点上,用户的标示信息已经知道了,所以这是一个合适的位置以插入我们的过滤器。

???????? 现在你可以重启应用,因为这个新的IP过滤器,作为admin用户登录将会被限制。你可以对其进行随意的修改,以完全理解各部分是如何协同的。

【扩展IP过滤器。对于更复杂的需求,可以扩展这个过滤器以允许对角色和IP地址(子网匹配,IP段等)更复杂的匹配。但是,在java中并没有广泛使用的类库来进行这种类型的计算——考虑到安全环境中普遍存在的IP过滤,这一点颇令人吃惊。】

???????? 尝试增强IP过滤器的功能以添加我们尚未描述到的功能——动手是学习的最好方法,而将练习改造成现实世界中的例子是将抽象概念变得具体的很好方式。

?

?

1 楼 hekuilove 2011-12-05 不错 LZ辛苦了 2 楼 yz_gbz 2012-06-06 目前看过的最好的Spring Security3中文学习文档

读书人网 >编程

热点推荐