shiro教程(4)-shiro與項目集成開發

shiro與項目集成開發

 

1.1 shirospring web項目整合

 

shirospringweb項目整合在“基於url攔截實現的工程”基礎上整合,基於url攔截實現的工程的技術架構springmvc+mybatis,整合注意兩點:

1shirospring整合

2、加入shiroweb應用的支持

 

1.1.1 取消原springmvc認證和授權攔截器

去掉springmvc.xml中配置的LoginInterceptorPermissionInterceptor攔截器。

 

1.1.2 加入shirojar

 

 

1.1.3 web.xml添加shiro Filter

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <!-- shiro過慮器,DelegatingFilterProx會從spring容器中找shiroFilter -->  

  2.   

  3. <filter>  

  4.   

  5. <filter-name>shiroFilter</filter-name>  

  6.   

  7. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  

  8.   

  9. <init-param>  

  10.   

  11. <param-name>targetFilterLifecycle</param-name>  

  12.   

  13. <param-value>true</param-value>  

  14.   

  15. </init-param>  

  16.   

  17. </filter>  

  18.   

  19. <filter-mapping>  

  20.   

  21. <filter-name>shiroFilter</filter-name>  

  22.   

  23. <url-pattern>/*</url-pattern>  

  24.   

  25. </filter-mapping>  

  26.   

  27.    



 

1.1.4 applicationContext-shiro.xml 

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <!-- Shiro 的Web過濾器 -->  

  2.   

  3. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  

  4.   

  5. <property name="securityManager" ref="securityManager" />  

  6.   

  7. <!-- 如果沒有認證將要跳轉的登陸地址,http可訪問的url,如果不在表單認證過慮器FormAuthenticationFilter中指定此地址就爲身份認證地址 -->  

  8.   

  9. <property name="loginUrl" value="/login.action" />  

  10.   

  11. <!-- 沒有權限跳轉的地址 -->  

  12.   

  13. <property name="unauthorizedUrl" value="/refuse.jsp" />  

  14.   

  15. <!-- shiro攔截器配置 -->  

  16.   

  17. <property name="filters">  

  18.   

  19. <map>  

  20.   

  21. <entry key="authc" value-ref="formAuthenticationFilter" />  

  22.   

  23. </map>  

  24.   

  25. </property>  

  26.   

  27. <property name="filterChainDefinitions">  

  28.   

  29. <value>  

  30.   

  31. <!-- 必須通過身份認證方可訪問,身份認 證的url必須和過慮器中指定的loginUrl一致 -->  

  32.   

  33. /loginsubmit.action = authc  

  34.   

  35. <!-- 退出攔截,請求logout.action執行退出操作 -->  

  36.   

  37. /logout.action = logout  

  38.   

  39. <!-- 無權訪問頁面 -->  

  40.   

  41. /refuse.jsp = anon  

  42.   

  43. <!-- roles[XX]表示有XX角色纔可訪問 -->  

  44.   

  45. /item/list.action = roles[item],authc  

  46.   

  47. /js/** anon  

  48.   

  49. /images/** anon  

  50.   

  51. /styles/** anon  

  52.   

  53. <!-- user表示身份認證通過或通過記住我認證通過的可以訪問 -->  

  54.   

  55. /** = user  

  56.   

  57. <!-- /**放在最下邊,如果一個url有多個過慮器則多個過慮器中間用逗號分隔,如:/** = user,roles[admin] -->  

  58.   

  59.    

  60.   

  61. </value>  

  62.   

  63. </property>  

  64.   

  65. </bean>  

  66.   

  67.    

  68.   

  69.    

  70.   

  71. <!-- 安全管理器 -->  

  72.   

  73. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  

  74.   

  75. <property name="realm" ref="userRealm" />  

  76.   

  77. </bean>  

  78.   

  79.    

  80.   

  81. <!-- 自定義 realm -->  

  82.   

  83. <bean id="userRealm" class="cn.itcast.ssm.realm.CustomRealm1">  

  84.   

  85. </bean>  

  86.   

  87. <!-- 基於Form表單的身份驗證過濾器,不配置將也會註冊此過慮器,表單中的用戶賬號、密碼及loginurl將採用默認值,建議配置 -->  

  88.   

  89. <bean id="formAuthenticationFilter"  

  90.   

  91. class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">  

  92.   

  93. <!-- 表單中賬號的input名稱 -->  

  94.   

  95. <property name="usernameParam" value="usercode" />  

  96.   

  97. <!-- 表單中密碼的input名稱 -->  

  98.   

  99. <property name="passwordParam" value="password" />  

  100.   

  101. <!-- <property name="rememberMeParam" value="rememberMe"/> -->  

  102.   

  103. <!-- loginurl:用戶登陸地址,此地址是可以http訪問的url地址 -->  

  104.   

  105. <property name="loginUrl" value="/loginsubmit.action" />  

  106.   

  107. </bean>  



 

securityManager:這個屬性是必須的。

loginUrl:沒有登錄認證的用戶請求將跳轉到此地址,不是必須的屬性,不輸入地址的話會自動尋找項目web項目的根目錄下的”/login.jsp”頁面。

unauthorizedUrl:沒有權限默認跳轉的頁面。

 

 

1.1.5 使用shiro註解授權

 

springmvc.xml中配置shiro註解支持,可在controller方法中使用shiro註解配置權限:

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <!-- 開啓aop,對類代理 -->  

  2.   

  3. <aop:config proxy-target-class="true"></aop:config>  

  4.   

  5. <!-- 開啓shiro註解支持 -->  

  6.   

  7. <bean  

  8.   

  9. class="  

  10.   

  11. org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  

  12.   

  13. <property name="securityManager" ref="securityManager" />  

  14.   

  15. </bean>  



 

修改Controller代碼,在方法上添加授權註解,如下:

 

[java] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. // 查詢商品列表  

  2.   

  3. @RequestMapping("/queryItem")  

  4.   

  5. @RequiresPermissions("item:query")  

  6.   

  7. public ModelAndView queryItem() throws Exception {  



 

上邊代碼@RequiresPermissions("item:query")表示必須擁有item:query”權限方可執行。

其它的方法參考示例添加註解

 

 

1.1.6 自定義realm

 

realm先不從數據庫查詢權限數據,當前需要先將shiro整合完成,在上邊章節定義的realm基礎上修改。

 

[java] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. public class CustomRealm1 extends AuthorizingRealm {  

  2.   

  3.    

  4.   

  5. @Autowired  

  6.   

  7. private SysService sysService;  

  8.   

  9.    

  10.   

  11. @Override  

  12.   

  13. public String getName() {  

  14.   

  15. return "customRealm";  

  16.   

  17. }  

  18.   

  19.    

  20.   

  21. // 支持什麼類型的token  

  22.   

  23. @Override  

  24.   

  25. public boolean supports(AuthenticationToken token) {  

  26.   

  27. return token instanceof UsernamePasswordToken;  

  28.   

  29. }  

  30.   

  31.    

  32.   

  33. // 認證  

  34.   

  35. @Override  

  36.   

  37. protected AuthenticationInfo doGetAuthenticationInfo(  

  38.   

  39. AuthenticationToken token) throws AuthenticationException {  

  40.   

  41.    

  42.   

  43. // 從token中 獲取用戶身份信息  

  44.   

  45. String username = (String) token.getPrincipal();  

  46.   

  47. // 拿username從數據庫中查詢  

  48.   

  49. // ....  

  50.   

  51. // 如果查詢不到則返回null  

  52.   

  53. if (!username.equals("zhang")) {// 這裏模擬查詢不到  

  54.   

  55. return null;  

  56.   

  57. }  

  58.   

  59.    

  60.   

  61. // 獲取從數據庫查詢出來的用戶密碼  

  62.   

  63. String password = "123";// 這裏使用靜態數據模擬。。  

  64.   

  65. // 根據用戶id從數據庫取出菜單  

  66.   

  67. //...先用靜態數據  

  68.   

  69. List<SysPermission> menus = new ArrayList<SysPermission>();;  

  70.   

  71. SysPermission sysPermission_1 = new SysPermission();  

  72.   

  73. sysPermission_1.setName("商品管理");  

  74.   

  75. sysPermission_1.setUrl("/item/queryItem.action");  

  76.   

  77. SysPermission sysPermission_2 = new SysPermission();  

  78.   

  79. sysPermission_2.setName("用戶管理");  

  80.   

  81. sysPermission_2.setUrl("/user/query.action");  

  82.   

  83. menus.add(sysPermission_1);  

  84.   

  85. menus.add(sysPermission_2);  

  86.   

  87. // 構建用戶身體份信息  

  88.   

  89. ActiveUser activeUser = new ActiveUser();  

  90.   

  91. activeUser.setUserid(username);  

  92.   

  93. activeUser.setUsername(username);  

  94.   

  95. activeUser.setUsercode(username);  

  96.   

  97. activeUser.setMenus(menus);  

  98.   

  99.    

  100.   

  101. // 返回認證信息由父類AuthenticatingRealm進行認證  

  102.   

  103. SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(  

  104.   

  105. activeUser, password, getName());  

  106.   

  107.    

  108.   

  109. return simpleAuthenticationInfo;  

  110.   

  111. }  

  112.   

  113.    

  114.   

  115. // 授權  

  116.   

  117. @Override  

  118.   

  119. protected AuthorizationInfo doGetAuthorizationInfo(  

  120.   

  121. PrincipalCollection principals) {  

  122.   

  123. // 獲取身份信息  

  124.   

  125. ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();  

  126.   

  127. //用戶id  

  128.   

  129. String userid = activeUser.getUserid();  

  130.   

  131. // 根據用戶id從數據庫中查詢權限數據  

  132.   

  133. // ....這裏使用靜態數據模擬  

  134.   

  135. List<String> permissions = new ArrayList<String>();  

  136.   

  137. permissions.add("item:query");  

  138.   

  139. permissions.add("item:update");  

  140.   

  141.    

  142.   

  143. // 將權限信息封閉爲AuthorizationInfo  

  144.   

  145.    

  146.   

  147. SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();  

  148.   

  149. for (String permission : permissions) {  

  150.   

  151. simpleAuthorizationInfo.addStringPermission(permission);  

  152.   

  153. }  

  154.   

  155.    

  156.   

  157. return simpleAuthorizationInfo;  

  158.   

  159. }  

  160.   

  161.    

  162.   

  163. }  

  164.   

  165.    



 

 

1.1.7 登錄

[java] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. //用戶登陸頁面  

  2.   

  3. @RequestMapping("/login")  

  4.   

  5. public String login()throws Exception{  

  6.   

  7. return "login";  

  8.   

  9. }  

  10.   

  11. // 用戶登陸提交  

  12.   

  13. @RequestMapping("/loginsubmit")  

  14.   

  15. public String loginsubmit(Model model, HttpServletRequest request)  

  16.   

  17. throws Exception {  

  18.   

  19.    

  20.   

  21. // shiro在認證過程中出現錯誤後將異常類路徑通過request返回  

  22.   

  23. String exceptionClassName = (String) request  

  24.   

  25. .getAttribute("shiroLoginFailure");  

  26.   

  27. if (UnknownAccountException.class.getName().equals(exceptionClassName)) {  

  28.   

  29. throw new CustomException("賬號不存在");  

  30.   

  31. else if (IncorrectCredentialsException.class.getName().equals(  

  32.   

  33. exceptionClassName)) {  

  34.   

  35. throw new CustomException("用戶名/密碼錯誤");  

  36.   

  37. else{  

  38.   

  39. throw new Exception();//最終在異常處理器生成未知錯誤  

  40.   

  41. }  

  42.   

  43. }  



 

1.1.8 首頁

 

由於session由shiro管理,需要修改首頁的controller方法:

 

[java] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. //系統首頁  

  2.   

  3. @RequestMapping("/first")  

  4.   

  5. public String first(Model model)throws Exception{  

  6.   

  7. //主體  

  8.   

  9. Subject subject = SecurityUtils.getSubject();  

  10.   

  11. //身份  

  12.   

  13. ActiveUser activeUser = (ActiveUser) subject.getPrincipal();  

  14.   

  15. model.addAttribute("activeUser", activeUser);  

  16.   

  17. return "/first";  

  18.   

  19. }  



 

 

1.1.9 退出

 

由於使用shiro的sessionManager,不用開發退出功能,使用shiro的logout攔截器即可。

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <!-- 退出攔截,請求logout.action執行退出操作 -->  

  2.   

  3. /logout.action = logout  



 

 

1.1.10 無權限refuse.jsp

 

當用戶無操作權限,shiro將跳轉到refuse.jsp頁面。

參考:applicationContext-shiro.xml

 

 

 

1.2 realm連接數據庫

 

1.2.1 添加憑證匹配器

添加憑證匹配器實現md5加密校驗。

修改applicationContext-shiro.xml

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <!-- 憑證匹配器 -->  

  2.   

  3. <bean id="credentialsMatcher"  

  4.   

  5. class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">  

  6.   

  7. <property name="hashAlgorithmName" value="md5" />  

  8.   

  9. <property name="hashIterations" value="1" />  

  10.   

  11. </bean>  

  12.   

  13.    

  14.   

  15. <!-- 自定義 realm -->  

  16.   

  17. <bean id="userRealm" class="cn.itcast.ssm.realm.CustomRealm1">  

  18.   

  19. <property name="credentialsMatcher" ref="credentialsMatcher" />  

  20.   

  21. </bean>  

  22.   

  23.    



 

1.2.2 realm代碼

修改realm代碼從數據庫中查詢用戶身份信息和權限信息,將sysService注入realm

 

 

[java] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. public class CustomRealm1 extends AuthorizingRealm {  

  2.   

  3.    

  4.   

  5. @Autowired  

  6.   

  7. private SysService sysService;  

  8.   

  9.    

  10.   

  11. @Override  

  12.   

  13. public String getName() {  

  14.   

  15. return "customRealm";  

  16.   

  17. }  

  18.   

  19.    

  20.   

  21. // 支持什麼類型的token  

  22.   

  23. @Override  

  24.   

  25. public boolean supports(AuthenticationToken token) {  

  26.   

  27. return token instanceof UsernamePasswordToken;  

  28.   

  29. }  

  30.   

  31.    

  32.   

  33. @Override  

  34.   

  35. protected AuthenticationInfo doGetAuthenticationInfo(  

  36.   

  37. AuthenticationToken token) throws AuthenticationException {  

  38.   

  39. // 從token中獲取用戶身份  

  40.   

  41. String usercode = (String) token.getPrincipal();  

  42.   

  43.    

  44.   

  45. SysUser sysUser = null;  

  46.   

  47. try {  

  48.   

  49. sysUser = sysService.findSysuserByUsercode(usercode);  

  50.   

  51. catch (Exception e) {  

  52.   

  53. // TODO Auto-generated catch block  

  54.   

  55. e.printStackTrace();  

  56.   

  57. }  

  58.   

  59.    

  60.   

  61. // 如果賬號不存在  

  62.   

  63. if (sysUser == null) {  

  64.   

  65. throw new UnknownAccountException("賬號找不到");  

  66.   

  67. }  

  68.   

  69.    

  70.   

  71. // 根據用戶id取出菜單  

  72.   

  73. List<SysPermission> menus = null;  

  74.   

  75. try {  

  76.   

  77. menus = sysService.findMenuList(sysUser.getId());  

  78.   

  79. catch (Exception e) {  

  80.   

  81. // TODO Auto-generated catch block  

  82.   

  83. e.printStackTrace();  

  84.   

  85. }  

  86.   

  87. // 用戶密碼  

  88.   

  89. String password = sysUser.getPassword();  

  90.   

  91. //鹽  

  92.   

  93. String salt = sysUser.getSalt();  

  94.   

  95. // 構建用戶身體份信息  

  96.   

  97. ActiveUser activeUser = new ActiveUser();  

  98.   

  99. activeUser.setUserid(sysUser.getId());  

  100.   

  101. activeUser.setUsername(sysUser.getUsername());  

  102.   

  103. activeUser.setUsercode(sysUser.getUsercode());  

  104.   

  105. activeUser.setMenus(menus);  

  106.   

  107. SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(  

  108.   

  109. activeUser, password, ByteSource.Util.bytes(salt),getName());  

  110.   

  111. return simpleAuthenticationInfo;  

  112.   

  113. }  

  114.   

  115.    

  116.   

  117. @Override  

  118.   

  119. protected AuthorizationInfo doGetAuthorizationInfo(  

  120.   

  121. PrincipalCollection principals) {  

  122.   

  123. //身份信息  

  124.   

  125. ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();  

  126.   

  127. //用戶id  

  128.   

  129. String userid = activeUser.getUserid();  

  130.   

  131. //獲取用戶權限  

  132.   

  133. List<SysPermission> permissions = null;  

  134.   

  135. try {  

  136.   

  137. permissions = sysService.findSysPermissionList(userid);  

  138.   

  139. catch (Exception e) {  

  140.   

  141. // TODO Auto-generated catch block  

  142.   

  143. e.printStackTrace();  

  144.   

  145. }  

  146.   

  147. //構建shiro授權信息  

  148.   

  149. SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();  

  150.   

  151. for(SysPermission sysPermission:permissions){  

  152.   

  153. simpleAuthorizationInfo.addStringPermission(sysPermission.getPercode());  

  154.   

  155. }  

  156.   

  157. return simpleAuthorizationInfo;  

  158.   

  159. }  

  160.   

  161.    

  162.   

  163. }  



 

 

 

 

 

1.3 緩存

shiro每個授權都會通過realm獲取權限信息,爲了提高訪問速度需要添加緩存,第一次從realm中讀取權限數據,之後不再讀取,這裏ShiroEhcache整合。

 

1.3.1 添加Ehcachejar

 

 

1.3.2 配置

applicationContext-shiro.xml中配置緩存管理器。

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <!-- 安全管理器 -->  

  2.   

  3. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  

  4.   

  5. <property name="realm" ref="userRealm" />  

  6.   

  7. <property name="sessionManager" ref="sessionManager" />  

  8.   

  9. <property name="cacheManager" ref="cacheManager"/>  

  10.   

  11. </bean>  

  12.   

  13.    

  14.   

  15. <!-- 緩存管理器 -->  

  16.   

  17.     <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">  

  18.   

  19.     </bean>  



 

1.4 session管理

applicationContext-shiro.xml中配置sessionManager

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <!-- 安全管理器 -->  

  2.   

  3. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  

  4.   

  5. <property name="realm" ref="userRealm" />  

  6.   

  7. <property name="sessionManager" ref="sessionManager" />  

  8.   

  9. </bean>  

  10.   

  11. <!-- 會話管理器 -->  

  12.   

  13.     <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">  

  14.   

  15.         <!-- session的失效時長,單位毫秒 -->  

  16.   

  17.         <property name="globalSessionTimeout" value="600000"/>  

  18.   

  19.         <!-- 刪除失效的session -->  

  20.   

  21.         <property name="deleteInvalidSessions" value="true"/>  

  22.   

  23.     </bean>  



 

 

 

1.5 驗證碼

 

1.5.1 自定義FormAuthenticationFilter

需要在驗證賬號和名稱之前校驗驗證碼。

 

[java] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. public class MyFormAuthenticationFilter extends FormAuthenticationFilter {  

  2.   

  3. protected boolean onAccessDenied(ServletRequest request,  

  4.   

  5. ServletResponse response, Object mappedValue) throws Exception {  

  6.   

  7.    

  8.   

  9. // 校驗驗證碼  

  10.   

  11. // 從session獲取正確的驗證碼  

  12.   

  13. HttpSession session = ((HttpServletRequest)request).getSession();  

  14.   

  15. //頁面輸入的驗證碼  

  16.   

  17. String randomcode = request.getParameter("randomcode");  

  18.   

  19. //從session中取出驗證碼  

  20.   

  21. String validateCode = (String) session.getAttribute("validateCode");  

  22.   

  23. if (!randomcode.equals(validateCode)) {  

  24.   

  25. // randomCodeError表示驗證碼錯誤  

  26.   

  27. request.setAttribute("shiroLoginFailure""randomCodeError");  

  28.   

  29. //拒絕訪問,不再校驗賬號和密碼  

  30.   

  31. return true;  

  32.   

  33. }  

  34.   

  35. return super.onAccessDenied(request, response, mappedValue);  

  36.   

  37. }  

  38.   

  39. }  



 

1.5.2 修改FormAuthenticationFilter配置

修改applicationContext-shiro.xml中對FormAuthenticationFilter的配置。

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <bean id="formAuthenticationFilter"  

  2.   

  3. class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">  

  4.   

  5.    

  6.   

  7. 改爲  

  8.   

  9. <bean id="formAuthenticationFilter"  

  10.   

  11. class="cn.itcast.ssm.shiro.MyFormAuthenticationFilter">  

  12.   

  13.    



 

1.5.3 登陸頁面

添加驗證碼:

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <TR>  

  2.   

  3. <TD>驗證碼:</TD>  

  4.   

  5. <TD><input id="randomcode" name="randomcode" size="8" /> <img  

  6.   

  7. id="randomcode_img" src="${baseurl}validatecode.jsp" alt=""  

  8.   

  9. width="56" height="20" align='absMiddle' /> <a  

  10.   

  11. href=javascript:randomcode_refresh()>刷新</a></TD>  

  12.   

  13. </TR>  



 

1.5.4 配置validatecode.jsp匿名訪問

 

修改applicationContext-shiro.xml

 

 

 

1.6 記住我

用戶登陸選擇“自動登陸”本次登陸成功會向cookie寫身份信息,下次登陸從cookie中取出身份信息實現自動登陸。

1.6.1 用戶身份實現java.io.Serializable接口

cookie記錄身份信息需要用戶身份信息對象實現序列化接口,如下:

 

 

 

 

 

1.6.2 配置

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <!-- 安全管理器 -->  

  2.   

  3. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  

  4.   

  5. <property name="realm" ref="userRealm" />  

  6.   

  7. <property name="sessionManager" ref="sessionManager" />  

  8.   

  9. <property name="cacheManager" ref="cacheManager"/>  

  10.   

  11. <!-- 記住我 -->  

  12.   

  13. <property name="rememberMeManager" ref="rememberMeManager"/>  

  14.   

  15. </bean>  

  16.   

  17.    

  18.   

  19. <!-- rememberMeManager管理器 -->  

  20.   

  21. <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">  

  22.   

  23. <property name="cookie" ref="rememberMeCookie" />  

  24.   

  25. </bean>  

  26.   

  27. <!-- 記住我cookie -->  

  28.   

  29. <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  

  30.   

  31. <constructor-arg value="rememberMe" />  

  32.   

  33. <!-- 記住我cookie生效時間30天 -->  

  34.   

  35. <property name="maxAge" value="2592000" />  

  36.   

  37. </bean>  

  38.   

  39.    


 

修改formAuthenticationFitler添加頁面中“記住我checkbox”的input名稱:

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <bean id="formAuthenticationFilter"  

  2.   

  3. class="cn.itcast.ssm.shiro.MyFormAuthenticationFilter">  

  4.   

  5. <!-- 表單中賬號的input名稱 -->  

  6.   

  7. <property name="usernameParam" value="usercode" />  

  8.   

  9. <!-- 表單中密碼的input名稱 -->  

  10.   

  11. <property name="passwordParam" value="password" />  

  12.   

  13. <property name="rememberMeParam" value="rememberMe"/>  

  14.   

  15. <!-- loginurl:用戶登陸地址,此地址是可以http訪問的url地址 -->  

  16.   

  17. <property name="loginUrl" value="/loginsubmit.action" />  

  18.   

  19. </bean>  



 

 

1.6.3 登陸頁面

login.jsp中添加“記住我”checkbox

 

[html] view plain copy print?在CODE上查看代碼片派生到我的代碼片

  1. <TR>  

  2.   

  3. <TD></TD>  

  4.   

  5. <TD>  

  6.   

  7. <input type="checkbox" name="rememberMe" />自動登陸  

  8.   

  9. </TD>  

  10.   

  11. </TR>  



 

 

附:

2.1 shiro過慮器

過濾器簡稱

對應的Java

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] ,其中methodpostgetdelete等。

port:例子/admins/user/**=port[8081],當請求的url的端口不是8081是跳轉到schemal://serverName:8081?queryString,其中schmal是協議httphttps等,serverName是你訪問的host,8081url配置裏port的端口,queryString

是你訪問的url裏的?後面的參數。

authcBasic:例如/admins/user/**=authcBasic沒有參數表示httpBasic認證

 

ssl:例子/admins/user/**=ssl沒有參數,表示安全的url請求,協議爲https

user:例如/admins/user/**=user沒有參數表示必須存在用戶,當登入操作時不做檢查

注:

anonauthcBasicauchcuser是認證過濾器,

permsrolessslrestport是授權過濾器

 

2.2 shirojsp標籤

 

Jsp頁面添加:

<%@ tagliburi="http://shiro.apache.org/tags" prefix="shiro" %>

 

標籤名稱

標籤條件(均是顯示標籤內容)

<shiro:authenticated>

登錄之後

<shiro:notAuthenticated>

不在登錄狀態時

<shiro:guest>

用戶在沒有RememberMe時

<shiro:user>

用戶在RememberMe時

<shiro:hasAnyRoles name="abc,123" >

在有abc或者123角色時

<shiro:hasRole name="abc">

擁有角色abc

<shiro:lacksRole name="abc">

沒有角色abc

<shiro:hasPermission name="abc">

擁有權限資源abc

<shiro:lacksPermission name="abc">

沒有abc權限資源

<shiro:principal>

顯示用戶身份名稱

 <shiro:principal property="username"/>     顯示用戶身份中的屬性值


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章