Shiro權限框架簡單快速入門

聲明本文只適合初學者,本人也是剛接觸而已,通過一段時間的研究小有收穫,特來分享下但願和你們互相交流學習。

首先配置咱們的web.xml代碼以下:
           
           
           
           
<filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </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



相關文章
相關標籤/搜索