主頁 > 後端開發 > SpringBoot整合Shiro安全框架完整實作

SpringBoot整合Shiro安全框架完整實作

2020-11-06 08:05:16 後端開發


目錄

  • 一、環境搭建
    • 1. 匯入shiro-spring依賴
    • 2. 撰寫首頁及其controller
    • 3. 撰寫shiro配置類
  • 二、Shiro實作登錄攔截
    • 1. 撰寫頁面及其controller
    • 2. 實作登錄攔截
    • 3. 撰寫攔截后的登錄頁面
  • 三、Shiro實作用戶認證
  • 四、整合MyBatis
    • 1. 匯入依賴
    • 2. 創建資料庫&連接
    • 3. 配置資料源
    • 4. 撰寫pojo物體類
    • 5. 撰寫Mapper層
    • 6. 撰寫service層(可省略)
    • 7. 測驗
    • 8. 更改偽造資料為真實資料
  • 五、Shiro請求授權實作
    • 1. 添加授權
    • 2. 撰寫未授權頁面
    • 3. 給用戶授予權限
  • 六、Shiro整合thymeleaf
    • 1. 匯入依賴
    • 2. 撰寫配置
    • 3. 修改index.html


image-20201104155806233

  • Apache Shiro是一個功能強大且易于使用的Java安全框架,用于執行身份驗證,授權,加密和會話管理,

  • 使用Shiro易于理解的API,您可以快速輕松地保護任何應用程式-從最小的移動應用程式到最大的Web和企業應用程式,

官網:https://shiro.apache.org/

Github:https://github.com/apache/shiro

PS:筆者是看著狂神老師的shiro視頻來學習的,也推薦給大家:https://www.bilibili.com/video/BV1PE411i7CV?p=38

一、環境搭建

首先創建一個springboot專案,勾選組件時勾選Spring WebThymeleaf

1. 匯入shiro-spring依賴

匯入shiro整合springboot的包

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.6.0</version>
</dependency>

2. 撰寫首頁及其controller

resources/templates目錄下新建index.html首頁,注意匯入thymeleaf的命名空間,我們用th:text標簽接收前端的引數msg并顯示

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
</body>
</html>

然后在主程式同級目錄下新建controller包,其中新建MyController類,撰寫首頁跳轉的controller

其中給前端視圖存值msg

package com.zsr.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
    @RequestMapping({"/index", "/"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "Hello Shiro");
        return "index";
    }
}

3. 撰寫shiro配置類

在主程式同級目錄下新建config包,其中新建ShiroConfig配置類

其中需要配置三大物件并將其注入到spring容器中:

  • realm物件:可看作安全物體的資料源,該物件需要自定義,繼承AuthorizingRealm
  • DefaultWebSecurityManager物件:默認安全管理器物體
  • ShiroFilterFactoryBean物件:Shiro過濾工廠物體

首先撰寫自定義的realm類UserRealm,只需要繼承AuthorizingRealm類,重寫其認證和授權的方法

package com.zsr.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class UserRealm extends AuthorizingRealm {
    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("執行了=>授權doGetAuthorizationInfo");
        return null;
    }

    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("執行了=>認證doGetAuthorizationInfo");
        return null;
    }
}

然后撰寫shiro的配置類ShiroConfig,其中宣告三個物件:

  • realm安全物體資料源:用我們自定義的UserRealm類來創建
  • DefaultWebSecurityManager默認安全管理器:該物件需要關聯realm物件,在方法引數中傳入realm物件的引數,用@Qualifier指定需要的realm實作類UserRealm方法名即可
  • ShiroFilterFactoryBeanshiro過濾工廠物件:該物件需要關聯SecurityManager物件,同樣在引數中傳入該物件的引數,用@Qualifier指定需要的實作類方法名
package com.zsr.config;

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;

@Configuration
public class ShiroConfig {
    //創建realm物件,自定義
    @Bean
    public UserRealm userRealm() {
        return new UserRealm();
    }

    //DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //關聯UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //設定安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        return bean;
    }
}


二、Shiro實作登錄攔截

1. 撰寫頁面及其controller

在templates目錄下新建user包,撰寫add.htmlupdate.html頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>update</title>
</head>
<body>
<h1>update</h1>
</body>
</html>

然后在MyController中撰寫對應的controller

@RequestMapping("/user/add")
public String add() {
    return "user/add";
}

@RequestMapping("/user/update")
public String update() {
    return "user/update";
}

然后在首頁上增加相應跳轉的鏈接

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
<hr>
<a th:href="@{/user/add}">add</a> | <a th:href="@{/user/update}">update</a>
</body>
</html>

到此,我們的基本環境搭建完成

啟動主程式測驗一下,訪問localhost:8080
image-20201018133002954
點擊add即可跳轉到add.html,點擊update即可跳轉到update.html

2. 實作登錄攔截

在shiro配置類中,我們創建了三個物件,要實作登錄攔截功能,就要用到shiro過濾工廠物件

我們在配置類ShiroConfigshiroFilterFactoryBean()方法中添加shiro的攔截器,實作登錄過濾的功能

shiroFilterFactoryBean()方法中設定攔截器setFilterChainDefinitionMap

//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    //設定安全管理器
    bean.setSecurityManager(defaultWebSecurityManager);
    //添加shiro內置的過濾器
    /*
            anon:無需認證就可以訪問
            authc:必須認證了才能訪問
            user:必須擁有記住我功能才能使用
            perms:擁有對某個資源的權限才能訪問
            role:擁有某個角色權限才能訪問
         */
    Map<String, String> filterMap = new LinkedHashMap<>();//鏈式
    filterMap.put("/user/add", "anon");
    filterMap.put("/user/update", "authc");
    //filterMap.put("/user/*", "authc");支持通配符
    bean.setFilterChainDefinitionMap(filterMap);//引數為map型別
    //設定登錄的請求
    bean.setLoginUrl("/login");
    return bean;
}

再次重啟主程式訪問測驗一下,同樣訪問localhost:8080

點擊add可以正常訪問,點擊update無法正常訪問,這是因為攔截器的作用,/user/add請求無需認證就可以訪問,但是/user/authc請求需要認證才能訪問
image-20201018133247454
image-20201018133256387

3. 撰寫攔截后的登錄頁面

上述代碼成功實作攔截的功能,但是我們被攔截后應該跳轉到登陸頁面,因此我們需要創建一個登錄頁面,在templates目錄下新建一個login.html登錄頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登錄頁面</title>
</head>
<body>
<h1>登錄</h1>
<form action="/login">
    <p>用戶名:<input type="text" name="username"></p>
    <p>密碼:<input type="text" name="password"></p>
    <p><input type="submit"></p>
</form>
</body>
</html>

然后撰寫視圖跳轉的contoller

@RequestMapping("/login")
public String login() {
    return "login";
}

然后在上述配置類方法中中設定登錄的請求

bean.setLoginUrl("/login");//設定登錄的請求

啟動主程式測驗一下,訪問8080埠,點擊add成功顯示add.html,但是點擊update則會跳轉到登陸頁面,成功~
image-20201018134535009



三、Shiro實作用戶認證

上述創建Realm物件中,我們繼承了AuthorizingRealm類,重寫了其兩個方法,shiro實作用戶認證的功能,也就是在其中的認證方法doGetAuthenticationInfo中完成的,我們來測驗測驗

同官方案例的Quickstart原始碼一樣,可以看我的上一篇博客:Shiro第一個程式:官方快速入門程式Qucickstart詳解教程

實作用戶認證有幾個步驟:

  1. 獲取當前用戶
  2. 封裝用戶資訊生成token令牌
  3. 執行登錄操作(可以自定義捕獲例外)

我們將這些代碼撰寫在一個controller中,其中需要傳入兩個引數

  • username:用戶名
  • password:密碼

這兩個引數是通過前端登錄頁面傳送的

MyController類中增添toLogin方法

@RequestMapping("/toLogin")
public String toLogin(String username, String password, Model model) {
    //獲取當前用戶
    Subject subject = SecurityUtils.getSubject();
    //封裝用戶資訊生成token令牌
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    //執行登錄操作,可以自定義捕獲例外
    try {
        subject.login(token);
        return "index";//登錄成功回傳首頁
    } catch (UnknownAccountException e) {
        model.addAttribute("msg", "用戶名不存在");
        return "login";//用戶名錯誤回到登錄頁面
    } catch (IncorrectCredentialsException e) {
        model.addAttribute("msg", "密碼不正確");
        return "login";//證書
    }
}

然后登錄頁面點擊提交跳轉到/toLogin請求,即進入到上述方法,并且接收傳入的msg

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登錄頁面</title>
</head>
<body>
<h1>登錄</h1>
<p th:text="${msg}" style="color: red"></p>
<form action="/toLogin">
    <p>用戶名:<input type="text" name="username"></p>
    <p>密碼:<input type="text" name="password"></p>
    <p><input type="submit"></p>
</form>
</body>
</html>

我們啟動測驗一下:訪問localhost:8080/login
image-20201028142143575
隨便輸入用戶名密碼,然后點擊登錄,可以看到顯示用戶名不存在

同時查看控制臺資訊
image-20201028142258604
發現執行了自定義UserRealm中的doGetAuthenticationInfo認證方法

//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("執行了=>認證doGetAuthorizationInfo");
    return null;
}j

也就是只要我們點擊登錄,就會執行認證方法,因此我們需要在該方法中添加認證用戶資訊代碼

//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("執行了=>認證doGetAuthorizationInfo");
    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
    //偽造正確用戶名和密碼
    String username = "zsr";
    String password = "200024";
    //用戶名認證
    if (!token.getUsername().equals(username))
        return null;//只需要return null,就會自動拋出UnknownAccountException例外
    //密碼認證,涉及到安全問題,shiro自動完成
    return new SimpleAuthenticationInfo("", password, "zsr");
}

再次重啟測驗一下,輸入錯誤的用戶名和密碼
image-20201028143032285
顯示用戶不存在
image-20201028143141437
如果輸入正確的用戶名和錯誤的密碼
image-20201028143157018
則會顯示密碼不正確
image-20201028143249401
如果輸入正確的用戶名和密碼
image-20201028143308348
則成功登錄到首頁
image-20201028143318954



四、整合MyBatis

上述實作了簡單的用戶認證,實際開發中,所有的用戶資訊都在資料庫中,因此現在來整合資料庫進行使用

1. 匯入依賴

這里我們使用druid資料源,匯入三個依賴:

  • mysql連接驅動
  • druid資料源
  • log4j(配合druid資料源)
  • lombok(方便后續物體類)
<!--MySQL連接驅動-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--Druid資料源-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.1</version>
</dependency>
<!--log4j-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.12</version>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>
<!--springboot-mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

2. 創建資料庫&連接

首先創建一個資料庫shiro_mybatis

-- 創建資料庫
CREATE DATABASE shiro_mybatis;

-- 使用shiro_myabtis資料庫
use shiro_mybatis;

-- 創建user表
CREATE TABLE IF NOT EXISTS `user`(
	`id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '身份號',
	`name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '姓名',
	`pwd` VARCHAR(30) NOT NULL DEFAULT '123456' COMMENT '密碼',
	PRIMARY KEY (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8

-- 給user表插入資料
INSERT INTO `user`(`id`,`name`,`pwd`) 
VALUES ('1','zsr',000204),('2','gcc',000421),('3','BaretH',200024);

然后idea連接該資料庫并打開
image-20201028144744600
image-20201028232151515
資料表
image-20201028144834309

3. 配置資料源

新建spring-application.yaml,配置資料庫連接資訊和druid資料源的專有配置

spring:
  datasource:
    username: root
    password: 200024
    url: jdbc:mysql://localhost:3306/shiro_mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默認是不注入這些屬性值的,需要自己系結
    #druid 資料源專有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置監控統計攔截的filters
    # stat:監控統計
    # log4j:日志記錄(需要匯入log4j依賴)
    # wall:防御sql注入
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

4. 撰寫pojo物體類

在主程式同級目錄下新建pojo包,其中新建User

package com.zsr.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

5. 撰寫Mapper層

在主程式同級目錄下新建mapper包,其中新建UserMapper介面

package com.zsr.mapper;

import com.zsr.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Mapper //表示這是Mybatis的mapper類
@Repository
public interface UserMapper {
    //通過用戶名查詢用戶
    public User queryUserByName();
}

然后撰寫對應的mapper.xml,在resources目錄下新建mapper包,在其中新建UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsr.mapper.UserMapper">
    <select id="queryUserByName" parameterType="String" resultType="com.zsr.pojo.User">
        select * from shiro_mybatis.user where name=#{name};
    </select>
</mapper>

然后需然后要在springboot核心組態檔中系結該UserMapper.xml檔案

#系結mapper.xml
mybatis:
  mapper-locations: classpath:mapper/*.xml

6. 撰寫service層(可省略)

在主程式同級目錄下新建service包,其中新建UserServiceUserServiceImpl兩個類

package com.zsr.service;

import com.zsr.pojo.User;

public interface UserService {
    public User queryUserByName(String username);
}
package com.zsr.service;

import com.zsr.mapper.UserMapper;
import com.zsr.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User queryUserByName(String username) {
        return userMapper.queryUserByName(username);
    }
}

7. 測驗

在springboot提供的測驗類中進行測驗,根據用戶名查詢用戶

package com.zsr;

import com.zsr.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springboot07ShiroApplicationTests {
    @Autowired
    private UserServiceImpl userService;

    @Test
    void contextLoads() {
        System.out.println(userService.queryUserByName("zsr"));
    }
}

運行測驗一下,成功查到指定用戶
image-20201028232936434

8. 更改偽造資料為真實資料

到此,整合mybatis完畢,我們可以將上述偽造的用戶資料用資料庫來替代,我們修改UserRealm中認證方法的相關代碼

首先要注入UserServiceImpl物件,然后將偽造的資料更改為資料庫中真實的資料

package com.zsr.config;

import com.zsr.pojo.User;
import com.zsr.service.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserServiceImpl userService;

    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("執行了=>授權doGetAuthorizationInfo");
        return null;
    }

    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("執行了=>認證doGetAuthorizationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //連接真實的資料庫
        User user = userService.queryUserByName(token.getUsername());
        //用戶名認證
        if (user == null)
            return null;//只需要return null,就會自動拋出UnknownAccountException一場
        //密碼認證,涉及到安全問題,shiro自動完成
        return new SimpleAuthenticationInfo("", user.getPwd(), "zsr");
    }
}

然后再次重啟主程式進行測驗,進入到登錄頁面,只要輸入資料庫中正確的用戶名和密碼即可實作登錄
image-20201028234101357
image-20201028234135337
image-20201028234151698



五、Shiro請求授權實作

1. 添加授權

要實作登錄攔截功能,同樣通過shiro過濾工廠設定權限:

在shiro配置類ShiroConfig中的shiroFilterFactoryBean()方法中添加相關代碼實作請求授權

//設定授權,只有user:add權限的才能請求/user/add
filterMap.put("/user/add", "perms[user:add]");
//設定授權,只有user:update權限的才能請求/user/update
filterMap.put("/user/update", "perms[user:update]");
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    //設定安全管理器
    bean.setSecurityManager(defaultWebSecurityManager);
    //添加shiro內置的過濾器
    /*
            anon:無需認證就可以訪問
            authc:必須認證了才能訪問
            user:必須擁有記住我功能才能使用
            perms:擁有對某個資源的權限才能訪問
            role:擁有某個角色權限才能訪問
         */
    Map<String, String> filterMap = new LinkedHashMap<>();//鏈式
    filterMap.put("/user/add", "perms[user:add]");//設定授權,只有user:add權限的才能請求/user/add
    filterMap.put("/user/update", "perms[user:update]");
    bean.setFilterChainDefinitionMap(filterMap);//引數為map型別
    //設定登錄的請求
    bean.setLoginUrl("/login");
    return bean;
}

然后啟動主程式測驗一下,首先訪問登錄頁面localhost:8080/login
image-20201028235952915
輸入正確的用戶名和密碼點擊提交登錄進入到登錄頁面
image-20201029000058759
點擊update或者add,會提示未授權
image-20201029000348501

2. 撰寫未授權頁面

我們撰寫一個未授權頁面,當沒有權限時,跳轉到該頁面

MyController中添加未授權頁面跳轉的controller,即未授權跳轉到該請求顯示字串

@RequestMapping("/unauthorized")
@ResponseBody
public String unauthorized() {
    return "未授權,無法訪問此頁面";
}

然后同樣在shiroFilterFactoryBean方法中設定未授權頁面的請求

//設定未授權頁面的請求
bean.setUnauthorizedUrl("/unauthorized");

啟動測驗一下,同樣按照剛才的測驗,則跳轉到未授權頁面

3. 給用戶授予權限

我們上述設定了權限,但是還沒有給用戶賦予對應的權限,我們接下來在UserRealm的授權方法中進行授權

這里是給了所有的用戶都賦予user:add的權限

//授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("執行了=>授權doGetAuthorizationInfo");
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.addStringPermission("user:add");
    return info;
}

我們重啟訪問,成功登錄后可以訪問/add頁面

但是對用戶的授權不應該放在此,應該設定在資料庫中,我們給user表新增一個欄位perms,用于表示用戶的權限資訊
image-20201029125319919

image-20201029125332575

然后給不同的用戶添加不同的權限

image-20201029125411565 然后同步物體類
package com.zsr.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String perms;
}

然后我們需要在授權方法中拿到當前用戶的資源,這時候只需要將認證方法中的principal引數傳入,即可取出

package com.zsr.config;

import com.zsr.pojo.User;
import com.zsr.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
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.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserServiceImpl userService;

    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("執行了=>授權doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //獲取當前subject
        Subject subject = SecurityUtils.getSubject();
        //通過subject獲取當前user
        User CurrentUser = (User) subject.getPrincipal();
        //設定當前user的權限(從資料庫中讀取)
        info.addStringPermission(CurrentUser.getPerms());
        return info;
    }

    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("執行了=>認證doGetAuthorizationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //連接真實的資料庫
        User user = userService.queryUserByName(token.getUsername());
        //用戶名認證
        if (user == null)
            return null;//只需要return null,就會自動拋出UnknownAccountException一場
        //密碼認證(md5加密,md5鹽值加密),涉及到安全問題,shiro自動完成
        return new SimpleAuthenticationInfo(user, user.getPwd(), "zsr");
    }
}

重啟測驗一下,我們登錄zsr用戶,可以成功進入add頁面,無法進入update頁面
image-20201029164847279
image-20201029164912713
如果登錄gcc用戶,則兩個頁面都沒有權限

如果登錄BaretH用戶,可以成功進入update頁面,無法進入add頁面



六、Shiro整合thymeleaf

如果我們想實作在首頁,擁有對應權限的用戶只顯示對應的超鏈接

這時候就可以通過Thymeleaf來完成,

1. 匯入依賴

<!-- 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配置類ShiroConfig中撰寫對應的配置

//配式shiro整合thymeleaf
@Bean
public ShiroDialect shiroDialect() {
    return new ShiroDialect();
}

3. 修改index.html

我們要實作在首頁,擁有對應權限的用戶只顯示對應的超鏈接,然后添加一個登錄按鈕

首先匯入shiro的命名空間

xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
	<h1>首頁</h1>
    <p>
        <a th:href="@{/login}">登錄</a>
    </p>
    <p th:text="${msg}"></p>
    <hr>
    <div shiro:hasPermission="user:add">
        <a th:href="@{/user/add}">add</a>
    </div>
    <div shiro:hasPermission="user:update">
        <a th:href="@{/user/update}">update</a>
    </div>
</body>
</html>

重啟測驗,訪問http://localhost:8080/
image-20201029171204221
由于當前未登錄,所以兩個跳轉鏈接都不顯示;我們點擊登錄zsr用戶
image-20201029171248798
可以看到只顯示add鏈接
image-20201029171318884
同樣,如果我們登錄gcc用戶,則兩個都不顯示
image-20201029171359293
如果我們登錄BaretH用戶,則只顯示update鏈接
image-20201029171434976
如果我們還想實作如果登錄成功就不顯示登錄鏈接了呢?

我們可以用session來完成,當用戶登錄后,將其session存入,然后前端判斷session是否為空來顯示

//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("執行了=>認證doGetAuthorizationInfo");
    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
    //連接真實的資料庫
    User user = userService.queryUserByName(token.getUsername());
    //用戶名認證
    if (user == null)
        return null;//只需要return null,就會自動拋出UnknownAccountException一場
    //將用戶資訊存入session
    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession();
    session.setAttribute("loginUser",user);
    //密碼認證(md5加密,md5鹽值加密),涉及到安全問題,shiro自動完成
    return new SimpleAuthenticationInfo(user, user.getPwd(), "zsr");
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
<h1>首頁</h1>
<p th:if="${session.loginUser}==null">
    <a th:href="@{/login}">登錄</a>
</p>
<p th:text="${msg}"></p>
<hr>

<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">update</a>
</div>

</body>
</html>

再次測驗,登陸成功后不顯示登錄連接了
image-20201029173704627

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/204145.html

標籤:python

上一篇:Python編程基礎02:Python基本語法

下一篇:【TCP/IP】圖解TCP的通信機制

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more