天天看點

Shiro 授權&注解式開發 - SSMShiro 授權Shiro 注解開發

Shiro 授權&注解式開發 - SSM

  • Shiro 授權
  • Shiro 注解開發

權限圖解如下:

Shiro 授權&注解式開發 - SSMShiro 授權Shiro 注解開發

Shiro 授權

  1. 添加角色和權限的授權方法
    //根據username查詢該使用者的所有角色,用于角色驗證
     		  Set<String> findRoles(String username);
     		
     		  //根據username查詢他所擁有的權限資訊,用于權限判斷
     		  Set<String> findPermissions(String username);
               
  2. 自定義 Realm 配置 Shiro 授權認證
    1) 擷取驗證身份(使用者名)
     		  
     		  2) 根據身份(使用者名)擷取角色和權限資訊
     		  
     		  3) 将角色和權限資訊設定到SimpleAuthorizationInfo
     		  SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
     		  info.setRoles(roles);
     		  info.setStringPermissions(permissions);
               
  3. 使用 Shiro 标簽實作權限驗證

    3.1 導入 Shiro 标簽庫

    <%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
               
    3.2 Shiro 标簽庫
    guest标簽 :驗證目前使用者是否為“訪客”,即未認證(包含未記住)的使用者
     		  
     		  user标簽 :認證通過或已記住的使用者
     		  
     		  authenticated标簽 :已認證通過的使用者。不包含已記住的使用者,這是與user标簽的差別所在
     		  
     		  notAuthenticated标簽 :未認證通過使用者,與authenticated标簽相對應。與guest标簽的差別是,該标簽包含已記住使用者
     		  
     		  principal 标簽 :輸出目前使用者資訊,通常為登入帳号資訊 
     		  
     		  hasRole标簽 :驗證目前使用者是否屬于該角色 
     		  
     		  lacksRole标簽 :與hasRole标簽邏輯相反,當使用者不屬于該角色時驗證通過
     		  
     		  hasAnyRole标簽 :驗證目前使用者是否屬于以下任意一個角色
     		  
     		  hasPermission标簽 :驗證目前使用者是否擁有指定權限
     		  
     		  lacksPermission标簽 :與hasPermission标簽邏輯相反,目前使用者沒有制定權限時,驗證通過 
               

在 ShiroUserMapper.xml 中新增内容

<select id="getRolesByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select r.roleid from t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
    where u.userid = ur.userid and ur.roleid = r.roleid
    and u.userid = #{userid}
</select>
<select id="getPersByUserId" resultType="java.lang.String" parameterType="java.lang.Integer">
  select p.permission from t_shiro_user u,t_shiro_user_role ur,t_shiro_role_permission rp,t_shiro_permission p
  where u.userid = ur.userid and ur.roleid = rp.roleid and rp.perid = p.perid
  and u.userid = #{userid}
</select>


           

Service 層

ShiroUserService.java

package com.dj.ssm.service;

import com.dj.ssm.model.ShiroUser;

import java.util.Set;

public interface ShiroUserService {
    public Set<String> getRolesByUserId(Integer userId);

    public Set<String> getPersByUserId(Integer userId);

    public ShiroUser queryByName(String userName);
}


           

ShiroUserServiceImpl.java

package com.dj.ssm.service.impl;

import com.dj.ssm.mapper.ShiroUserMapper;
import com.dj.ssm.model.ShiroUser;
import com.dj.ssm.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;
    @Override
    public Set<String> getRolesByUserId(Integer userId) {
        return shiroUserMapper.getRolesByUserId(userId);
    }

    @Override
    public Set<String> getPersByUserId(Integer userId) {
        return shiroUserMapper.getPersByUserId(userId);
    }

    @Override
    public ShiroUser queryByName(String userName) {
        return shiroUserMapper.queryByName(userName);
    }
}


           

重寫自定義 realm 中的授權方法

@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("使用者授權...");
        String username = principals.getPrimaryPrincipal().toString();
        ShiroUser user = shiroUserService.queryByName(username);
        Set<String> roles = shiroUserService.getRolesByUserId(user.getUserid());
        Set<String> pers = shiroUserService.getPersByUserId(user.getUserid());

//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addRoles(roles);
//        info.addStringPermissions(pers);

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(pers);

        return info;
    }


           

Shiro 注解開發

  1. 配置注解權限驗證

    4.1 Shiro 注解

    常用注解介紹:

    @RequiresAuthenthentication:表示目前Subject已經通過login進行身份驗證;即 Subject.isAuthenticated()傳回 true
     		  
     		  @RequiresUser:表示目前Subject已經身份驗證或者通過記住我登入的
     		  
     		  @RequiresGuest:表示目前Subject沒有身份驗證或者通過記住我登入過,即是遊客身份
     		  
     		  @RequiresRoles(value = {"admin","user"},logical = Logical.AND):表示目前Subject需要角色admin和user
     		  
     		  @RequiresPermissions(value = {"user:delete","user:b"},logical = Logical.OR):表示目前Subject需要權限user:delete或者user:b
               

    4.2 開啟注解

    注意:必須将Shiro注解的開啟放置到spring-mvc.xml中(即放在springMVC容器中加載),不然Shiro注解開啟無效!!!

    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
     		      depends-on="lifecycleBeanPostProcessor">
     		    <property name="proxyTargetClass" value="true"></property>
     		</bean>
     		<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
     		    <property name="securityManager" ref="securityManager"/>
     		</bean>
               

    4.3 注解權限驗證失敗不跳轉路徑問題

    問題原因:由于我們架構是用springmvc架構來搭建的是以項目的路徑跳轉是由springmvc 來控制的,也就是說我們在shiro裡面的配置沒有用

    <!-- 身份驗證成功,跳轉到指定頁面 -->
     		  <property name="successUrl" value="/index.jsp"/>                //沒有用,達不到預期效果
     		  
     		  <!-- 權限驗證失敗,跳轉到指定頁面 -->
     		  <property name="unauthorizedUrl" value="/user/noauthorizeUrl"/> //沒有用,達不到預期效果
               
    解決方案: springmvc中有一個org.springframework.web.servlet.handler.SimpleMappingExceptionResolver 類就可以解決這個問題
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
     		    <property name="exceptionMappings">
     		        <props>
     		            <prop key="org.apache.shiro.authz.UnauthorizedException">
     		                unauthorized
     		            </prop>
     		        </props>
     		    </property>
     			<property name="defaultErrorView" value="unauthorized"/>
     		  </bean>
               

注解的具體使用:

Controller層

@RequiresUser
@RequestMapping("/passUser")
public String passUser(HttpServletRequest request){
    return "admin/addUser";
}

@RequiresRoles(value = {"1","4"},logical = Logical.AND)
@RequestMapping("/passRole")
public String passRole(HttpServletRequest request){
    return "admin/listUser";
}

@RequiresPermissions(value = {"user:update","user:view"},logical = Logical.OR)
@RequestMapping("/passPer")
public String passPer(HttpServletRequest request){
    return "admin/resetPwd";
}

@RequestMapping("/unauthorized")
public String unauthorized(){
    return "unauthorized";
}


           

Springmvc.xml

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
      depends-on="lifecycleBeanPostProcessor">
    <property name="proxyTargetClass" value="true"></property>
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>

<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="org.apache.shiro.authz.UnauthorizedException">
                unauthorized
            </prop>
        </props>
    </property>
    <property name="defaultErrorView" value="unauthorized"/>
</bean>


           

Jsp 測試代碼

<ul>
    shiro注解
    <li>
        <a href="${pageContext.request.contextPath}/passUser">使用者認證</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passRole">角色</a>
    </li>
    <li>
        <a href="${pageContext.request.contextPath}/passPer">權限認證</a>
    </li>
</ul>


           

結果:

zs隻能檢視身份認證的按鈕内容

ls、ww可以看權限認證按鈕内容

zdm可以看所有按鈕的内容

繼續閱讀