SpringBoot+shiro整合學(xué)習(xí)之登錄認(rèn)證和權(quán)限控制

學(xué)習(xí)任務(wù)目標(biāo)

  1. 用戶必須要登陸之后才能訪問定義鏈接,否則跳轉(zhuǎn)到登錄頁面。

  2. 對(duì)鏈接進(jìn)行權(quán)限控制,只有當(dāng)當(dāng)前登錄用戶有這個(gè)鏈接訪問權(quán)限才可以訪問,否則跳轉(zhuǎn)到指定頁面。

  3. 輸入錯(cuò)誤密碼用戶名或則用戶被設(shè)置為靜止登錄,返回相應(yīng)json串信息。

我是用的是之前搭建的一個(gè)springboot+mybatisplus+jsp的一個(gè)基礎(chǔ)框架。在這之上進(jìn)行shiro的整合。需要的同學(xué)可以去我的碼云下載。

個(gè)人博客:http://z77z.oschina.io/

此項(xiàng)目下載地址:https://git.oschina.net/z77z/springboot_mybatisplus

導(dǎo)入shiro依賴包到pom.xml

<!-- shiro權(quán)限控制框架 -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.3.2</version>
</dependency>

采用RBAC模式建立數(shù)據(jù)庫

RBAC 是基于角色的訪問控制(Role-Based Access Control )在 RBAC 中,權(quán)限與角色相關(guān)聯(lián),用戶通過成為適當(dāng)角色的成員而得到這些角色的權(quán)限。這就極大地簡(jiǎn)化了權(quán)限的管理。這樣管理都是層級(jí)相互依賴的,權(quán)限賦予給角色,而把角色又賦予用戶,這樣的權(quán)限設(shè)計(jì)很清楚,管理起來很方便。

/*表結(jié)構(gòu)插入*/
DROP TABLE IF EXISTS `u_permission`;

CREATE TABLE `u_permission` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `url` varchar(256) DEFAULT NULL COMMENT 'url地址',
  `name` varchar(64) DEFAULT NULL COMMENT 'url描述',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

/*Table structure for table `u_role` */

DROP TABLE IF EXISTS `u_role`;

CREATE TABLE `u_role` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL COMMENT '角色名稱',
  `type` varchar(10) DEFAULT NULL COMMENT '角色類型',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Table structure for table `u_role_permission` */

DROP TABLE IF EXISTS `u_role_permission`;

CREATE TABLE `u_role_permission` (
  `rid` bigint(20) DEFAULT NULL COMMENT '角色I(xiàn)D',
  `pid` bigint(20) DEFAULT NULL COMMENT '權(quán)限ID'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Table structure for table `u_user` */

DROP TABLE IF EXISTS `u_user`;

CREATE TABLE `u_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(20) DEFAULT NULL COMMENT '用戶昵稱',
  `email` varchar(128) DEFAULT NULL COMMENT '郵箱|登錄帳號(hào)',
  `pswd` varchar(32) DEFAULT NULL COMMENT '密碼',
  `create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
  `last_login_time` datetime DEFAULT NULL COMMENT '最后登錄時(shí)間',
  `status` bigint(1) DEFAULT '1' COMMENT '1:有效,0:禁止登錄',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;

/*Table structure for table `u_user_role` */

DROP TABLE IF EXISTS `u_user_role`;

CREATE TABLE `u_user_role` (
  `uid` bigint(20) DEFAULT NULL COMMENT '用戶ID',
  `rid` bigint(20) DEFAULT NULL COMMENT '角色I(xiàn)D'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Dao層代碼的編寫

Dao層的entity,service,mapper等我是采用mybatisplus的代碼自動(dòng)生成工具生成的,具備了單表的增刪改查功能和分頁功能,比較方便,這里我就不貼代碼了。

配置shiro

ShiroConfig.java

/**
 * @author 作者 z77z
 * @date 創(chuàng)建時(shí)間:2017年2月10日 下午1:16:38
 * 
 */
@Configuration
public class ShiroConfig {
    /**
     * ShiroFilterFactoryBean 處理攔截資源文件問題。
     * 注意:?jiǎn)为?dú)一個(gè)ShiroFilterFactoryBean配置是或報(bào)錯(cuò)的,以為在
     * 初始化ShiroFilterFactoryBean的時(shí)候需要注入:SecurityManager
     *
     * Filter Chain定義說明 1、一個(gè)URL可以配置多個(gè)Filter,使用逗號(hào)分隔 2、當(dāng)設(shè)置多個(gè)過濾器時(shí),全部驗(yàn)證通過,才視為通過
     * 3、部分過濾器可指定參數(shù),如perms,roles
     *
     */
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 必須設(shè)置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 如果不設(shè)置默認(rèn)會(huì)自動(dòng)尋找Web工程根目錄下的"/login.jsp"頁面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登錄成功后要跳轉(zhuǎn)的鏈接
        shiroFilterFactoryBean.setSuccessUrl("/index");
        // 未授權(quán)界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");

        // 攔截器.
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        // 配置不會(huì)被攔截的鏈接 順序判斷
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/ajaxLogin", "anon");

        // 配置退出過濾器,其中的具體的退出代碼Shiro已經(jīng)替我們實(shí)現(xiàn)了
        filterChainDefinitionMap.put("/logout", "logout");

        filterChainDefinitionMap.put("/add", "perms[權(quán)限添加]");

        // <!-- 過濾鏈定義,從上向下順序執(zhí)行,一般將 /**放在最為下邊 -->:這是一個(gè)坑呢,一不小心代碼就不好使了;
        // <!-- authc:所有url都必須認(rèn)證通過才可以訪問; anon:所有url都都可以匿名訪問-->
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        System.out.println("Shiro攔截器工廠類注入成功");
        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 設(shè)置realm.
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    /**
     * 身份認(rèn)證realm; (這個(gè)需要自己寫,賬號(hào)密碼校驗(yàn);權(quán)限等)
     * 
     * @return
     */
    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        return myShiroRealm;
    }
}

登錄認(rèn)證實(shí)現(xiàn)

在認(rèn)證、授權(quán)內(nèi)部實(shí)現(xiàn)機(jī)制中都有提到,最終處理都將交給Real進(jìn)行處理。因?yàn)樵赟hiro中,最終是通過Realm來獲取應(yīng)用程序中的用戶、角色及權(quán)限信息的。通常情況下,在Realm中會(huì)直接從我們的數(shù)據(jù)源中獲取Shiro需要的驗(yàn)證信息??梢哉f,Realm是專用于安全框架的DAO.

Shiro的認(rèn)證過程最終會(huì)交由Realm執(zhí)行,這時(shí)會(huì)調(diào)用Realm的getAuthenticationInfo(token)方法。
該方法主要執(zhí)行以下操作:

1、檢查提交的進(jìn)行認(rèn)證的令牌信息

2、根據(jù)令牌信息從數(shù)據(jù)源(通常為數(shù)據(jù)庫)中獲取用戶信息

3、對(duì)用戶信息進(jìn)行匹配驗(yàn)證。

4、驗(yàn)證通過將返回一個(gè)封裝了用戶信息的AuthenticationInfo實(shí)例。

5、驗(yàn)證失敗則拋出AuthenticationException異常信息。

而在我們的應(yīng)用程序中要做的就是自定義一個(gè)Realm類,繼承AuthorizingRealm抽象類,重載doGetAuthenticationInfo
(),重寫獲取用戶信息的方法。

doGetAuthenticationInfo的重寫

/**
* 認(rèn)證信息.(身份驗(yàn)證) : Authentication 是用來驗(yàn)證用戶身份
 * 
 * @param token
 * @return
 * @throws AuthenticationException
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
        AuthenticationToken authcToken) throws AuthenticationException {
    System.out.println("身份認(rèn)證方法:MyShiroRealm.doGetAuthenticationInfo()");

    ShiroToken token = (ShiroToken) authcToken;
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("nickname", token.getUsername());
    map.put("pswd", token.getPswd());
    SysUser user = null;
    // 從數(shù)據(jù)庫獲取對(duì)應(yīng)用戶名密碼的用戶
    List<SysUser> userList = sysUserService.selectByMap(map);
    if(userList.size()!=0){
        user = userList.get(0);
    }
    if (null == user) {
        throw new AccountException("帳號(hào)或密碼不正確!");
    }else if(user.getStatus()==0){
        /**
         * 如果用戶的status為禁用。那么就拋出<code>DisabledAccountException</code>
         */
        throw new DisabledAccountException("帳號(hào)已經(jīng)禁止登錄!");
    }else{
        //更新登錄時(shí)間 last login time
        user.setLastLoginTime(new Date());
        sysUserService.updateById(user);
    }
    return new SimpleAuthenticationInfo(user, user.getPswd(), getName());
}

通俗的說,這個(gè)的重寫就是我們第一個(gè)學(xué)習(xí)目標(biāo)的實(shí)現(xiàn)。

鏈接權(quán)限的實(shí)現(xiàn)

shiro的權(quán)限授權(quán)是通過繼承AuthorizingRealm抽象類,重載doGetAuthorizationInfo();

當(dāng)訪問到頁面的時(shí)候,鏈接配置了相應(yīng)的權(quán)限或者shiro標(biāo)簽才會(huì)執(zhí)行此方法否則不會(huì)執(zhí)行,所以如果只是簡(jiǎn)單的身份認(rèn)證沒有權(quán)限的控制的話,那么這個(gè)方法可以不進(jìn)行實(shí)現(xiàn),直接返回null即可。

在這個(gè)方法中主要是使用類:SimpleAuthorizationInfo

進(jìn)行角色的添加和權(quán)限的添加。

authorizationInfo.addRole(role.getRole());

authorizationInfo.addStringPermission(p.getPermission());

當(dāng)然也可以添加set集合:roles是從數(shù)據(jù)庫查詢的當(dāng)前用戶的角色,stringPermissions是從數(shù)據(jù)庫查詢的當(dāng)前用戶對(duì)應(yīng)的權(quán)限

authorizationInfo.setRoles(roles);

authorizationInfo.setStringPermissions(stringPermissions);

就是說如果在shiro配置文件中添加了filterChainDefinitionMap.put("/add", "perms[權(quán)限添加]");
就說明訪問/add這個(gè)鏈接必須要有“權(quán)限添加”這個(gè)權(quán)限才可以訪問,

如果在shiro配置文件中添加了filterChainDefinitionMap.put("/add", "roles[100002],perms[權(quán)限添加]");
就說明訪問/add這個(gè)鏈接必須要有“權(quán)限添加”這個(gè)權(quán)限和具有“100002”這個(gè)角色才可以訪問。

/**
* 授權(quán)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
        PrincipalCollection principals) {
    System.out.println("權(quán)限認(rèn)證方法:MyShiroRealm.doGetAuthenticationInfo()");
    SysUser token = (SysUser)SecurityUtils.getSubject().getPrincipal();
    String userId = token.getId();
    SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
    //根據(jù)用戶ID查詢角色(role),放入到Authorization里。
    /*Map<String, Object> map = new HashMap<String, Object>();
    map.put("user_id", userId);
    List<SysRole> roleList = sysRoleService.selectByMap(map);
    Set<String> roleSet = new HashSet<String>();
    for(SysRole role : roleList){
        roleSet.add(role.getType());
    }*/
    //實(shí)際開發(fā),當(dāng)前登錄用戶的角色和權(quán)限信息是從數(shù)據(jù)庫來獲取的,我這里寫死是為了方便測(cè)試
    Set<String> roleSet = new HashSet<String>();
    roleSet.add("100002");
    info.setRoles(roleSet);
    //根據(jù)用戶ID查詢權(quán)限(permission),放入到Authorization里。
    /*List<SysPermission> permissionList = sysPermissionService.selectByMap(map);
    Set<String> permissionSet = new HashSet<String>();
    for(SysPermission Permission : permissionList){
        permissionSet.add(Permission.getName());
    }*/
    Set<String> permissionSet = new HashSet<String>();
    permissionSet.add("權(quán)限添加");
    info.setStringPermissions(permissionSet);
       return info;
}

這個(gè)類的實(shí)現(xiàn)是完成了我們學(xué)習(xí)目標(biāo)的第二個(gè)任務(wù)。

編寫web層的代碼

登錄頁面:

controller

//跳轉(zhuǎn)到登錄表單頁面
@RequestMapping(value="login")
public String login() {
    return "login";
}

/**
 * ajax登錄請(qǐng)求
 * @param username
 * @param password
 * @return
 */
@RequestMapping(value="ajaxLogin",method=RequestMethod.POST)
@ResponseBody
public Map<String,Object> submitLogin(String username, String password,Model model) {
    Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    try {
        
        ShiroToken token = new ShiroToken(username, password);
        SecurityUtils.getSubject().login(token);
        resultMap.put("status", 200);
        resultMap.put("message", "登錄成功");

    } catch (Exception e) {
        resultMap.put("status", 500);
        resultMap.put("message", e.getMessage());
    }
    return resultMap;
}

jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path;
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript"
    src="<%=basePath%>/static/js/jquery-1.11.3.js"></script>
<title>登錄</title>
</head>
<body>
    錯(cuò)誤信息:
    <h4 id="erro"></h4>
    <form>
        <p>
            賬號(hào):<input type="text" name="username" id="username" value="admin" />
        </p>
        <p>
            密碼:<input type="text" name="password" id="password" value="123" />
        </p>
        <p>
            <input type="button" id="ajaxLogin" value="登錄" />
        </p>
    </form>
</body>
<script>
    var username = $("#username").val();
    var password = $("#password").val();
    $("#ajaxLogin").click(function() {
        $.post("/ajaxLogin", {
            "username" : username,
            "password" : password
        }, function(result) {
            if (result.status == 200) {
                location.href = "/index";
            } else {
                $("#erro").html(result.message);
            }
        });
    });
</script>
</html>

主頁頁面

controller

//跳轉(zhuǎn)到主頁
@RequestMapping(value="index")
public String index() {
    return "index";
}

/**
* 退出
 * @return
 */
@RequestMapping(value="logout",method =RequestMethod.GET)
@ResponseBody
public Map<String,Object> logout(){
    Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    try {
        //退出
        SecurityUtils.getSubject().logout();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    return resultMap;
}

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript"
    src="<%=basePath%>/static/js/jquery-1.11.3.js"></script>
<title>Insert title here</title>
</head>
<body>
    helloJsp
    <input type="button" id="logout" value="退出登錄" />
</body>
<script type="text/javascript">
    $("#logout").click(function(){
        location.href="/logout";
    });
</script>
</html>

添加操作頁面

controller

@RequestMapping(value="add")
public String add() {
    return "add";
}

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript"
    src="<%=basePath%>/static/js/jquery-1.11.3.js"></script>
<title>Insert title here</title>
</head>
<body>
具有添加權(quán)限
</body>
</html>

測(cè)試

任務(wù)一

編寫好后就可以啟動(dòng)程序,訪問index頁面,由于沒有登錄就會(huì)跳轉(zhuǎn)到login頁面。

登錄之后就會(huì)跳轉(zhuǎn)到index頁面,點(diǎn)擊退出登錄后,有直接在瀏覽器中輸入index頁面訪問,又會(huì)跳轉(zhuǎn)到login頁面

上面這些操作時(shí)候觸發(fā)MyShiroRealm.doGetAuthenticationInfo()這個(gè)方法,也就是登錄認(rèn)證的方法。


任務(wù)二

登錄之后訪問add頁面成功訪問,在shiro配置文件中改變add的訪問權(quán)限為

filterChainDefinitionMap.put("/add","perms[權(quán)限刪除]");

再重新啟動(dòng)程序,登錄后訪問,會(huì)重定向到/403頁面,由于沒有編寫403頁面,報(bào)404錯(cuò)誤。

上面這些操作,會(huì)觸發(fā)權(quán)限認(rèn)證方法:MyShiroRealm.doGetAuthorizationInfo(),每訪問一次就會(huì)觸發(fā)一次。


任務(wù)三

輸入錯(cuò)誤的用戶名或則密碼,返回“帳號(hào)或密碼不正確!”的錯(cuò)誤信息,在數(shù)據(jù)庫中把一個(gè)用戶的狀態(tài)改為被禁用,再登陸,提示“帳號(hào)已經(jīng)禁止登錄!”的錯(cuò)誤信息

上面的操作,是在MyShiroRealm.doGetAuthenticationInfo()登錄認(rèn)證的方法中實(shí)現(xiàn)的,通過查詢數(shù)據(jù)庫判斷當(dāng)前登錄用戶是否被禁用,具體可以去看源碼。

總結(jié)

當(dāng)然shiro很強(qiáng)大,這僅僅是完成了登錄認(rèn)證和權(quán)限管理這兩個(gè)功能,接下來我會(huì)繼續(xù)學(xué)習(xí)和分享,說說接下來的學(xué)習(xí)路線吧:

  1. shiro+redis集成,避免每次訪問有權(quán)限的鏈接都會(huì)去執(zhí)行MyShiroRealm.doGetAuthenticationInfo()方法來查詢當(dāng)前用戶的權(quán)限,因?yàn)閷?shí)際情況中權(quán)限是不會(huì)經(jīng)常變得,這樣就可以使用redis進(jìn)行權(quán)限的緩存。

  2. 實(shí)現(xiàn)shiro鏈接權(quán)限的動(dòng)態(tài)加載,之前要添加一個(gè)鏈接的權(quán)限,要在shiro的配置文件中添加filterChainDefinitionMap.put("/add", "roles[100002],perms[權(quán)限添加]"),這樣很不方便管理,一種方法是將鏈接的權(quán)限使用數(shù)據(jù)庫進(jìn)行加載,另一種是通過init配置文件的方式讀取。

  3. Shiro 自定義權(quán)限校驗(yàn)Filter定義,及功能實(shí)現(xiàn)。

  4. Shiro Ajax請(qǐng)求權(quán)限不滿足,攔截后解決方案。這里有一個(gè)前提,我們知道Ajax不能做頁面redirect和forward跳轉(zhuǎn),所以Ajax請(qǐng)求假如沒登錄,那么這個(gè)請(qǐng)求給用戶的感覺就是沒有任何反應(yīng),而用戶又不知道用戶已經(jīng)退出了。

  5. Shiro JSP標(biāo)簽使用。

  6. Shiro 登錄后跳轉(zhuǎn)到最后一個(gè)訪問的頁面

  7. 在線顯示,在線用戶管理(踢出登錄)。

  8. 登錄注冊(cè)密碼加密傳輸。

  9. 集成驗(yàn)證碼。

  10. 記住我的功能。關(guān)閉瀏覽器后還是登錄狀態(tài)。

  11. 還有沒有想到的后面再說,歡迎大家提出一些建議。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容