spring 集成shiro 之 自定义过滤器shiroFilter
转:http://blog.csdn.net/shuishouhcd/article/details/9077379
最近一段时间,我一直在将shiro集成到我的一个项目中,用作认证和授权处理。
shiro对我来说是个新东西,以下是我学习过的内容:
http://shiro.apache.org/authorization.html
http://www.cnblogs.com/skyme/archive/2011/09/11/2173760.html 系列
http://www.infoq.com/cn/articles/apache-shiro
http://www.ibm.com/developerworks/cn/java/j-lo-shiro/
如果我那个地方没说明白,可以看这些。
集成shiro,需要配置web.xml文件,spring的applicationContext.xml配置文件(当然,独立配置一个shiro.xml文件交给spring容器处理也是可以的)。
web.xml文件中的配置:
public class MonitorRealm extends AuthorizingRealm{
@Autowired
private DAO dao;<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px; background-color: rgb(248, 248, 248);">//这里自己需要什么就注入什么。 </span>
public MonitorRealm() {
super();
}
/**
* 授权操作,决定那些角色可以使用那些资源
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
//<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px; background-color: rgb(248, 248, 248);">TODO </span><span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px; background-color: rgb(248, 248, 248);">访问授权信息</span>
return info;
}
/**
* 认证操作,判断一个请求是否被允许进入系统
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
//<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px;">TODO 用户认证信息 </span>
return info;
}
} public class PermissionsAuthorizationFilter extends AuthorizationFilter {
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
<span style="font-family: Consolas, 'Courier New', Courier, mono, serif; font-size: 11.818181991577148px; line-height: 17.27272605895996px; background-color: rgb(248, 248, 248);"> //自定义过滤器逻辑</span>
return true;
}
}
配置自定义过滤器的关键是配置文件中 的这几句
- <property name="filters">
- <map>
- <entry key="sperm" value-ref="simplePermFilter"/>
- </map>
- </property>
- <property name="filterChainDefinitions">
- <value>
- ...
- /test/objT.do ="sperm"
- </value>
- </property>
颜色相同的地方一定要一样,表示用某个过滤器过滤指定路径。因为这个我费了好长时间。
org.apache.shiro.spring.web.ShiroFilterFactoryBean 的作用是通过spring来初始化shiro的工作环境。如果一个请求进来,shiro的过滤器会先工作,过滤器会调用realm中的授权或认证的方法来获取授权或认证信息。