单点登录cas与权限管理框架shiro集成-普通web项目方式 .
<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#配置casRealmcasRealm = org.apache.shiro.cas.CasRealmcasRealm.defaultRoles = ROLE_USERcasRealm.casServerUrlPrefix = https://www.cas.com#客户端的回调地址设置,必须和下面的shiro-cas过滤器拦截的地址一致casRealm.casService = http://www.example.com/shiro-cas#如果要实现cas的remember me的功能,需要引入下面两个配置casSubjectFactory = org.apache.shiro.cas.CasSubjectFactorysecurityManager.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或怎样由你定。