搜尋
首頁Javajava教程SpringBoot安全管理之Shiro框架怎麼使用

SpringBoot安全管理之Shiro框架怎麼使用

May 10, 2023 pm 05:49 PM
springbootshiro

Shiro 簡介

Apache Shiro 是一個開源的輕量級的 Java 安全框架,它提供身份驗證、授權、密碼管理以及會話管理等功能。相對於 Spring Security ,Shiro 框架更加直覺、易用,同時也能提供健壯的安全性。

在傳統的SSM 框架中,手動整合Shiro 的配置步驟還是比較多的,針對Spring Boot ,Shiro 官方提供了shiro-spring-boot-web-starter 用來簡化Shiro 在Spring Boot 中的配置。

整合Shiro

1. 建立項目

首先建立一個普通的Spring Boot Web 項目,加入Shiro 依賴以及頁面模板依賴

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring-boot-web-starter</artifactId>
  <version>1.4.0</version>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
  <groupId>com.github.theborakompanioni</groupId>
  <artifactId>thymeleaf-extras-shiro</artifactId>
  <version>2.0.0</version>
</dependency>

這裡不需要加入spring-boot-starter-web 依賴,shiro-spring-boot-web-starter 中已經依賴了spring-boot-starter-web 。同時,此處使用 Thymeleaf 模板,為了在 Thymeleaf 使用 shiro 標籤,加入了 thymeleaf-extras-shiro 依賴。

2. Shiro基本配置

在application.properties 中配置Shiro 的基本資訊

# 開啟Shiro 配置,預設為true
shiro.enabled =true
# 開啟Shiro Web 配置,預設為true
shiro.web.enabled=true
# 設定登入位址,預設為/login.jsp
shiro.loginUrl=/login
# 配置登入成功的位址,預設為/
shiro.successUrl=/index
# 未獲授權預設跳轉位址
shiro.unauthorizedUrl=/unauthorized
# 是否允許透過URL 參數實現會話跟踪,如果網站支援Cookie,可以關閉此選項,預設為true
shiro.sessionManager.sessionIdUrlRewritingEnabled=true
# 是否允許透過Cookie 實現會話跟踪,預設為true
shiro.sessionManager.sessionIdCookieEnabled=true

然後在Java 程式碼中設定Shiro ,提供兩個最基本的Bean 即可

@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm() {
        TextConfigurationRealm realm = new TextConfigurationRealm();
        realm.setUserDefinitions("sang=123,user\n admin=123,admin");
        realm.setRoleDefinitions("admin=read,write\n user=read");
        return realm;
    }
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition =
                new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/login", "anon");
        chainDefinition.addPathDefinition("/doLogin", "anon");
        chainDefinition.addPathDefinition("/logout", "logout");
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}

程式碼解釋:

  • 這裡提供兩個關鍵的Bean ,一個是Realm,另一個是ShiroFilterChainDefinition 。至於ShiroDialect 則是為了支持在Thymeleaf 中使用Shiro 標籤,如果不在Thymeleaf 中使用Shiro 標籤,那麼可以不提供ShiroDialect

  • #Realm 可以是自訂的Realm,也可以是Shiro提供的Realm,簡單起見,此處沒有配置資料庫連接,直接配置了兩個使用者:sang/123 和admin/123 ,分別對應角色user 和admin。

  • ShiroFilterChainDefinition Bean 中配置了基本的過濾規則,“/login” 和“/doLogin”,可以匿名訪問,“/logout”是一個註銷登錄請求,其餘請求則都需要認證後才能存取

然後配置登入介面以及頁面存取介面

@Controller
public class UserController {
    @PostMapping("/doLogin")
    public String doLogin(String username, String password, Model model) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            model.addAttribute("error", "用户名或密码输入错误!");
            return "login";
        }
        return "redirect:/index";
    }
    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin() {
        return "admin";
    }
    @RequiresRoles(value = {"admin", "user"}, logical = Logical.OR)
    @GetMapping("/user")
    public String user() {
        return "user";
    }
}

程式碼解釋:

  • ##在doLogin 方法中,先建立一個UsernamePasswordToken 實例,然後取得一個Subject 物件並呼叫該物件中的login 方法執行登入操作,在登入操作執行過程中,當有異常拋出時,說明登入失敗,攜帶錯誤訊息返回登入視圖;當登入成功時,則重定向到“/index”

  • 接下來暴露兩個接口“/admin”和“/user”,對於“/admin”接口,需要具有admin 角色才可以存取;對於「/user」接口,具備admin 角色和user角色其中任何一個即可訪問

對於其他不需要角色就能訪問的接口,直接在WebMvc 中配置即可

@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/unauthorized").setViewName("unauthorized");
    }
}

接下來建立全域異常處理器進行全域異常處理,此處主要是處理授權異常

@ControllerAdvice
public class ExceptionController {
    @ExceptionHandler(AuthorizationException.class)
    public ModelAndView error(AuthorizationException e) {
        ModelAndView mv = new ModelAndView("unauthorized");
        mv.addObject("error", e.getMessage());
        return mv;
    }
}

當使用者存取未授權的資源時,跳到unauthorized 檢視中,並攜帶出錯誤訊息。

設定完成後,最後在 resources/templates 目錄下建立 5 個 HTML 頁面進行測試。

(1)index.html

<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h4 id="Hello-nbsp-shiro-principal">Hello, <shiro:principal/></h4>
<h4 id="a-nbsp-href-logout-nbsp-rel-external-nbsp-nofollow-nbsp-注销登录-a"><a href="/logout" rel="external nofollow" >注销登录</a></h4>
<h4 id="a-nbsp-shiro-hasRole-admin-nbsp-href-admin-nbsp-rel-external-nbsp-nofollow-nbsp-管理员页面-a"><a shiro:hasRole="admin" href="/admin" rel="external nofollow" >管理员页面</a></h4>
<h4 id="a-nbsp-shiro-hasAnyRoles-admin-user-nbsp-href-user-nbsp-rel-external-nbsp-nofollow-nbsp-普通用户页面-a"><a shiro:hasAnyRoles="admin,user" href="/user" rel="external nofollow" >普通用户页面</a></h4>
</body>
</html>

(2)login.html

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

(3)user.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2 id="普通用户页面">普通用户页面</h2>
</body>
</html>

(4)admin. html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2 id="管理员页面">管理员页面</h2>
</body>
</html>

(5)unauthorized.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <h4 id="未获授权-非法访问">未获授权,非法访问</h4>
    <h4 th:text="${error}"></h4>
</div>
</body>
</html>

3. 測試

啟動項目,造訪登入頁面,使用sang/123 登入

SpringBoot安全管理之Shiro框架怎麼使用

#注意:由於sang 使用者不具備admin 角色,因此登入成功後的頁面沒有前往管理員頁面的超連結。

然後使用 admin/123 登入。

SpringBoot安全管理之Shiro框架怎麼使用

如果使用者使用sang 登錄,然後去存取:http://localhost:8080/admin,會跳到未授權頁面

SpringBoot安全管理之Shiro框架怎麼使用

以上是SpringBoot安全管理之Shiro框架怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
Java平台是否獨立,如果如何?Java平台是否獨立,如果如何?May 09, 2025 am 12:11 AM

Java是平台獨立的,因為其"一次編寫,到處運行"的設計理念,依賴於Java虛擬機(JVM)和字節碼。 1)Java代碼編譯成字節碼,由JVM解釋或即時編譯在本地運行。 2)需要注意庫依賴、性能差異和環境配置。 3)使用標準庫、跨平台測試和版本管理是確保平台獨立性的最佳實踐。

關於Java平台獨立性的真相:真的那麼簡單嗎?關於Java平台獨立性的真相:真的那麼簡單嗎?May 09, 2025 am 12:10 AM

Java'splatFormIndenceIsnotsimple; itinvolvesComplexities.1)jvmcompatiblemustbebeeniblemustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)

Java平台獨立性:Web應用程序的優勢Java平台獨立性:Web應用程序的優勢May 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM解釋:Java虛擬機的綜合指南JVM解釋:Java虛擬機的綜合指南May 09, 2025 am 12:04 AM

thejvmistheruntimeenvorment forexecutingjavabytecode,Cocucialforjava的“ WriteOnce,RunanyWhere”能力

Java的主要功能:為什麼它仍然是頂級編程語言Java的主要功能:為什麼它仍然是頂級編程語言May 09, 2025 am 12:04 AM

JavaremainsatopchoicefordevelopersduetoitsplatFormentence,對象與方向設計,強度,自動化的MememoryManagement和ComprechensivestAndArdArdArdLibrary

Java平台獨立性:這對開發人員意味著什麼?Java平台獨立性:這對開發人員意味著什麼?May 08, 2025 am 12:27 AM

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允許univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

如何為第一次使用設置JVM?如何為第一次使用設置JVM?May 08, 2025 am 12:21 AM

要設置JVM,需按以下步驟進行:1)下載並安裝JDK,2)設置環境變量,3)驗證安裝,4)設置IDE,5)測試運行程序。設置JVM不僅僅是讓其工作,還包括優化內存分配、垃圾收集、性能調優和錯誤處理,以確保最佳運行效果。

如何查看產品的Java平台獨立性?如何查看產品的Java平台獨立性?May 08, 2025 am 12:12 AM

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中