權限管理系統之集成Shiro實現登陸、url和頁面按鈕的訪問控制

用戶權限管理通常是對用戶頁面、按鈕的訪問權限管理。Shiro框架是一個強大且易用的Java安全框架,執行身份驗證、受權、密碼和會話管理,對於Shiro的介紹這裏就很少說。本篇博客主要是瞭解Shiro的基礎使用方法,在權限管理系統中集成Shiro實現登陸、url和頁面按鈕的訪問控制。html

1、引入依賴前端

使用SpringBoot集成Shiro時,在pom.xml中能夠引入shiro-spring-boot-web-starter。因爲使用的是thymeleaf框架,thymeleaf與Shiro結合須要 引入thymeleaf-extras-shiro。java

        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring-boot-web-starter -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-web-starter</artifactId>
            <version>1.4.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

2、增長Shiro配置git

有哪些url是須要攔截的,哪些是不須要攔截的,登陸頁面、登陸成功頁面的url、自定義的Realm等這些信息須要設置到Shiro中,因此建立Configuration文件ShiroConfig。github

package com.example.config;


import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

import java.util.LinkedHashMap;
import java.util.Map;


@Configuration
public class ShiroConfig {
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //攔截器.
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
        // 配置不會被攔截的連接 順序判斷
        filterChainDefinitionMap.put("/static/**", "anon");
        //配置退出 過濾器,其中的具體的退出代碼Shiro已經替咱們實現了
        filterChainDefinitionMap.put("/logout", "logout");
        //<!-- 過濾鏈定義,從上向下順序執行,通常將/**放在最爲下邊 -->:這是一個坑呢,一不當心代碼就很差使了;
        //<!-- authc:全部url都必須認證經過才能夠訪問; anon:全部url都均可以匿名訪問-->
        filterChainDefinitionMap.put("/**", "authc");
        // 若是不設置默認會自動尋找Web工程根目錄下的"/login.jsp"頁面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登陸成功後要跳轉的連接
        shiroFilterFactoryBean.setSuccessUrl("/index");

        //未受權界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean(name="defaultWebSecurityManager")    //建立DefaultWebSecurityManager    
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")MyShiroRealm userRealm){        
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();        
        defaultWebSecurityManager.setRealm(userRealm);        
        return defaultWebSecurityManager;
        
    }        
    //建立Realm    
    @Bean(name="userRealm")    
    public MyShiroRealm getUserRealm(){        
        return new MyShiroRealm();    
        
    }
    
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}
View Code

ShiroDialect這個bean對象是在thymeleaf與Shiro結合,前端html訪問Shiro時使用。web

3、自定義Realmspring

在自定義的Realm中繼承了AuthorizingRealm抽象類,重寫了兩個方法:doGetAuthorizationInfo和doGetAuthenticationInfo。doGetAuthorizationInfo主要是用來處理權限配置,doGetAuthenticationInfo主要處理身份認證。這裏在doGetAuthorizationInfo中,將role表的id和permission表的code分別設置到SimpleAuthorizationInfo對象中的role和permission中。還有一個地方須要注意:@Component("authorizer"),剛開始我沒設置,但報錯提示須要一個authorizer的bean,查看AuthorizingRealm能夠發現它implements了Authorizer,因此在自定義的realm上添加@Component("authorizer")就能夠了。chrome

package com.example.config;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.pojo.Permission;
import com.example.pojo.Role;
import com.example.pojo.User;
import com.example.service.RoleService;
import com.example.service.UserService;

@Component("authorizer")
public class MyShiroRealm extends AuthorizingRealm {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private RoleService roleService;
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("權限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user  = (User)principals.getPrimaryPrincipal();
        System.out.println("User:"+user.toString()+" roles count:"+user.getRoles().size());
        for(Role role:user.getRoles()){
            authorizationInfo.addRole(role.getId());
            role=roleService.getRoleById(role.getId());
            System.out.println("Role:"+role.toString());
            for(Permission p:role.getPermissions()){
                System.out.println("Permission:"+p.toString());
                authorizationInfo.addStringPermission(p.getCode());
            }
        }
        System.out.println("權限配置-->authorizationInfo"+authorizationInfo.toString());
        return authorizationInfo;
    }

    /*主要是用來進行身份認證的,也就是說驗證用戶輸入的帳號和密碼是否正確。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //獲取用戶的輸入的帳號.
        String username = (String)token.getPrincipal();
        System.out.println(token.getCredentials());
        //經過username從數據庫中查找 User對象,若是找到,沒找到.
        //實際項目中,這裏能夠根據實際狀況作緩存,若是不作,Shiro本身也是有時間間隔機制,2分鐘內不會重複執行該方法
        User user = userService.getUserById(username);
        System.out.println("----->>userInfo="+user);
        if(user == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用戶名
                "123456", //密碼
                getName()  //realm name
        );
        return authenticationInfo;
    }

}
View Code

4、登陸認證數據庫

1.登陸頁面apache

這裏作了一個很是醜的登陸頁面,主要是本身懶,不想在網上覆制粘貼找登陸頁面了。

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
</head>

<form action="/login" method="post"> 
      <label>用戶名:</label><input type="text" name="id"   id="id" ><br>
      <label >密碼:</label><input type="text" name="pwd"  id="pwd" ><br>
      <button type="submit">登陸</button><button type="reset">取消</button>
</form>
</body>
</html>
View Code

2.處理登陸請求

在LoginController中經過登陸名、密碼獲取到token實現登陸。

package com.example.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

    //退出的時候是get請求,主要是用於退出
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    //post登陸
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(Model model,String id,String pwd){
        //添加用戶認證信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                id,
                "123456");
        try {            
                subject.login(usernamePasswordToken);            
                return "home";   
            }
        catch (UnknownAccountException e) {            
            //用戶名不存在            
            model.addAttribute("msg","用戶名不存在");            
            return "login";        
            }catch (IncorrectCredentialsException e) {            
                //密碼錯誤            
                model.addAttribute("msg","密碼錯誤");            
                return "login";        
                }
        
    }
    @RequestMapping(value = "/index")
    public String index(){
        return "home";
    }

}
View Code

5、Controller層訪問控制

1.首先來數據庫的數據,兩張圖是用戶角色、和角色權限的數據。

2.設置權限

這裏在用戶頁面點擊編輯按鈕時設置須要有id=002的角色,在點擊選擇角色按鈕時須要有code=002的權限。

    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    @RequiresRoles("002")//權限管理;
    public String editGet(Model model,@RequestParam(value="id") String id) {
        model.addAttribute("id", id);
        return "/user/edit";
    }
    @RequestMapping(value = "/selrole",method = RequestMethod.GET)
    @RequiresPermissions("002")//權限管理;
    public String selctRole(Model model,@RequestParam("id") String id,@RequestParam("type") Integer type) {
        model.addAttribute("id",id);
        model.addAttribute("type", type);
        return "/user/selrole";
    }
 

 當使用用戶001登陸時,點擊編輯,彈出框以下,提示沒有002的角色

點擊選擇角色按鈕時提示沒有002的權限。

當使用用戶002登陸時,點擊編輯按鈕,顯示正常,點擊選擇角色也是提示沒002的權限,由於權限只有001。

6、前端頁面層訪問控制

有時爲了避免想像上面那樣彈出錯誤頁面,須要在按鈕顯示上進行不可見,這樣用戶也不會點擊到。前面已經引入了依賴並配置了bean,這裏測試下在html中使用shiro。

1.首先設置html標籤引入shiro

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

2.控制按鈕可見

這裏使用shiro:hasAnyRoles="002,003"判斷用戶角色是不是002或003,是則顯示不是則不顯示。

    <div class="layui-inline">
        <a shiro:hasAnyRoles="002,003" class="layui-btn layui-btn-normal newsAdd_btn" onclick="addUser('')">添加用戶</a>
    </div>
    <div class="layui-inline">
        <a shiro:hasAnyRoles="002,003" class="layui-btn layui-btn-danger batchDel" onclick="getDatas();">批量刪除</a>
    </div>

當001用戶登陸時,添加用戶、批量刪除按鈕都不顯示,只顯示查詢按鈕。

當002用戶登陸時,添加用戶、批量刪除按鈕都顯示

7、小結

這裏只是實現了Shiro的簡單的功能,Shiro還有不少很強大的功能,好比session管理等,並且目前權限管理模塊還有不少須要優化的功能,左側導航欄的動態加載和權限控制、Shiro與Redis結合實現session共享、Shiro與Cas結合實現單點登陸等。後續能夠把項目作爲開源項目,慢慢完善集成更多模塊例如:Swagger二、Redis、Druid、RabbitMQ等供初學者參考。

相關文章
相關標籤/搜索