Shiro權限框架簡單快速入門


聲明本文只適合初學者,本人也是剛接觸而已,經過一段時間的研究小有收獲,特來分享下希望和大家互相交流學習。

首先配置我們的web.xml代碼如下:
           
           
           
                   
  1. <filter>
  2. <filter-name>shiroFilter</filter-name>
  3. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>shiroFilter</filter-name>
  7. <url-pattern>/*</url-pattern>
  8. </filter-mapping>

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //獲取當前登陸的用戶名
        String loginName = 
              (String) principalCollection.fromRealm(getName()).iterator().next();
        //根據用戶名查找對象
        User user = userService.findByLoginName(loginName);
        if(user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //添加角色(Set集合<字符串>)
            info.setRoles(user.getGroupNameSet());
            //迭代用戶對應的角色集合,為了獲取角色對應的權限
            for(UserGroup g : user.getUserGroupList()) {
                //添加permission
                info.addStringPermissions(g.getPermissionStringList());
            }
            return info;
        }
        return null;
    }
   
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //根據用戶名去查找對象
        User user = userService.findByLoginName(token.getUsername());
       
        if(user != null) {
          return new SimpleAuthenticationInfo(user.getName(),
              user.getPassword(),getName());
        }
        return null;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}

各部分代碼功能上面注釋已基本解釋了,我要說的是,我們平時有可能比較喜歡使用currUser對象,但是貌似在這里沒有辦法得到了。其實不然,首先shiro給我們提供的Subject的會話可以滿足我們的需求
Session session = subject.getSession();
Session session = subject.getSession(boolean create);
這些方法在概念上等同於HttpServletRequest API。第一個方法會返 回Subject的現有會話,或者如果還沒有會話,它會創建一個新的並將之返回。
第二個方法接受一個布爾參數,這個參數用於判定會話不存在時是否創建新會話 。一旦獲得Shiro的會話,你幾乎可以像使用HttpSession一樣使用它。Shiro團 隊覺得對於Java開發者,HttpSession API用起來太舒服了,所以我們保留了它 的很多感覺。當然,最大的不同在於,你可以在任何應用中使用Shiro會話,不 僅限於Web應用。 因此你可以再驗證登陸里寫這樣的一句話來完成我們的代碼轉換 SecurityUtils.getSubject().getSession().setAttribute("currUser", user); 注意在異常處理里需要移除此currUser。 當然官方推薦使用 Subject currentUser SecurityUtils.getSubject()

最后就是我們的Controller了。 在這里我介紹登陸和退出
@RequestMapping("/user/login")
    public String login(User user,HttpSession session) {
        try {
            SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getName(), user.getPassword()));
            return "redirect:/index";
        } catch (AuthenticationException e) {
            session.setAttribute("msg","用戶密碼錯誤或用戶名不存在");
            return "redirect:/user/tologin";
        }
            
    }      

@RequestMapping("/user/exit")
    public String exit() {
        SecurityUtils.getSubject().logout();
        return "redirect:/user/login";
    }
好了,這樣基本算是完成任務了,接下來就是頁面上的操作了。為此shiro還提供了相應的標簽,在這里我就照搬官方的了,因為這個實在簡單,大家一看就明白
引用 <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
guest標簽 
驗證當前用戶是否為“訪客”,即未認證(包含未記住)的用戶

  1. <shiro:guest>  
  2.     Hi there!  Please <a href="login.jsp">Login</a> or <a href="signup.jsp">Signup</a> today!  
  3. </shiro:guest> 

user標簽 
認證通過或已記住的用戶

  1. <shiro:user>  
  2.     Welcome back John!  Not John? Click <a href="login.jsp">here<a> to login.  
  3. </shiro:user> 

authenticated標簽 
已認證通過的用戶。不包含已記住的用戶,這是與user標簽的區別所在。 
  1. <shiro:authenticated>  
  2.     <a href="updateAccount.jsp">Update your contact information</a> 
  3. </shiro:authenticated>  

notAuthenticated標簽 
未認證通過用戶,與authenticated標簽相對應。與guest標簽的區別是,該標簽包含已記住用戶。
  1. <shiro:notAuthenticated>  
  2.     Please <a href="login.jsp">login</a> in order to update your credit card information.  
  3. </shiro:notAuthenticated> 

principal 標簽 
輸出當前用戶信息,通常為登錄帳號信息 
  1. Hello, <shiro:principal/>how are you today?  

hasRole標簽 
驗證當前用戶是否屬於該角色 
  1. <shiro:hasRole name="administrator">  
  2.     <a href="admin.jsp">Administer the system</a>  
  3. </shiro:hasRole> 


lacksRole標簽 
與hasRole標簽邏輯相反,當用戶不屬於該角色時驗證通過 
  1. <shiro:lacksRole name="administrator">  
  2.     Sorry, you are not allowed to administer the system.  
  3. </shiro:lacksRole> 


hasAnyRole標簽 
驗證當前用戶是否屬於以下任意一個角色。
  1. <shiro:hasAnyRoles name="developer, project manager, administrator">  
  2.     You are either developer, project manager, or administrator.  
  3. </shiro:lacksRole>  

hasPermission標簽 
驗證當前用戶是否擁有制定權限 

  1. <shiro:hasPermission name="user:create">  
  2.     <a href="createUser.jsp">Create new User</a>  
  3. </shiro:hasPermission> 

lacksPermission標簽 
與hasPermission標簽邏輯相反,當前用戶沒有制定權限時,驗證通過 
Xml代碼  
  1. <shiro:hasPermission name="user:create">  
  2.     <a href="createUser.jsp">Create new User</a>  
  3. </shiro:hasPermission> 
還有一個重要的就是數據庫的設計,我把圖貼出來大家一看也就明白了,我在這里簡單的描述下吧
shiro權限框架簡單快速入門

user == subject:用戶, group(role):角色
permission:權限(擁有權限比較細的情況,一般只要user和group就滿足要求了)
最后 提一下jar包,別弄錯了。是shiro-all.jar。可以從官網下載 http://shiro.apache.org/download.html






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM