Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能:
- 认证 - 用户身份识别,常被称为用户“登录”;
- 授权 - 访问控制;
- 密码加密 - 保护或隐藏数据防止被偷窥;
- 会话管理 - 每用户相关的时间敏感的状态。
对于任何一个应用程序,Shiro都可以提供全面的安全管理服务。并且相对于其他安全框架,Shiro要简单的多。
二:springmvc整合shiro
1,在web.xml中加入如下配置
<!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->
<!-- 这里filter-name必须对应applicationContext.xml中定义的<bean id="shiroFilter"/> -->
<!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 -->
<!-- 通常会将此filter-mapping放置到最前面(即其他filter-mapping前面),以保证它是过滤器链中第一个起作用的 -->
<!-- targetFilterLifecycle值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->
- <!-- shiro start安全过滤器 -->
- <filter>
- <filter-name>shiroFilter</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- <async-supported>true</async-supported>
- <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>
- <dispatcher>REQUEST</dispatcher>
- </filter-mapping>
- <!-- shiro end -->
2,配置applicationContext.xml
<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
<!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->
- <!-- 缓存管理器 -->
- <bean id="cacheManager" class="com.www.admin.spring.SpringCacheManagerWrapper">
- <property name="cacheManager" ref="springCacheManager"/>
- </bean>
- <!-- 凭证匹配器 -->
- <bean id="credentialsMatcher" class="com.www.admin.user.credentials.RetryLimitHashedCredentialsMatcher">
- <constructor-arg ref="cacheManager"/>
- <property name="hashAlgorithmName" value="md5"/>
- <property name="hashIterations" value="2"/>
- <property name="storedCredentialsHexEncoded" value="true"/>
- </bean>
- <!-- Realm实现 -->
- <bean id="userRealm" class="com.www.admin.user.realm.UserRealm">
- <property name="credentialsMatcher" ref="credentialsMatcher"/>
- <property name="cachingEnabled" value="true"/>
- <property name="authenticationCachingEnabled" value="true"/>
- <property name="authenticationCacheName" value="authenticationCache"/>
- <property name="authorizationCachingEnabled" value="true"/>
- <property name="authorizationCacheName" value="authorizationCache"/>
- </bean>
- <!-- 会话ID生成器 -->
- <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>
- <!-- 会话Cookie模板 -->
- <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
- <constructor-arg value="sid"/>
- <property name="httpOnly" value="true"/>
- <property name="maxAge" value="-1"/>
- </bean>
- <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
- <constructor-arg value="rememberMe"/>
- <property name="httpOnly" value="true"/>
- <property name="maxAge" value="2592000"/><!-- 30天 -->
- </bean>
- <!-- rememberMe管理器 -->
- <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
- <!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)-->
- <property name="cipherKey"
- value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/>
- <property name="cookie" ref="rememberMeCookie"/>
- </bean>
- <!-- 会话DAO -->
- <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
- <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
- <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
- </bean>
- <!-- 会话验证调度器 -->
- <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
- <property name="sessionValidationInterval" value="1800000"/>
- <property name="sessionManager" ref="sessionManager"/>
- </bean>
- <!-- 会话管理器 -->
- <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
- <property name="globalSessionTimeout" value="1800000"/>
- <property name="deleteInvalidSessions" value="true"/>
- <property name="sessionValidationSchedulerEnabled" value="true"/>
- <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
- <property name="sessionDAO" ref="sessionDAO"/>
- <property name="sessionIdCookieEnabled" value="true"/>
- <property name="sessionIdCookie" ref="sessionIdCookie"/>
- </bean>
- <!-- 安全管理器 -->
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="userRealm"/>
- <property name="sessionManager" ref="sessionManager"/>
- <property name="cacheManager" ref="cacheManager"/>
- <property name="rememberMeManager" ref="rememberMeManager"/>
- </bean>
- <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
- <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
- <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
- <property name="arguments" ref="securityManager"/>
- </bean>
- <!-- 基于Form表单的身份验证过滤器 -->
- <bean id="loginFormAuthenticationFilter" class="com.www.admin.filter.shiro.LoginFormAuthenticationFilter"/>
- <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
- <property name="redirectUrl" value="/admin/login.do" />
- </bean>
- <bean id="sysUserFilter" class="com.www.admin.filter.shiro.SysUserFilter"/>
- <!-- Shiro的Web过滤器 -->
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
- <property name="securityManager" ref="securityManager"/>
- <property name="loginUrl" value="/admin/login.do"/>
- <property name="successUrl" value="/admin/index.do"/>
- <property name="filters">
- <util:map>
- <entry key="authc" value-ref="loginFormAuthenticationFilter"/>
- <entry key="sysUser" value-ref="sysUserFilter"/>
- <entry key="logout" value-ref="logoutFilter"/>
- </util:map>
- </property>
- <property name="filterChainDefinitions">
- <value>
- /**/*.js=anon
- /**/*.img=anon
- /**/*.css=anon
- /**/*.png=anon
- /**/*.gif=anon
- /**/*.jpg=anon
- /static/**=anon
- /admin/logout.do = logout
- /admin/login.do = authc
- /authenticated = authc
- /** = authc,user,sysUser
- </value>
- </property>
- </bean>
- <!-- Shiro生命周期处理器-->
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
securityManager:这个属性是必须的。
loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面。
successUrl:登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。
unauthorizedUrl:没有权限默认跳转的页面。
3, 自定义的Realm类
- import java.util.HashSet;
- import java.util.Set;
- import javax.annotation.Resource;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.AuthenticationInfo;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.LockedAccountException;
- import org.apache.shiro.authc.SimpleAuthenticationInfo;
- import org.apache.shiro.authc.UnknownAccountException;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.authz.SimpleAuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
- import org.apache.shiro.util.ByteSource;
- public class UserRealm extends AuthorizingRealm {
- @Resource
- private UserService userService;
- //这是授权方法
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- String username = (String)principals.getPrimaryPrincipal();
- SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
- Set<String> permissionsSet = null;
- Set<String> permissionsSetStr = new HashSet<String>();
- try {
- authorizationInfo.setRoles(userService.findRoles(username));
- permissionsSet = userService.findPermissions(username);
- for(String perStr:permissionsSet) {
- if(perStr.indexOf("*")<0) {
- permissionsSetStr.add(perStr);
- }
- }
- authorizationInfo.setStringPermissions(permissionsSetStr);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return authorizationInfo;
- }
- //这是认证方法
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- String username = (String)token.getPrincipal();
- UserVo userVo = null;
- SimpleAuthenticationInfo authenticationInfo = null;
- try {
- userVo = userService.findByUsername(username);
- if(userVo == null) {
- throw new UnknownAccountException();//没找到帐号
- }
- if(userVo.getLocked()==0) {
- throw new LockedAccountException(); //帐号锁定
- }
- //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
- authenticationInfo = new SimpleAuthenticationInfo(
- userVo.getUsername(), //用户名
- userVo.getPassword(), //密码
- ByteSource.Util.bytes(userVo.getCredentialsSalt()),//salt=username+salt
- getName() //realm name
- );
- } catch (Exception e) {
- e.printStackTrace();
- }
- return authenticationInfo;
- }
- @Override
- public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
- super.clearCachedAuthorizationInfo(principals);
- }
- @Override
- public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
- super.clearCachedAuthenticationInfo(principals);
- }
- @Override
- public void clearCache(PrincipalCollection principals) {
- super.clearCache(principals);
- }
- public void clearAllCachedAuthorizationInfo() {
- getAuthorizationCache().clear();
- }
- public void clearAllCachedAuthenticationInfo() {
- getAuthenticationCache().clear();
- }
- public void clearAllCache() {
- clearAllCachedAuthenticationInfo();
- clearAllCachedAuthorizationInfo();
- }
- }
4,controller层实例
@RequiresPermissions
例如: @RequiresPermissions({"file:read", "write:aFile.txt"} )
void someMethod();
要求subject中必须同时含有file:read和write:aFile.txt的权限才能执行方法someMethod()。否则抛出异常AuthorizationException。
- @RequiresPermissions("sys:user:add")//此处就是控制权限的注解
- @RequestMapping(value = "/add", method = RequestMethod.POST)
- public ModelAndView addUser(){
- ModelAndView mav = new ModelAndView("user/add");
- List<RoleVo> roleList = userService.add();
- mav.addObject("roleList", roleList);
- return mav;
- }
5,jsp处控制
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>//引入标签
- <div class="progess_btn" style=" text-align: left;margin-left: 120px;margin-top: -50px;">
- <shiro:hasPermission name="sys:user:add">
- <a class="btn_sure" href="javascript:void(0);" style=" margin-right: 58px; width: 100px;" οnclick="addSubmit()">添加</a>
- </shiro:hasPermission>
- <a class="btn_sure" href="javascript:history.back(-1);" style=" margin-right: 58px; width: 100px;">返回</a>
- </div>
6.
默认,添加或删除用户的角色 或资源 ,系统不需要重启,但是需要用户重新登录。
即用户的授权是首次登录后第一次访问需要权限页面时进行加载。
但是需要进行控制的权限资源,是在启动时就进行加载,如果要新增一个权限资源需要重启系统。
7.
Springsecurity 与apache shiro差别:
8.
控制精度:
注解方式控制权限只能是在方法上控制,无法控制类级别访问。
过滤器方式控制是根据访问的URL进行控制。允许使用*匹配URL,所以可以进行粗粒度,也可以进行细粒度控制。