主頁 >  其他 > SpringBoot整合Shiro安全框架完整實作

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

2020-11-06 09:01:29 其他


目錄

  • 一、環境搭建
    • 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/qita/204204.html

標籤:其他

上一篇: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)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more