目錄
Shiro 簡介
整合Shiro
1. 建立項目
2. Shiro基本配置
Hello, 
注销登录" >注销登录
管理员页面" >管理员页面
普通用户页面" >普通用户页面
普通用户页面
管理员页面
未获授权,非法访问
首頁 Java java教程 SpringBoot安全管理之Shiro框架怎麼使用

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

May 10, 2023 pm 05:49 PM
springboot shiro

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

熱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

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Springboot怎麼整合Jasypt實現設定檔加密 Springboot怎麼整合Jasypt實現設定檔加密 Jun 01, 2023 am 08:55 AM

Jasypt介紹Jasypt是一個java庫,它允許開發員以最少的努力為他/她的專案添加基本的加密功能,並且不需要對加密工作原理有深入的了解用於單向和雙向加密的高安全性、基於標準的加密技術。加密密碼,文本,數字,二進位檔案...適合整合到基於Spring的應用程式中,開放API,用於任何JCE提供者...添加如下依賴:com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt好處保護我們的系統安全,即使程式碼洩露,也可以保證資料來源的

SpringBoot怎麼整合Redisson實現延遲隊列 SpringBoot怎麼整合Redisson實現延遲隊列 May 30, 2023 pm 02:40 PM

使用場景1、下單成功,30分鐘未支付。支付超時,自動取消訂單2、訂單簽收,簽收後7天未進行評估。訂單超時未評價,系統預設好評3、下單成功,商家5分鐘未接單,訂單取消4、配送超時,推播簡訊提醒…對於延時比較長的場景、即時性不高的場景,我們可以採用任務調度的方式定時輪詢處理。如:xxl-job今天我們採

怎麼在SpringBoot中使用Redis實現分散式鎖 怎麼在SpringBoot中使用Redis實現分散式鎖 Jun 03, 2023 am 08:16 AM

一、Redis實現分散式鎖原理為什麼需要分散式鎖在聊分散式鎖之前,有必要先解釋一下,為什麼需要分散式鎖。與分散式鎖相對就的是單機鎖,我們在寫多執行緒程式時,避免同時操作一個共享變數產生資料問題,通常會使用一把鎖來互斥以保證共享變數的正確性,其使用範圍是在同一個進程中。如果換做是多個進程,需要同時操作一個共享資源,如何互斥?現在的業務應用通常是微服務架構,這也意味著一個應用會部署多個進程,多個進程如果需要修改MySQL中的同一行記錄,為了避免操作亂序導致髒數據,此時就需要引入分佈式鎖了。想要實現分

springboot讀取檔案打成jar包後存取不到怎麼解決 springboot讀取檔案打成jar包後存取不到怎麼解決 Jun 03, 2023 pm 04:38 PM

springboot讀取文件,打成jar包後訪問不到最新開發出現一種情況,springboot打成jar包後讀取不到文件,原因是打包之後,文件的虛擬路徑是無效的,只能通過流去讀取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現 Springboot+Mybatis-plus不使用SQL語句進行多表新增怎麼實現 Jun 02, 2023 am 11:07 AM

在Springboot+Mybatis-plus不使用SQL語句進行多表添加操作我所遇到的問題準備工作在測試環境下模擬思維分解一下:創建出一個帶有參數的BrandDTO對像模擬對後台傳遞參數我所遇到的問題我們都知道,在我們使用Mybatis-plus中進行多表操作是極其困難的,如果你不使用Mybatis-plus-join這一類的工具,你只能去配置對應的Mapper.xml文件,配置又臭又長的ResultMap,然後再寫對應的sql語句,這種方法雖然看上去很麻煩,但具有很高的靈活性,可以讓我們

SpringBoot怎麼自訂Redis實作快取序列化 SpringBoot怎麼自訂Redis實作快取序列化 Jun 03, 2023 am 11:32 AM

1.自訂RedisTemplate1.1、RedisAPI預設序列化機制基於API的Redis快取實作是使用RedisTemplate範本進行資料快取操作的,這裡開啟RedisTemplate類,查看該類別的源碼資訊publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations,BeanClassLoaderAware{//聲明了value的各種序列化方式,初始值為空@NullableprivateRedisSe

SpringBoot與SpringMVC的比較及差別分析 SpringBoot與SpringMVC的比較及差別分析 Dec 29, 2023 am 11:02 AM

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

SpringBoot+Dubbo+Nacos 開發實戰教程 SpringBoot+Dubbo+Nacos 開發實戰教程 Aug 15, 2023 pm 04:49 PM

本文來寫個詳細的例子來說下dubbo+nacos+Spring Boot開發實戰。本文不會講述太多的理論的知識,會寫一個最簡單的例子來說明dubbo如何與nacos整合,快速建構開發環境。

See all articles