pom文件加入html
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro-version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro-version}</version> </dependency>
web.xmljava
<!-- 配置Shiro過濾器,先讓Shiro過濾系統接收到的請求 --> <!-- 這裏filter-name必須對應applicationContext.xml中定義的<bean id="shiroFilter"/> --> <!-- 使用[/*]匹配全部請求,保證全部的可控請求都通過Shiro的過濾 --> <!-- 一般會將此filter-mapping放置到最前面(即其餘filter-mapping前面),以保證它是過濾器鏈中第一個起做用的 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <!-- 該值缺省爲false,表示生命週期由SpringApplicationContext管理,設置爲true則表示由servlet container管理 --> <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.xmlweb
<?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"> <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登陸的類爲自定義的UserRealm.java --> <bean id="userRealm" class="com.platform.shiro.UserRealm"/> <bean id="cluterShiroSessionDao" class="com.platform.shiro.CluterShiroSessionDao"/> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <!-- 設置session過時時間爲1小時(單位:毫秒),默認爲30分鐘 --> <property name="globalSessionTimeout" value="3600000"></property> <property name="sessionValidationSchedulerEnabled" value="true"></property> <property name="sessionIdUrlRewritingEnabled" value="false"></property> <property name="sessionDAO" ref="cluterShiroSessionDao"/> </bean> <!-- Shiro默認會使用Servlet容器的Session,可經過sessionMode屬性來指定使用Shiro原生Session --> <!-- 即<property name="sessionMode" value="native"/>,詳細說明見官方文檔 --> <!-- 這裏主要是設置自定義的單Realm應用,如有多個Realm,可以使用'realms'屬性代替 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="sessionManager" ref="sessionManager"></property> <property name="realm" ref="userRealm"/> </bean> <!-- Shiro主過濾器自己功能十分強大,其強大之處就在於它支持任何基於URL路徑表達式的、自定義的過濾器的執行 --> <!-- 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.html"頁面 --> <property name="loginUrl" value="/login.html"/> <!-- 登陸成功後要跳轉的鏈接 --> <property name="successUrl" value="/index.html"/> <!-- 用戶訪問未對其受權的資源時,所顯示的鏈接 --> <!-- 若想更明顯的測試此屬性能夠修改它的值,如unauthor.jsp,而後用[玄玉]登陸後訪問/admin/listUser.jsp就看見瀏覽器會顯示unauthor.jsp --> <property name="unauthorizedUrl" value="/"/> <!-- Shiro鏈接約束配置,即過濾鏈的定義 --> <!-- 此處可配合個人這篇文章來理解各個過濾連的做用http://blog.csdn.net/jadyer/article/details/12172839 --> <!-- 下面value值的第一個'/'表明的路徑是相對於HttpServletRequest.getContextPath()的值來的 --> <!-- anon:它對應的過濾器裏面是空的,什麼都沒作,這裏.do和.jsp後面的*表示參數,比方說login.jsp?main這種 --> <!-- authc:該過濾器下的頁面必須驗證後才能訪問,它是Shiro內置的一個攔截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter --> <property name="filterChainDefinitions"> <value> /statics/**=anon /api/**=anon /api/**=noSessionCreation /login.html=anon /sys/login=anon /captcha.jpg=anon /**=authc </value> </property> </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>
UserRealm.java
public class UserRealm extends AuthorizingRealm { @Autowired private SysUserDao sysUserDao; @Autowired private SysMenuDao sysMenuDao; /** * 受權(驗證權限時調用) */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal(); Long userId = user.getUserId(); List<String> permsList; //系統管理員,擁有最高權限 if (userId == Constant.SUPER_ADMIN) { List<SysMenuEntity> menuList = sysMenuDao.queryList(new HashMap<>()); permsList = new ArrayList<>(menuList.size()); for (SysMenuEntity menu : menuList) { permsList.add(menu.getPerms()); } } else { permsList = sysUserDao.queryAllPerms(userId); } //用戶權限列表 Set<String> permsSet = new HashSet<String>(); if (permsList != null && permsList.size() != 0) { for (String perms : permsList) { if (StringUtils.isBlank(perms)) { continue; } permsSet.addAll(Arrays.asList(perms.trim().split(","))); } } SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); info.setStringPermissions(permsSet); return info; } /** * 認證(登陸時調用) */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { String username = (String) token.getPrincipal(); String password = new String((char[]) token.getCredentials()); //查詢用戶信息 SysUserEntity user = sysUserDao.queryByUserName(username); //帳號不存在 if (user == null) { throw new UnknownAccountException("帳號或密碼不正確"); } //密碼錯誤 if (!password.equals(user.getPassword())) { throw new IncorrectCredentialsException("帳號或密碼不正確"); } //帳號鎖定 if (user.getStatus() == 0) { throw new LockedAccountException("帳號已被鎖定,請聯繫管理員"); } // 把當前用戶放入到session中 Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(true); session.setAttribute(Constant.CURRENT_USER, user); List<String> permsList; //系統管理員,擁有最高權限 if (Constant.SUPER_ADMIN == user.getUserId()) { List<SysMenuEntity> menuList = sysMenuDao.queryList(new HashMap<String, Object>()); permsList = new ArrayList<>(menuList.size()); for (SysMenuEntity menu : menuList) { permsList.add(menu.getPerms()); } } else { permsList = sysUserDao.queryAllPerms(user.getUserId()); } J2CacheUtils.put(Constant.PERMS_LIST + user.getUserId(), permsList); //若是身份認證驗證成功,返回一個AuthenticationInfo實現; SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName()); return info; } }
1、UserRealm父類AuthorizingRealm將獲取Subject相關信息分紅兩步:獲取身份驗證信息(doGetAuthenticationInfo)及受權信息(doGetAuthorizationInfo);spring
2、doGetAuthenticationInfo獲取身份驗證相關信息:首先根據傳入的用戶名獲取User信息;而後若是user爲空,那麼拋出沒找到賬號異常UnknownAccountException;若是user找到但鎖定了拋出鎖定異常LockedAccountException;最後生成AuthenticationInfo信息,交給間接父類AuthenticatingRealm使用CredentialsMatcher進行判斷密碼是否匹配,若是不匹配將拋出密碼錯誤異常IncorrectCredentialsException;另外若是密碼重試此處太多將拋出超出重試次數異常ExcessiveAttemptsException;在組裝SimpleAuthenticationInfo信息時,須要傳入:身份信息(用戶名)、憑據(密文密碼)、鹽(username+salt),CredentialsMatcher使用鹽加密傳入的明文密碼和此處的密文密碼進行匹配。apache
3、doGetAuthorizationInfo獲取受權信息:PrincipalCollection是一個身份集合,由於咱們如今就一個Realm,因此直接調用getPrimaryPrincipal獲得以前傳入的用戶名便可;而後根據用戶名調用UserService接口獲取角色及權限信息。api