spring xml 配置文件向Bean 设置List值

本文介绍了一种IP角色认证过滤器的设计与实现,该过滤器能够根据用户的权限和IP地址来决定是否允许请求通过。主要功能包括:检查用户是否具备特定角色,并验证其IP地址是否在允许列表中。

package com.zendaimoney.uc.web.interceptor;

import java.io.IOException;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

public class IPRoleAuthenticationFilter extends OncePerRequestFilter {
private String targetRole;
private List<String> allowedIPAddresses;

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 placed after the user has been authenticated in the filter chain.");
}
chain.doFilter(req, res);
}
// accessors (getters and setters) omitted
}

 

 

 

 

 

 

 

 

 

-------------------------------------------------------------------

  1. <bean id="ipFilter" class="com.packtpub.springsecurity .security.IPRoleAuthenticationFilter">  
  2.   <property name="targetRole" value="ROLE_ADMIN"/>  
  3.   <property name="allowedIPAddresses">  
  4.     <list>  
  5.       <value>1.2.3.4</value>  
  6.     </list>  
  7.   </property>  
  8. </bean>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值