在web.xml中配置如下
<!-- Shiro Filter -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在spring-shiro.xml中配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "
default-lazy-init="true">
<description>Shiro Configuration</description>
<!-- 项目自定义的Realm:继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的SystemAuthorizingRealm.java -->
<bean id="shiroDbRealm" class="com.cmcc.common.security.SystemAuthorizingRealm" />
<!--安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 设置自定义Realm -->
<property name="realm" ref="shiroDbRealm" />
<!-- 将缓存管理器,交给安全管理器 -->
<property name="cacheManager" ref="shiroEhcacheManager" />
<!-- 记住密码管理 -->
<property name="rememberMeManager" ref="rememberMeManager"/>
<!-- 配置session管理器 -->
<!-- <property name="sessionManager" ref="sessionManager" /> -->
</bean>
<!-- 记住密码Cookie -->
<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="rememberMe"/>
<property name="httpOnly" value="true"/>
<!-- 7天,采用spring el计算方便修改[细节决定成败]! -->
<property name="maxAge" value="#{7 * 24 * 60 * 60}"/>
</bean>
<!-- rememberMe管理器,cipherKey生成见{@code Base64Test.java} -->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('U3ByaW5nQmxhZGUAAAAAAA==')}"/>
<property name="cookie" ref="rememberMeCookie"/>
</bean>
<!-- Shiro Filter:Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 安全管理器:Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager" />
<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
<property name="loginUrl" value="/sys/views/login" />
<!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码为main.jsp了) -->
<!-- <property name="successUrl" value="/system/main" /> -->
<!-- 没有权限跳转的url: 用户访问未对其授权的资源时,所显示的连接 -->
<property name="unauthorizedUrl" value="/" />
<property name="filterChainDefinitions">
<value>
<!--
anon 不需要认证
authc 需要认证
user 验证通过或RememberMe登录的都可以
-->
/sys/views/login = anon
/sys/views/register = anon
/sys/api/login = anon
/sys/api/register = anon
/sys/api/register = anon
/sys/api/checkAccount = anon
/sys/** = user
</value>
</property>
</bean>
<!-- 用户授权信息Cache, 采用EhCache -->
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManager" ref="ehcache"/>
</bean>
<!-- 在方法中 注入 securityManager ,进行代理控制 -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
<property name="arguments" ref="securityManager"/>
</bean>
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<!-- 启用shrio授权注解拦截方式 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>
pom依赖:
<shiro.version>1.3.2</shiro.version>
<ehcache.version>3.1.3</ehcache.version>
<!-- 安全框架SECURITY:shiro begin -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 安全框架SECURITY:shiro end -->
<!-- ehcache:缓存框架 begin -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<!-- ehcache:缓存框架 end -->
<!-- spring 定时:Quartz 时间配置详解 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>${quartz.version}</version>
</dependency>
systemAuthorizingRealm
public class SystemAuthorizingRealm extends AuthorizingRealm {
@Autowired
private SysRoleService sysRoleService;
@Autowired
private SysFuncService sysFuncService;
@Autowired
private SysUserService sysUserService;
/**
* 认证回调函数, 登录时调用
* Shiro登录认证(原理:用户提交 用户名和密码 --- shiro 封装令牌 ---- realm 通过用户名将密码查询返回 ---- shiro 自动去比较查询出密码和用户输入密码是否一致---- 进行登陆控制
* 该方法的调用时机为LoginController.login()方法中执行Subject.login()时
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
// 获取基于用户名和密码的令牌:实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
SysUser systemUser = sysUserService.selectByLoginAccount(token.getUsername());
if (systemUser != null) {
// 校验用户状态
if (systemUser.getUserIsEnabled()) {
throw new DisabledAccountException();
}
SystemAuthorizingUser authorizingUser = new SystemAuthorizingUser(
systemUser.getUserId(), systemUser.getUserAccount(),
systemUser.getUserName());
// 认证缓存信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
authorizingUser, systemUser.getUserPassword(), getName());
return simpleAuthenticationInfo;
} else {
return null;
}
}
/**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
* 经测试:本例中该方法的调用时机为需授权资源被访问时
* 经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache
* 比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SystemAuthorizingUser authorizingUser = (SystemAuthorizingUser) principalCollection.getPrimaryPrincipal();
if(authorizingUser != null){
//权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//获得用户角色列表
List<SysRole> systemUserRoles = sysRoleService.selectSysRoleByUserId(authorizingUser.getUserId());
List<Integer> roleIdList = new ArrayList<Integer>();
for (SysRole systemRole : systemUserRoles) { // 添加用户角色信息
simpleAuthorizationInfo.addRole(systemRole.getRoleName());
roleIdList.add(systemRole.getRoleId());
}
//获得权限列表
List<SysFunc> sysFuncs = sysFuncService.selectFuncByRoleIds(roleIdList);
for(SysFunc sysFunc : sysFuncs){
if(sysFunc.getFuncUrl()!=null){
// 添加基于Permission的权限信息
simpleAuthorizationInfo.addStringPermission(sysFunc.getFuncUrl());
}
}
return simpleAuthorizationInfo;
}
System.out.println();
return null;
}
}
SystemAuthorizingUser
public class SystemAuthorizingUser implements Serializable{
private static final long serialVersionUID = 1L;
/** 用户ID */
private String userId;
/** 登录名 */
private String loginName;
/** 昵称 */
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public SystemAuthorizingUser(String accountId, String loginName,
String userName) {
super();
this.userId = accountId;
this.loginName = loginName;
this.userName = userName;
}
}