Spring集成Shiro權限管理

本文介紹在Java Web項目中Spring和Shiro集成,實現權限控制管理,主要包括以下步驟:

新建Maven項目

1.新建Maven項目,增加shiro pom依賴:
pom.xml

<properties>
    <shiro.version>1.2.3</shiro.version>
</properties>
<!-- shiro -->
<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>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>${shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>${shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-quartz</artifactId>
    <version>${shiro.version}</version>
</dependency>

在Spring中集成Shiro

1.Shiro過濾器配置
web.xml

<!-- shiro 安全過濾器 -->
<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>
</filter-mapping>

2.Spring集成Shiro配置
ApplicationContext-Shiro.xml

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
   <property name="securityManager" ref="securityManager"/>
   <property name="loginUrl" value="/page/login"/>
   <property name="unauthorizedUrl" value="/page/401"/>
   <property name="filterChainDefinitions">
       <value>
           <!-- 靜態資源允許訪問 -->
           /app/** = anon
           /assets/** = anon
           <!-- 登錄頁允許訪問 -->
           /user/login = anon
           <!-- 其他資源需要認證 -->
           /** = authc
       </value>
   </property>
</bean>
<!-- 緩存管理器 使用Ehcache實現 -->
 <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
     <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
 </bean>

 <!-- 會話DAO -->
 <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/>

 <!-- 會話管理器 -->
 <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
     <property name="sessionDAO" ref="sessionDAO"/>
 </bean>

 <!-- 安全管理器 -->
 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
     <property name="realms">
         <list>
             <ref bean="securityRealm"/>
         </list>
     </property>
     <!-- cacheManager,集合spring緩存工廠 -->
     <!-- <property name="cacheManager" ref="shiroEhcacheManager" /> -->
     <!-- <property name="sessionManager" ref="sessionManager" /> -->
 </bean>

<!-- Shiro生命週期處理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- Shiro Spring AOP權限註解 , 需要設置<aop:config proxy-target-class="true"> -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">  
  <property name="securityManager" ref="securityManager"/>  
</bean>

3.配置Shiro Ehcache緩存
eache-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="shiroCache">
    <defaultCache maxElementsInMemory="10000" eternal="false"
        timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false"
        diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
</ehcache>

Realm實現

認證實現

Shiro權限認證,最終交由Realm來執行,會調用doGetAuthenticationInfo(AuthenticationToken token)方法,該方法主要完成以下操作:
    1 檢查提交的進行認證的令牌信息
    2 根據令牌信息從數據源(通常爲數據庫)中獲取用戶信息
    3 對用戶信息進行匹配驗證。
    4 驗證通過將返回一個封裝了用戶信息的AuthenticationInfo實例。
    5 驗證失敗則拋出AuthenticationException異常信息。

新建SecurityReaml類

/**
 * 登陸驗證
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    String username = String.valueOf(token.getPrincipal());
       String password = new String((char[]) token.getCredentials());
       // 通過數據庫進行驗證
       User authentication = userService.authentication(new User(username, password));
       if (authentication == null) {
           throw new AuthenticationException("用戶名或密碼錯誤.");
       }
       SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName());
       return authenticationInfo;
}

授權實現

Shiro的授權,是通過Realm的doGetAuthorizationInfo(PrincipalCollection principals)方法完成

/**
* 權限檢查
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
   SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
   String username = String.valueOf(principals.getPrimaryPrincipal());

   User user = userService.selectByUsername(username);//獲取用戶,拿到角色權限信息
   authorizationInfo.addRole(RoleSign.ADMIN);//添加admin權限
   authorizationInfo.addStringPermission(PermissionSign.USER_CREATE);//添加創建用戶user:create權限
    //TODO 在這裏添加角色權限,從數據庫查詢
    // final List<Role> roleInfos = roleService.selectRolesByUserId(user.getId());
    // for (Role role : roleInfos) {
    // 添加角色
    //authorizationInfo.addRole(role.getRoleSign());
    //
    //final List<Permission> permissions = permissionService.selectPermissionsByRoleId(role.getId());
    //for (Permission permission : permissions) {            
        //authorizationInfo.addStringPermission(permission.getPermissionSign());
    // }
    //}
   return authorizationInfo;
}

注意:Shiro權限控制是依賴項目自身的權限管理,Shiro本身不提供權限管理功能

Controller權限控制

登錄
在Controller控制層中,完成登錄驗證

@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(@Valid User user,Model model,HttpServletRequest request){
    try {
        // 得到當前Subject,即"用戶"
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return "redirect:/index";
        }
        // 身份驗證
        subject.login(new UsernamePasswordToken(user.getUname(), user.getPwd()));
        User authUser = userService.selectByUsername(user.getUname());
        request.getSession().setAttribute(Constants.SESSION_USER, authUser);
    } catch (AuthenticationException e) {
        // 身份驗證失敗
        model.addAttribute("error", "用戶名或密碼錯誤 !");
        return "login";
    }
    return "redirect:/index";
}

登出

/**
 * 用戶登出
 * 
 * @param session
 * @return
 */
 @RequestMapping(value = "/logout", method = RequestMethod.GET)
 public String logout(HttpSession session) {
     session.removeAttribute(Constants.SESSION_USER);
     // 登出操作
     Subject subject = SecurityUtils.getSubject();
     subject.logout();
     return "login";
 }

角色權限驗證
通過@RequiresRoles註解驗證

@RequestMapping(value="/admin")
@ResponseBody
@RequiresRoles(value=RoleSign.ADMIN)
public String admin(){
    return "擁有admin角色";
}

操作權限驗證
通過@RequiresPermissions驗證

@RequestMapping(value="/create")
@ResponseBody
@RequiresPermissions(value=PermissionSign.USER_CREATE)
public String create(){
    return "擁有創建用戶user:create權限";
}

JSP權限控制

導入taglib

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

guest標籤
用戶還沒有身份驗證

<shiro:guest>  
歡迎訪問,<a href="${pageContext.request.contextPath}/login">登錄</a>  
</shiro:guest>   

user標籤
用戶已經身份驗證/記住我登錄後顯示相應的信息

<shiro:user>  
歡迎[<shiro:principal/>],<a href="${pageContext.request.contextPath}/logout">退出</a>  
</shiro:user>   

authenticated標籤
戶已經身份驗證通過,即Subject.login登錄成功,不是記住我登錄的

<shiro:authenticated>  
    用戶[<shiro:principal/>]已身份驗證通過  
</shiro:authenticated> 

notAuthenticated標籤
用戶已經身份驗證通過,即沒有調用Subject.login進行登錄,包括記住我自動登錄的也屬於未進行身份驗證。

<shiro:notAuthenticated>
    未身份驗證(包括記住我)
</shiro:notAuthenticated>

principal標籤
顯示用戶身份信息,默認調用Subject.getPrincipal()獲取,即Primary Principal。

<shiro: principal/>

Subject.getPrincipals().oneByType(String.class)。

<shiro:principal type="java.lang.String"/> 

獲取用戶名((User)Subject.getPrincipals()).getUsername()。

<shiro:principal property="username"/>

hasRole標籤

<shiro:hasRole name="admin">  
    用戶[<shiro:principal/>]擁有角色admin<br/>  
</shiro:hasRole>   

hasAnyRoles標籤
包含任一權限

<shiro:hasAnyRoles name="admin,user">  
    用戶[<shiro:principal/>]擁有角色admin或user<br/>  
</shiro:hasAnyRoles>

lacksRole標籤
如果當前Subject沒有角色將顯示body體內容

<shiro:lacksRole name="test">  
    用戶[<shiro:principal/>]沒有角色abc<br/>  
</shiro:lacksRole> 

hasPermission標籤
如果當前Subject有權限將顯示body體內容

<shiro:hasPermission name="user:create">  
    用戶[<shiro:principal/>]擁有權限user:create<br/>  
</shiro:hasPermission>   

lacksPermission標籤
如果當前Subject沒有權限將顯示body體內容

<shiro:lacksPermission name="org:create">  
    用戶[<shiro:principal/>]沒有權限org:create<br/>  
</shiro:lacksPermission>

實例源碼

https://github.com/tangthis/JThis

推薦技術分享微信公衆號
互聯網技術分享

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