1、Maven添加Shiro所需的jar包
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiroversion}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${shiroversion}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiroversion}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiroversion}</version> </dependency> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
ps:老夫用的1.4.0版本, ${shiroversion} 用 1.4.0替代就好
2、添加 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" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"> <!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登錄的類為自定義的UserRealm.java --> <bean id="userRealm" class="com.***.shiro.UserRealm"/> <!-- 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="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.jsp"/> <!-- 登錄成功后要跳轉的連接 --> <property name="successUrl" value="/views/admin/common/master.jsp"/> <!-- 用戶訪問未對其授權的資源時,所顯示的連接 --> <!-- 若想更明顯的測試此屬性可以修改它的值,如unauthor.jsp,然后用[玄玉]登錄后訪問/admin/listUser.jsp就看見瀏覽器會顯示unauthor.jsp --> <!-- <property name="unauthorizedUrl" value="/no_permissions.jsp" /> --> <!-- 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> <!-- anon表示此地址不需要任何權限即可訪問 --> /static/** = anon /resources/** = anon /admin/login.do = anon /** = authc </value> </property> </bean> <!-- Shiro生命周期處理器 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- Shiro的注解配置放在spring-mvc中 --> </beans>
3、web.xml里面添加 spring-shiro.xml 的引入
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-base.xml,classpath:spring-mybatis.xml,classpath:spring-druid.xml,classpath:spring-shiro.xml </param-value> </context-param>
4、在 spring-mvc.xml 里開啟 shiro 的的注解
<!-- 開啟shiro注解--> <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>
配置文件就到此結束了,下面自己創建一個 UserRealm;
5、創建一個繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證用戶登錄的類為自定義的UserRealm.java
package com.***.shiro; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import com.**.entity.Admin; import com.**.entity.Permissions; import com.**.entity.Role; import com.**.entity.form.AdminForm; import com.**.entity.form.PermissionsForm; import com.**.entity.form.RoleForm; import com.**.service.IAdminService; import com.**.service.IPermissionsService; import com.**.service.IRoleService; public class UserRealm extends AuthorizingRealm { @Resource private IAdminService adminService; @Resource private IRoleService roleService; @Resource private IPermissionsService permissionsService; /** * 為當前登錄的Subject授予角色和權限 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // 獲取當前登錄的用戶名,等價於(String)principals.fromRealm(this.getName()).iterator().next() String username = (String) super.getAvailablePrincipal(principals); List<String> roleList = new ArrayList<String>(); List<String> permissionList = new ArrayList<String>(); // 從數據庫中獲取當前登錄用戶的詳細信息 AdminForm form = new AdminForm(); form.setUserName(username); Admin admin = adminService.getList(form).get(0); if (null != admin) { // 實體類User中包含有用戶角色的實體類信息 if (null != admin.getRoleId()) { // 獲取當前登錄用戶的角色 RoleForm roleForm = new RoleForm(); roleForm.setId(admin.getRoleId()); Role role = roleService.getList(roleForm).get(0); roleList.add(role.getName()); // 實體類Role中包含有角色權限的實體類信息 if (null != role.getPermissionsList()) { String permissionsList[] = role.getPermissionsList().split(","); // 獲取權限 for (int i = 0; i < permissionsList.length; i++) { PermissionsForm permissionsForm = new PermissionsForm(); permissionsForm.setId(Integer.parseInt(permissionsList[i])); Permissions permi = permissionsService.getList(permissionsForm).get(0); permissionList.add(permi.getCode()); } } } } else { throw new AuthorizationException(); } // 為當前用戶設置角色和權限 SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); simpleAuthorInfo.addRoles(roleList); simpleAuthorInfo.addStringPermissions(permissionList); return simpleAuthorInfo; } /** * 驗證當前登錄的Subject * * @see 經測試:本例中該方法的調用時機為LoginController.login()方法中執行Subject.login()時 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { // 獲取基於用戶名和密碼的令牌 // 實際上這個authcToken是從AdminController里面currentUser.login(token)傳過來的 UsernamePasswordToken token = (UsernamePasswordToken) authcToken; System.err.println( "驗證當前Subject時獲取到token為" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); AdminForm form = new AdminForm(); form.setUserName(token.getUsername()); Admin admin = adminService.getList(form).get(0); if (null != admin) { AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(admin.getUserName(), admin.getPassword(), admin.getId().toString()); this.setSession("currentUser", admin); return authcInfo; } else { return null; } } /** * 將一些數據放到ShiroSession中,以便於其它地方使用 * * @see 比如Controller,使用時直接用HttpSession.getAttribute(key)就可以取到 */ private void setSession(Object key, Object value) { Subject currentUser = SecurityUtils.getSubject(); if (null != currentUser) { Session session = currentUser.getSession(); System.out.println("Session默認超時時間為[" + session.getTimeout() + "]毫秒"); if (null != session) { session.setAttribute(key, value); } } } }
數據庫、實體、Dao配置省略。。。
附:表片段
6、在登錄方法中,登錄成功后將用戶添加到 shiro 的 Subject 中
UsernamePasswordToken token = new UsernamePasswordToken(admin.getUserName(), admin.getPassword()); Subject currentUser = SecurityUtils.getSubject(); currentUser.login(token);
7、在需要訪問權限的方法上添加 @RequiresPermissions() 注解
@RequestMapping("/permissionsList") @RequiresPermissions("permissionsList") public ModelAndView permissionsList(HttpServletRequest request) { ModelAndView mv = new ModelAndView(); PermissionsForm form = new PermissionsForm(); if (!StringUtils.isEmpty(request.getParameter("id"))) form.setId(Integer.parseInt(request.getParameter("id"))); if (!StringUtils.isEmpty(request.getParameter("name"))) form.setName(request.getParameter("name")); if (!StringUtils.isEmpty(request.getParameter("group"))) form.setGroup(request.getParameter("group")); List<Permissions> menuList = permissionsService.getList(form); mv.addObject("menuList", menuList); mv.addObject("id", request.getParameter("id")); mv.addObject("name", request.getParameter("name")); mv.addObject("group", request.getParameter("group")); mv.setViewName("views/admin/system_manage/permissions_list"); return mv; }
@RequiresPermissions("permissionsList") : 表示擁有 permissionsList 權限方可訪問該方法
附加:
實際使用訪問到不具有權限的地址時會報錯 org.apache.shiro.authz.UnauthorizedException 或者 org.apache.shiro.authz.UnauthenticatedException
此時需要在 spring-mvc.xml 里添加 錯誤跳轉未授權頁面
<!-- shiro異常跳轉 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="org.apache.shiro.authz.UnauthorizedException">no_permissions</prop> <prop key="org.apache.shiro.authz.UnauthenticatedException">no_permissions</prop> </props> </property> </bean>
no_permissions 為 ModelAndView。
完結。。。