准备maven shiro架包:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.3</version>
</dependency>
1.一:首先创建spring的配置文件,位置都在resource中(非maven的项目可以放到classpath或者是WEB-INF下面,只要保证最后编译之后能在classpath下即可),配置文件为spring-context.xml.
二:创建Apache Shiro的配置文件,名字是spring-context-shiro.xml,我们只需要和spring的配置文件放在同一级就可以了。
三:还有一个配置文件是springmvc的,配置文件是spring-mvc。前面两个文件都是以spring-context*开头是有原因的,因为这样我们就可以在web.xml中设置配置文件的时候,直接使用通配符扫描前两个但是又可以不扫描springmvc的配置文件
这是在web.xml里面配置:
<!-- 配置spring容器的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring-context-*.xml</param-value>
</context-param>
<!-- 对spring开始监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
除了spring的配置,还有一个配置是非常重要的:shiroFilter。对于初次配置shiro的同学经常遇到一个问题:问题大概讲的是shiroFilter找不到,但是我们明明在web.xml和spring-context-shiro配置文件里面配置了呀,怎么回事?这是因为这个shiroFilter名字两边需要一致!!!(是不是很坑,但是其实是可以配置的,只是一般人不知道,这个后面讲)
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
除了在web.xml中设置spring和spring-shiro配置文件位置之外,我们还需要在web.xml中设置spring-mvc的位置:
<!-- MVC Servlet
设置springmvc的Servlet
-->
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
在spring-context配置文件中,还有一个是需要配置-cacheManager,因为shiro的session是自己实现的,所以我们还需要一个缓存框架,所以在spring的配置文件一定要注意配置哦,用的是ehcache
<!-- 缓存 -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:${ehcache.file}"></property>
</bean>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.9</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.3</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"
default-lazy-init="true">
<description>Shiro Configuration</description>
<!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />
<!-- Shiro权限过滤过滤器定义 -->
<bean name="shiroFilterChainDefinitions" class="java.lang.String">
<constructor-arg>
<value>
/static/** = anon
/userfiles/** = anon
${adminPath}/cas = cas
${adminPath}/login = authc
${adminPath}/logout = logout
${adminPath}/** = user
/act/editor/** = user
/ReportServer/** = user
</value>
</constructor-arg>
</bean>
<!-- 安全认证过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" /><!--
<property name="loginUrl" value="${cas.server.url}?service=${cas.project.url}${adminPath}/cas" /> -->
<property name="loginUrl" value="${adminPath}/login" />
<property name="successUrl" value="${adminPath}?login" />
<property name="filters">
<map>
<entry key="cas" value-ref="casFilter"/>
<entry key="authc" value-ref="formAuthenticationFilter"/>
</map>
</property>
<property name="filterChainDefinitions">
<ref bean="shiroFilterChainDefinitions"/>
</property>
</bean>
<!-- CAS认证过滤器 -->
<bean id="casFilter" class="org.apache.shiro.cas.CasFilter">
<property name="failureUrl" value="${adminPath}/login"/>
</bean>
<!-- 定义Shiro安全管理配置 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="systemAuthorizingRealm" />
<property name="sessionManager" ref="sessionManager" />
<property name="cacheManager" ref="shiroCacheManager" />
</bean>
<!-- 自定义会话管理配置 -->
<bean id="sessionManager" class="com.thinkgem.jeesite.common.security.shiro.session.SessionManager">
<property name="sessionDAO" ref="sessionDAO"/>
<!-- 会话超时时间,单位:毫秒 -->
<property name="globalSessionTimeout" value="${session.sessionTimeout}"/>
<!-- 定时清理失效会话, 清理用户直接关闭浏览器造成的孤立会话 -->
<property name="sessionValidationInterval" value="${session.sessionTimeoutClean}"/>
<!-- <property name="sessionValidationSchedulerEnabled" value="false"/> -->
<property name="sessionValidationSchedulerEnabled" value="true"/>
<property name="sessionIdCookie" ref="sessionIdCookie"/>
<property name="sessionIdCookieEnabled" value="true"/>
</bean>
<!-- 指定本系统SESSIONID, 默认为: JSESSIONID 问题: 与SERVLET容器名冲突, 如JETTY, TOMCAT 等默认JSESSIONID,
当跳出SHIRO SERVLET时如ERROR-PAGE容器会为JSESSIONID重新分配值导致登录会话丢失! -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg name="name" value="jeesite.session.id"/>
</bean>
<!-- 自定义Session存储容器 -->
<!-- <bean id="sessionDAO" class="com.thinkgem.jeesite.common.security.shiro.session.JedisSessionDAO"> -->
<!-- <property name="sessionIdGenerator" ref="idGen" /> -->
<!-- <property name="sessionKeyPrefix" value="${redis.keyPrefix}_session_" /> -->
<!-- </bean> -->
<bean id="sessionDAO" class="com.thinkgem.jeesite.common.security.shiro.session.CacheSessionDAO">
<property name="sessionIdGenerator" ref="idGen" />
<property name="activeSessionsCacheName" value="activeSessionsCache" />
<property name="cacheManager" ref="shiroCacheManager" />
</bean>
<!-- 自定义系统缓存管理器-->
<!-- <bean id="shiroCacheManager" class="com.thinkgem.jeesite.common.security.shiro.cache.JedisCacheManager"> -->
<!-- <property name="cacheKeyPrefix" value="${redis.keyPrefix}_cache_" /> -->
<!-- </bean> -->
<bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="cacheManager"/>
</bean>
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- AOP式方法级权限检查 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>
这里从上往下进行解释:
1.shiroFilterChainDefinitions
可以看到类型是String,String内部的各个字符串是使用"\n\t"进行换行。这里的每一行代表了一个路由,而后面的anno,user等等,也就是相对应的Filter(这块我们是可以自己定义的,后面会讲,${adminPath} 是我在配置文件里面配置的路径而已,完全可以根据自己的路由进行设置。shiroFilterChainDefinitions最主要是在shiroFilter中作为一个参数注入。
===============权限过滤器及配置释义=======================
anon org.apache.shiro.web.filter.authc.AnonymousFilter
authc org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasic org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
perms org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
port org.apache.shiro.web.filter.authz.PortFilter
rest org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
roles org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
ssl org.apache.shiro.web.filter.authz.SslFilter
user org.apache.shiro.web.filter.authc.UserFilter
logout org.apache.shiro.web.filter.authc.LogoutFilter
anon:例子/admins/**=anon 没有参数,表示可以匿名使用。
authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数
roles:例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。
perms:例子/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。
rest:例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等。
port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString
是你访问的url里的?后面的参数。
authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证
ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查
2.重点来了:shiroFilter(ShiroFilterFactoryBean),这里要非常小心!!
这里的bean的名字一定要和web.xml里面的那个Filter名字相同,具体可以见下面的源码:
DelegatingFilterProxy.java:
@Override
protected void initFilterBean() throws ServletException {
synchronized (this.delegateMonitor) {
if (this.delegate == null) {
// If no target bean name specified, use filter name.
if (this.targetBeanName == null) {
this.targetBeanName = getFilterName();
}
// Fetch Spring root application context and initialize the delegate early,
// if possible. If the root application context will be started after this
// filter proxy, we'll have to resort to lazy initialization.
WebApplicationContext wac = findWebApplicationContext();
if (wac != null) {
this.delegate = initDelegate(wac);
}
}
}
}
还记得我们web.xml里面配置的那个Filter吗, 其实我们配置的Filter只不过是起到一个代理的作用,那么它代理谁呢? 它也不能知道,它所能做的就是根据targetBeanName去容器中获取bean(这个bean是实现了Filter接口的),其中的targetBeanName就是bean的名称,如果没有设置的话,那么就默认使用的Filter名称。所以说前面说过的必须相同是不正确的,你只需要在Filter中设置targetBeanName和spring-context-shiro配置文件中ShiroFilterFactoryBean的bean名称一样即可。
除了上面需要注意的几个点之外,ShiroFilterFactoryBean还有一些属性:unauthorizedUrl,系统未认证时跳转的页面,loginUrl登录页面,successUrl登录成功的页面,filter属性就是和前面的shiroFilterChainDefinitions对应的。同时支持自定义,并且配置路由:像<entry key="outdate" value-ref="sessionOutDateFilter"/>这样的。最底层是过滤器,下面是我实现的一个filter:
package com.yonyou.kms.common.security.shiro.session;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.servlet.AdviceFilter;
import com.yonyou.kms.modules.sys.security.SystemAuthorizingRealm.Principal;
import com.yonyou.kms.modules.sys.utils.UserUtils;
/**
*
* 自定义filter
* @author Hotusm
*
*/
public class SessionOutDateFilter extends AdviceFilter{
private String redirectUrl="http://url/portal";//session 失效之后需要跳转的页面
private String platformUrl="http://url/kms/a/login";
//排除这个链接 其他的链接都会进行拦截
private String loginUrl="/kms/a/login";
private String frontUrl="cms/f";
private String uploadUrl="cms/article/plupload";
private String appUrl="a/app";
protected boolean preHandle(ServletRequest request, ServletResponse response){
Principal principal = UserUtils.getPrincipal();
HttpServletRequest req=(HttpServletRequest) request;
String uri=req.getRequestURI();
if(checkUrl(uri, loginUrl,frontUrl,uploadUrl,appUrl)|(principal!=null&&!principal.isMobileLogin())){
return true;
}
try {
issueRedirect(request,response,redirectUrl);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
protected void issueRedirect(ServletRequest request, ServletResponse response, String redirectUrl)
throws Exception
{
String url="<a href="+redirectUrl+" target=\"_blank\" οnclick=\"custom_close()\">重新登录<a/> ";
String platform="<a href="+platformUrl+" target=\"_blank\" οnclick=\"custom_close()\">直接登录<a/> ";
HttpServletResponse resp=(HttpServletResponse) response;
HttpServletRequest req=(HttpServletRequest) request;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=resp.getWriter();
out.print("<script language='javascript'>");
out.print("function custom_close(){" +
"self.opener=null;" +
"self.close();}");
out.print("</script>");
out.print("没有权限或者验证信息过期,请点击"+url+"登录portal<br/>");
out.print("直接登录"+platform);
}
public String getRedirectUrl() {
return redirectUrl;
}
public void setRedirectUrl(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
/**
* 排除一些url不进行拦截
* @param targetUrl
* @param urls
* @return
*/
private boolean checkUrl(String targetUrl,String ...urls){
for(int i=0;i<urls.length;i++){
if(targetUrl.contains(urls[i])){
return true;
}
}
return false;
}
}
这个和springmvc的拦截器是相同的用法,返回true则表示验证通过(后面的逻辑继续执行),返回false就表示验证不通过。
最后在shiroFilter的filters进行配置我们自定义的bean:
<property name="filters">
<map>
<entry key="outdate" value-ref="sessionOutDateFilter"/>
</map>
</property>
这个sessionOutDateFilter我们需要注入(这里省略)。最后我们就将可以将这些东西加到shiroFilterChainDefinitions中去:
<bean name="shiroFilterChainDefinitions" class="java.lang.String">
<constructor-arg>
<value>
......
${adminPath}/** = outdate
.....
</value>
</constructor-arg>
</bean>
这样我们自己定义的叫做outdata的路由会拦截${adminPath}下的所以路径,并且进行验证。
3.
SecurityManager
它和我们前面讲的ShiroFilterFactoryBean的关系形象的将就是ShiroFilterFactoryBean是一个路由规则配置仓库和代理类,其实真正的逻辑都是在SecurityManager中进行的,下面来进行详讲SecurityManager的依赖类。
一:realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源,下面是jeesite重写的realm:
//@DependsOn({"userDao","roleDao","menuDao"})
//@Service Spring自动注入。
public class SystemAuthorizingRealm extends AuthorizingRealm {
private Logger logger = LoggerFactory.getLogger(getClass());
private SystemService systemService;
/**
* 认证回调函数, 登录时调用
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
……
}
/**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
……
}
参考资料:http://www.cnblogs.com/zr520/p/5009790.html
任何请求首先会再web拦截,跳转到
1.FormAuthenticationFilter拦截器,创建一个UsernamePasswordToken 令牌。
2.如果未登录跳转到登录界面,如果首次登陆,会进行SystemAuthorizingRealm,认证和授权。