Shrio 安全框架

目錄

前言

1.介紹

2.整合 Shiro 到 Spring Boot

3.Shiro 相關配置

總結


前言

幾乎所有涉及用戶的系統都需要進行權限管理,權限管理涉及到一個系統的安全。Spring Boot 的安全框架整合方案中還有一個璀璨的明珠:Shrio。


1.介紹

Shiro是一款由Java 編寫的安全框架,功能強大,入手容易。Shiro 提供了一套完的RABC模式的授權認證體系,可以對密碼進行加密,并完成安全的會話管理。與SpringSecurity 相比顯得功能較少,但是對于追求“小而美”的解決方案的開發者和項目來說Shiro使用起來更加得心應手。?

  1. 用于身份驗證以及登錄,檢查用戶是否擁有相應的角色權限。
  2. 進行權限驗證,驗證某個已登錄認證的用戶是否擁有某個具體的角色權限; 常的如:檢驗某個用戶是否有對某些資源包括頁面的訪問和操作權限等。
  3. 進行會話管理,每當用戶登錄就是一次會話,在沒有退出賬號登錄之前,用戶的所有信息都在會話中存儲。
  4. 對數據加密,保護數據的安全性,如密碼加密存儲到數據庫,不是明文存儲,更加安全。
  5. 對Web 支持,非常方便地集成到 Web 環境中
  6. 支持多線程并發驗證。?

這里介紹 Shiro 的一些核心的概念,Shiro 主要由三部分組成:?

  1. Subject: 主體,外部應用會和 Subject 進行交互。Subject 會記錄當前的用戶,用在這里就是 Subject (主體),比如通過瀏覽器進行請求的用戶。而 Subject 要通過 SecurityManager 進行認證授權。在代碼層面,Subject 是一個定義了一些授權方法的接口 。
  2. Security Manager: 即安全管理器,它是 Shiro 的核心,將對所有的 Subject 進行安全管理。從代碼層面上來說,Security Manager 是一個多繼承接口,繼承了Authenticator、Authorizer、SessionManager 這三個接口。
  3. Realm:是 Shiro 和安全應用之間的連接器,類似于一個安全相關的 DAO,在進行認證和授權時,Shiro 會從 Realm 中獲取想要的數據

2.整合 Shiro 到 Spring Boot

新建一個 SpringBoot 項目 ,在 pom.xml 中添加如下配置:

        <dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring-boot-web-starter</artifactId><version>1.7.0</version></dependency>

3.Shiro 相關配置

在 applcation.yml 中編寫相關配置。

shiro:# 開啟 Shrio 配置,默認為 trueenabled: trueweb:#開啟 Shrio Web 配置,默認為 trueenabled: true#配置登錄地址,默認為"login.jsp"loginUrl: /login#配置登錄成功地址 默認為 /successUrl: /index# 配置未獲取授權默認跳轉地址unauthorizedUrl: /unauthorizedsessionManager:# 是否允許通過 Cookie,實現會話跟蹤,默認為 true。sessionIdCookieEnabled: true#是否允許通過 URL 參數實現會話跟蹤,默認為 true,如果網站支持 Cookie,可以關閉此選項
# thymeleaf
spring:thymeleaf:prefix: classpath:templates/suffix: .htmlmode: HTMLencoding: UTF-8cache: false # 對于開發,最好禁用緩存

編寫 ShiroConfig 文件,具體代碼如下:

package org.example.config;import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.realm.text.TextConfigurationRealm;
@Configuration
public class ShiroConfig {@Beanpublic Realm realm(){TextConfigurationRealm realm = new TextConfigurationRealm();realm.setUserDefinitions("freephp=123456,user\n admin=123456,admin");realm.setRoleDefinitions("user=read\n admin=read,write");return  realm;}@Beanpublic ShiroFilterChainDefinition shiroFilterChainDefinition(){DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();chainDefinition.addPathDefinition("/logout","logout");chainDefinition.addPathDefinition("/login","anon");//匿名訪問chainDefinition.addPathDefinition("/doLogin","anon");//匿名訪問chainDefinition.addPathDefinition("/**","authc");return chainDefinition;}
}

上面的代碼中有兩個方法,一個是 realm 方法,另一個是 shiroFilterChainDefinition 方法。realm 方法用于獲取權限認證數據,例如此處存儲了兩個賬號:freephp 和 admin。

然后再編寫 Controller 文件,只做簡單的邏輯判斷,代碼如下:

package org.example.controller;import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class UserController {@RequestMapping("/doLogin")public String doLogin(String username, String password, Model model){System.out.println("userName is"+username);UsernamePasswordToken token = new UsernamePasswordToken(username,password);Subject subject = SecurityUtils.getSubject();try {subject.login(token);return "index";}catch (AuthenticationException e){System.out.println(e.getCause());model.addAttribute("error","Username or Password is wrong!");return "login";}}@GetMapping("/admin")public String admin(){return "admin";}@GetMapping("/user")public String user(){return "user";}}

上面的代碼定義了三個接口,其中 doLogin 用于登錄,使用 UsernamePasswordToken 類創建 token。然后根據賬號和密碼進行匹配判斷,如果驗證失敗則返回 /dologin 頁面并顯示錯誤提示,如果驗證成功則可以訪問 index 頁面。

登錄頁面和首頁頁面都需要單獨編寫,在 resources 目錄下創建 templates 文件夾,然后分別創建 index.html 和 login.html。

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
hi,test
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Login</title>
</head>
<body>
<form action="/doLogin" method="post"><label>username:</label><input type="text" name="username"><br/><label>password:</label><input type="text" name="password"><br/><div th:text>${error}</div><input type="submit" value="登錄"/></form>
</body>
</html>

為了更好的加載上面的頁面,編寫一個 WebMvcConfig 來加載:

package org.example.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("index").setViewName("index");registry.addViewController("login").setViewName("login");}
}

訪問之后,輸入正確的賬號和密碼,則可以看到登錄成功的頁面,反之則提示登錄失敗。


總結

Shiro 的使用非常方便,只需實現最核心的 realm 定義和 shiroFilterChainDefinition 功能就可以很好地完成認證授權功能。除此之外,Shiro 還提供緩存功能,感興趣的同學可以自行查閱官方文檔進行學習。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/208207.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/208207.shtml
英文地址,請注明出處:http://en.pswp.cn/news/208207.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

信道復用技術

目錄 一、頻分復用FDM&#xff08;Frequency Division Multiplexing&#xff09; 二、波分復用 WDM&#xff08;Wavelength Division Multiplexing&#xff09; 三、時分復用TDM&#xff08;Time Division Multiplexing&#xff09; 四、統計時分復用 STDM&#xff08;Statisti…

雙通道5V高細分步進電機驅動芯片應用于搖頭機,X,Y控制,聚焦控制,CAMERA云臺控制等產品上的芯片選型分析

雙通道5V高細分步進電機驅動芯片GC6106&#xff0c;GC6107&#xff0c;GC6119&#xff0c;GC6151&#xff0c;GC6236&#xff0c;GC6225&#xff0c;GC6129&#xff0c;電壓范圍3~5.5V&#xff0c;最大持續電流可達0.6A左右。可應用于搖頭機&#xff0c;X,Y控制&#xff0c;聚焦…

安裝vue環境

1.Hello Vue.js <script src"https://cdn.staticfile.org/vue/2.7.0/vue.min.js"></script>/*引入js文件 */ <script> new Vue({ /* 創建一個對象&#xff0c;兩個屬性。 */ el: #app, data: { message: Hello Vue.js! }, methods: { details: f…

C++使用模板的注意事項

兩點注意事項 自動推導類型&#xff0c;必須推導出一致的數據類型T&#xff0c;才可以使用模板必須要確定出T的數據類型&#xff0c;才可以使用 #include<iostream> using namespace std;//第一點必須一致的數據類型 template <class T> void myswap(T& a, T…

基于AIS數據的船舶密度計算與規律研究

參考文獻&#xff1a;[1]陳曉. 基于AIS數據的船舶密度計算與規律研究[D].大連海事大學,2021.DOI:10.26989/d.cnki.gdlhu.2020.001129. 謝謝姐姐的文章&#xff01; 網格化AIS數據 網格化 AIS 數據是處理和分析船舶軌跡數據的一種有效方法&#xff0c;特別是當涉及到密度計算和…

C++_對C數據類型的擴展

結構體 c中定義結構體變量&#xff0c;可以省略struct關鍵字 c結構提重可以直接定義函數&#xff0c;謂之成員函數&#xff08;方法&#xff09; #include <iostream> using namespace std; struct stu {int num;char name[24];void price(void) {cout << "…

Vue3+Antd實現彈框顯示內容并加入復制按鈕

使用Vue3antd實現點擊彈框出現內容并可復制內容的功能&#xff1a; HTML部分&#xff1a; <a-button type"primary" click"showModel">打開彈框 </a-button><!-- ok 是彈框中確定按鈕的操作&#xff0c;cancel 是彈框中取消按鈕的操作 --…

Redis數據已經刪除了,為什么內存占用還是很高?

Redis數據已經刪除了&#xff0c;為什么內存占用還是很高&#xff1f; Redis做了數據刪除操作&#xff0c;為什么使用top命令時&#xff0c;還是顯示Redis占了很多內存&#xff1f; 沒做相關功課的人覺得這個問題有問題&#xff0c;刪了數據還說占著內存&#xff0c;面試官不…

【學一點兒前端】真機調試本地公眾號網頁項目

前言 微信公眾號網頁開發的真機調試一直是很頭疼的事情。 原因一 微信公眾號配置的JS安全域名只有三個&#xff0c;一個大中型的公眾號這三個JS安全域名都是生產的域名&#xff0c;不可能預留域名用于開發和調試。 原因二 在微信里面只有訪問正確的安全域名才能調用wx.config用…

vuepress-----18、圖片縮放

圖片引入兩種方式 地址 # 圖片縮放插件 # 實戰 md文件引入圖片 <img class"zoom-custom-imgs" :src"$withBase(/favicon.ico)" alt"favicon">安裝配置插件 vuepress/medium-zoom: {selector: img.zoom-custom-imgs,},效果展示

AI:89-基于卷積神經網絡的遙感圖像地物分類

?? 本文選自專欄:人工智能領域200例教程專欄 從基礎到實踐,深入學習。無論你是初學者還是經驗豐富的老手,對于本專欄案例和項目實踐都有參考學習意義。 ??? 每一個案例都附帶有在本地跑過的核心代碼,詳細講解供大家學習,希望可以幫到大家。歡迎訂閱支持,正在不斷更新…

MVCC是什么

程序員的公眾號&#xff1a;源1024&#xff0c;獲取更多資料&#xff0c;無加密無套路&#xff01; 最近整理了一波電子書籍資料&#xff0c;包含《Effective Java中文版 第2版》《深入JAVA虛擬機》&#xff0c;《重構改善既有代碼設計》&#xff0c;《MySQL高性能-第3版》&…

ChibiOS簡介1/5

ChibiOS簡介1/5 1. 源由2. ChibiOS基礎知識1/52.1 Chapter 1 - Introduction2.1.1 Priciple&#xff08;設計原則&#xff09;2.1.2 Fundamental requirements&#xff08;基本需求&#xff09; 2.2 Chapter 2 - Real Time Systems Concepts2.2.1 System&#xff08;系統&#…

flutter TextPainter 的用法

本文章基于 Flutter 3.16.2 Dart SDK 3.2.2。 TextPainter 是 Flutter 中用于在 Canvas 上繪制文本的類。它允許您在自定義的 CustomPainter 中使用 drawText 方法來繪制文本&#xff0c;并可以控制文本的位置、顏色、字體等屬性。 import package:flutter/material.dart;cla…

【NEON】學習資料匯總

一、資料鏈接 Guide &#xff1a; http://www.heenes.de/ro/material/arm/DEN0018A_neon_programmers_guide_en.pdf csdn博文1&#xff0c;基礎案例&#xff1a; https://blog.csdn.net/kakasxin/article/details/103912832? csdn博文2&#xff0c;內部函數&#xff1a; ht…

css 輸入框動態特效

先上圖 代碼 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>css 輸入框動效</title><style>.inputBox {position: relative;width: 250px;}.inputBox input {width: 100%;padding: 10px…

使用git push太慢怎么辦

使用git push太慢怎么辦 修改host文件&#xff1a; windows 的路徑應該在 C:\Windows\System32\drivers\etc\hosts 在host文件的最后一行加上 151.101.72.249 github.global.ssl.fastly.nethost不允許修改就復制一份&#xff0c;修改好了再替換掉&#xff0c;可能會讓你輸入…

028:簡單的foreach

028:簡單的foreach 總時間限制: 1000ms 內存限制: 65536kB 描述 編寫MyForeach模板&#xff0c;使程序按要求輸出 不得編寫 MyForeach函數 #include <iostream> #include <string> using namespace std; // 在此處補充你的代碼 void Print(string s) {cout <…

【面試經典150 | 二叉樹】對稱二叉樹

文章目錄 寫在前面Tag題目來源解題思路方法一&#xff1a;遞歸方法二&#xff1a;迭代 寫在最后 寫在前面 本專欄專注于分析與講解【面試經典150】算法&#xff0c;兩到三天更新一篇文章&#xff0c;歡迎催更…… 專欄內容以分析題目為主&#xff0c;并附帶一些對于本題涉及到的…

第6講、Hyper-V體系結構和相關管理程序文件及服務:

1、Hyper-V的體系結構 1、CPU能力在服務器虛擬化實現中扮演著一個重要角色&#xff0c;Intel/AMD型號的CPU定義了一些權限 級別&#xff0c;稱為ring。在傳統模型中&#xff0c;ring0級別最高權限最大。Windows內核和設備驅動程序 使用這個級別…