目錄
- 一、環境搭建
- 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
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 Web和Thymeleaf
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.html和update.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

點擊add即可跳轉到add.html,點擊update即可跳轉到update.html
2. 實作登錄攔截
在shiro配置類中,我們創建了三個物件,要實作登錄攔截功能,就要用到shiro過濾工廠物件
我們在配置類
ShiroConfig的shiroFilterFactoryBean()方法中添加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請求需要認證才能訪問


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則會跳轉到登陸頁面,成功~

三、Shiro實作用戶認證
上述創建Realm物件中,我們繼承了
AuthorizingRealm類,重寫了其兩個方法,shiro實作用戶認證的功能,也就是在其中的認證方法doGetAuthenticationInfo中完成的,我們來測驗測驗同官方案例的
Quickstart原始碼一樣,可以看我的上一篇博客:Shiro第一個程式:官方快速入門程式Qucickstart詳解教程實作用戶認證有幾個步驟:
- 獲取當前用戶
- 封裝用戶資訊生成token令牌
- 執行登錄操作(可以自定義捕獲例外)
我們將這些代碼撰寫在一個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

隨便輸入用戶名密碼,然后點擊登錄,可以看到顯示用戶名不存在
同時查看控制臺資訊

發現執行了自定義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");
}
再次重啟測驗一下,輸入錯誤的用戶名和密碼

顯示用戶不存在

如果輸入正確的用戶名和錯誤的密碼

則會顯示密碼不正確

如果輸入正確的用戶名和密碼

則成功登錄到首頁

四、整合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連接該資料庫并打開


資料表

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包,其中新建UserService和UserServiceImpl兩個類
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"));
}
}
運行測驗一下,成功查到指定用戶

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");
}
}
然后再次重啟主程式進行測驗,進入到登錄頁面,只要輸入資料庫中正確的用戶名和密碼即可實作登錄



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

輸入正確的用戶名和密碼點擊提交登錄進入到登錄頁面

點擊update或者add,會提示未授權

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,用于表示用戶的權限資訊

然后給不同的用戶添加不同的權限
然后同步物體類
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頁面


如果登錄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/

由于當前未登錄,所以兩個跳轉鏈接都不顯示;我們點擊登錄zsr用戶

可以看到只顯示add鏈接

同樣,如果我們登錄gcc用戶,則兩個都不顯示

如果我們登錄BaretH用戶,則只顯示update鏈接

如果我們還想實作如果登錄成功就不顯示登錄鏈接了呢?
我們可以用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>
再次測驗,登陸成功后不顯示登錄連接了

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

