1. 程式人生 > 實用技巧 >實現登入、URL和頁面按鈕的訪問控制

實現登入、URL和頁面按鈕的訪問控制

使用者許可權管理一般是對使用者頁面、按鈕的訪問許可權管理。Shiro框架是一個強大且易用的Java安全框架,執行身份驗證、授權、密碼和會話管理,對於Shiro的介紹這裡就不多說。本篇部落格主要是瞭解Shiro的基礎使用方法,在許可權管理系統中整合Shiro實現登入、url和頁面按鈕的訪問控制。

一、引入依賴

使用SpringBoot整合Shiro時,在pom.xml中可以引入shiro-spring-boot-web-starter。由於使用的是thymeleaf框架,thymeleaf與Shiro結合需要 引入thymeleaf-extras-shiro。

<!-- 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>

二、增加Shiro配置

有哪些url是需要攔截的,哪些是不需要攔截的,登入頁面、登入成功頁面的url、自定義的Realm等這些資訊需要設定到Shiro中,所以建立Configuration檔案ShiroConfig。

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();
    }
}

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

三、自定義Realm

在自定義的Realm中繼承了AuthorizingRealm抽象類,重寫了兩個方法:doGetAuthorizationInfo和doGetAuthenticationInfo。doGetAuthorizationInfo主要是用來處理許可權配置,doGetAuthenticationInfo主要處理身份認證。

這裡在doGetAuthorizationInfo中,將role表的id和permission表的code分別設定到SimpleAuthorizationInfo物件中的role和permission中。

還有一個地方需要注意:@Component("authorizer"),剛開始我沒設定,但報錯提示需要一個authorizer的bean,檢視AuthorizingRealm可以發現它implements了Authorizer,所以在自定義的realm上新增@Component("authorizer")就可以了。

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;
    }

}

四、登入認證

1.登入頁面

這裡做了一個非常醜的登入頁面,主要是自己懶,不想在網上覆制貼上找登入頁面了。

<!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>

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";
    }

}

五、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。

六、前端頁面層訪問控制

有時為了不想像上面那樣彈出錯誤頁面,需要在按鈕顯示上進行不可見,這樣使用者也不會點選到。前面已經引入了依賴並配置了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使用者登入時,新增使用者、批量刪除按鈕都顯示

七、小結

這裡只是實現了Shiro的簡單的功能,Shiro還有很多很強大的功能,比如session管理等,而且目前許可權管理模組還有很多需要優化的功能,左側導航欄的動態載入和許可權控制、Shiro與Redis結合實現session共享、Shiro與Cas結合實現單點登入等。後續可以把專案做為開源專案,慢慢完善整合更多模組例如:Swagger2、Redis、Druid、RabbitMQ等。

@RequestMapping(value="/selrole",method=RequestMethod.GET)
@RequiresPermissions("002")//許可權管理;
publicStringselctRole(Modelmodel,@RequestParam("id")Stringid,@RequestParam("type")Integertype){
model.addAttribute("id",id);
model.addAttribute("type",type);
return"/user/selrole";
}