?????? 由于项目需要做权限管理的功能,最先想到的是spring security,它是个功能强大的安全管理框架,不过它的复杂性和学习曲线之曲折让人生畏,转而寻求其它解决方案,知道另外一个项目组的人使用shiro做权限管理后就了解了下这个框架,发现比spring security简洁多了,于是就打算使用这个框架,首先嘛,当然是要和现在的系统进行集成,现在系统采用cas来做登录验证,所以先把cas和shiro进行集成。查看shiro官网,发现有个cas模块,下载试用,下面是集成方法,假设你已经搭建好cas服务器(具体搭建细节自己google百度下)
我是用maven管理项目的,先引入shiro的jar包
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-cas</artifactId> <version>1.2.0</version> </dependency>
?
配置web.xml,添加shiro过滤器
<filter> <filter-name>shiroFilter</filter-name> <filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class> <init-param> <param-name>configPath</param-name> <param-value>classpath:META-INF/shiro/shiro.ini</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
?
其中shiro.ini为shiro配置文件,可以根据具体情况指定其路径。
[main] casFilter = org.apache.shiro.cas.CasFilter #配置验证错误时的失败页面 casFilter.failureUrl = /error.jsp #配置casRealm casRealm = org.apache.shiro.cas.CasRealm casRealm.defaultRoles = ROLE_USER casRealm.casServerUrlPrefix = https://www.cas.com #客户端的回调地址设置,必须和下面的shiro-cas过滤器拦截的地址一致 casRealm.casService = http://www.example.com/shiro-cas #如果要实现cas的remember me的功能,需要引入下面两个配置 casSubjectFactory = org.apache.shiro.cas.CasSubjectFactory securityManager.subjectFactory = $casSubjectFactory #设定角色的登录链接,这里为cas登录页面的链接可配置回调地址 roles.loginUrl = https://www.<SPAN style="COLOR: #000000">cas</SPAN>.com/login?service=http://shop.youboy.com:8080/cshop/shiro-cas [urls] #设定shiro-cas过滤器拦截的地址 /shiro-cas = casFilter /admin/** = roles[ROLE_USER] /** = anon
?
这里需要注意的是casRealm.casService设置的回调地址必须和下面casFilter的地址保持一致,否则无法验证成功。更多有关shiro的配置可以参考官方文档
这样如果访问www.example.com/admin/index.html时,如果没登录就会跳到cas去登录,登录成功后跳转回当前页面。
如果想获得cas返回的更多用户的信息,比如:用户名,用户id,用户邮箱等,可以添加一个过滤器,这个过滤器必须在shiro的过滤器后面,否则获取不到相关的信息。过滤器代码如下:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { PrincipalCollection principalCollection = SecurityUtils.getSubject() .getPrincipals(); if (principalCollection != null) { List principals = principalCollection.asList(); // 这里获取到的list有两个元素, //一个是cas返回来的用户名,举例是aaa, //一个是cas返回的更多属性的map对象,举例是{uid:aaa,username:aaa,email:aaa} //通过principals.get(1)来获得属性集合的map对象 Map<String,String> attributes = (Map<String,String>) principals.get(1); if (principals != null) { String email = attributes.get("email"); String username = attributes.get("username"); String uid = attributes.get("uid"); //对获取到的信息进行再处理 } } chain.doFilter(request, response); }
?
获取到信息就可以把它设置到session或怎样由你定。