spring boot 2 + shiro 實現簡單的身份驗證例子

来源:https://www.cnblogs.com/gdjlc/archive/2019/12/08/12006635.html
-Advertisement-
Play Games

Shiro是一個功能強大且易於使用的Java安全框架,主要功能有身份驗證、授權、加密和會話管理,本文實現一個簡單的身份驗證例子。 ...


Shiro是一個功能強大且易於使用的Java安全框架,官網:https://shiro.apache.org/。

主要功能有身份驗證、授權、加密和會話管理。
其它特性有Web支持、緩存、測試支持、允許一個用戶用另一個用戶的身份進行訪問、記住我。

Shiro有三個核心組件:Subject,SecurityManager和 Realm。

Subject:即當前操作“用戶”,“用戶”並不僅僅指人,也可以是第三方進程、後臺帳戶或其他類似事物。
SecurityManager:安全管理器,Shiro框架的核心,通過SecurityManager來管理所有Subject,並通過它來提供安全管理的各種服務。
Realm:域,充當了Shiro與應用安全數據間的“橋梁”或者“連接器”。也就是說,當對用戶執行認證(登錄)和授權(訪問控制)驗證時,Shiro會從應用配置的Realm中查找用戶及其許可權信息。當配置Shiro時,必須至少指定一個Realm,用於認證和(或)授權。

Spring Boot 中整合Shiro,根據引入的依賴包shiro-springshiro-spring-boot-web-starter(當前版本都是1.4.2)不同有兩種不同方法。

方法一:引入依賴包shiro-spring

1、IDEA中創建一個新的SpringBoot項目,pom.xml引用的依賴包如下:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.2</version>
        </dependency>
        

2、創建Realm和配置shiro

(1)創建Realm

package com.example.demo.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyRealm extends AuthorizingRealm {

    /**許可權信息,暫不實現*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**身份認證:驗證用戶輸入的賬號和密碼是否正確。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //獲取用戶輸入的賬號
        String userName = (String) token.getPrincipal();
        //驗證用戶admin和密碼123456是否正確
        if (!"admin".equals(userName)) {
            throw new UnknownAccountException("賬戶不存在!");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName, "123456", getName());
        return authenticationInfo;
        //實際項目中,上面賬號從資料庫中獲取用戶對象,再判斷是否存在
        /*User user = userService.findByUserName(userName);
        if (user == null) {
            throw new UnknownAccountException("賬戶不存在!");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(), getName());
        return authenticationInfo;
        */
    }
}

(2)配置Shiro

package com.example.demo.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    MyRealm myRealm() {
        return new MyRealm();
    }

    @Bean
    DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm());
        return manager;
    }

    @Bean
    ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager());
        //如果不設置預設會自動尋找Web工程根目錄下的"/login.jsp"頁面
        bean.setLoginUrl("/login");
        //登錄成功後要跳轉的鏈接
        bean.setSuccessUrl("/index");
        //未授權界面
        bean.setUnauthorizedUrl("/403");
        //配置不會被攔截的鏈接
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/doLogin", "anon");
        map.put("/**", "authc");
        bean.setFilterChainDefinitionMap(map);
        return bean;
    }
}

3、控制器測試方法

package com.example.demo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @GetMapping("/login")
    public String  login() {
        return "登錄頁面...";
    }

    @PostMapping("/doLogin")
    public String doLogin(String userName, String password) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(userName, password));
            return "登錄成功!";
        } catch (UnknownAccountException e) {
            return e.getMessage();
        } catch (AuthenticationException e) {
            return "登陸失敗,密碼錯誤!";
        }
    }

    //如果沒有先登陸,訪問會跳到/login
    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/403")
    public String unauthorizedRole(){
        return "沒有許可權";
    }
}

方法二:引入依賴包shiro-spring-boot-web-starter

1、pom.xml中刪除shiro-spring,引入shiro-spring-boot-web-starter

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

2、創建Realm和配置shiro

(1)創建Realm,代碼和方法一的一樣。
(2)配置Shiro

package com.example.demo.config;

import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    @Bean
    MyRealm myRealm() {
        return new MyRealm();
    }

    @Bean
    DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm());
        return manager;
    }

    @Bean
    ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        definition.addPathDefinition("/doLogin", "anon");
        definition.addPathDefinition("/**", "authc");
        return definition;
    }
}

(3)application.yml配置

shiro:
  unauthorizedUrl: /403
  successUrl: /index
  loginUrl: /login

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 京東商品爬取 一.使用selenium 二.不使用selenium 三.個人感覺 `selenium真的慢 ` ...
  • 一、引入 首先我們看到的是 Thread 中有一個屬性 threadLocals,它的類型是 ThreadLocalMap,封裝類型是 default(表示它只能在包內可見),jdk 是這麼介紹它的:與此線程有關的 ThreadLocal 值,該映射由 ThreadLocal 類維護。 啥意思呢?那 ...
  • 開發工具: Eclipse, Tomcat, MySql 1. 登錄頁面登錄功能, 輸入用戶名與密碼, 選擇角色, 滑動箭頭拉到最右邊才可以點擊登錄 2. 學生角色登錄成功後,可以看到需要答題的試卷,有規定的答題時間(倒計時) 題目選擇完畢後,【提交答卷】可以立即看到分數, 然後查看試卷答案 3. ...
  • leetcode 237. 刪除鏈表中的節點 鏈接:https://leetcode-cn.com/problems/delete-node-in-a-linked-list/ 示例 : 輸入: head = [4,5,1,9], node = 5輸出: [4,1,9]解釋: 給定你鏈表中值為 5  ...
  • 本篇文章我們主要探討 一下如果 語句中有 ,這種情況下 語句還會執行嗎?其實JVM規範是對這種情況有特殊規定的,那我就先上代碼吧! 對於上述代碼,我們有以下幾個問題,來自測一下吧: 1. 如果在 try 語句塊里使用 return 語句,那麼 finally 語句塊還會執行嗎? 2. 如果執行,那麼 ...
  • 題目要求: 分析文件’課程成績.xlsx’,至少要完成內容:分析1)每年不同班級平均成績情況、2)不同年份總體平均成績情況、3)不同性別學生成績情況,並分別用合適的圖表展示出三個內容的分析結果。 廢話不多,直接上代碼 1每年不同班級平均成績情況: # 導入xlrd模塊import xlrdfrom ...
  • 前言本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。作者:weixin_45189038直接上知識點: 1. 註釋 單行註釋:在一行文字前面加#(快捷鍵:ctrl+/) 多行註釋:將註釋內容寫在三個英文雙引號或者單引號裡面(但是一 ...
  • 這個問題,是python與Pycharm不相容導致,解決辦法將Pycharm升級最新版本 ...
一周排行
    -Advertisement-
    Play Games
  • 基於.NET Framework 4.8 開發的深度學習模型部署測試平臺,提供了YOLO框架的主流系列模型,包括YOLOv8~v9,以及其系列下的Det、Seg、Pose、Obb、Cls等應用場景,同時支持圖像與視頻檢測。模型部署引擎使用的是OpenVINO™、TensorRT、ONNX runti... ...
  • 十年沉澱,重啟開發之路 十年前,我沉浸在開發的海洋中,每日與代碼為伍,與演算法共舞。那時的我,滿懷激情,對技術的追求近乎狂熱。然而,隨著歲月的流逝,生活的忙碌逐漸占據了我的大部分時間,讓我無暇顧及技術的沉澱與積累。 十年間,我經歷了職業生涯的起伏和變遷。從初出茅廬的菜鳥到逐漸嶄露頭角的開發者,我見證了 ...
  • C# 是一種簡單、現代、面向對象和類型安全的編程語言。.NET 是由 Microsoft 創建的開發平臺,平臺包含了語言規範、工具、運行,支持開發各種應用,如Web、移動、桌面等。.NET框架有多個實現,如.NET Framework、.NET Core(及後續的.NET 5+版本),以及社區版本M... ...
  • 前言 本文介紹瞭如何使用三菱提供的MX Component插件實現對三菱PLC軟元件數據的讀寫,記錄了使用電腦模擬,模擬PLC,直至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1. PLC開發編程環境GX Works2,GX Works2下載鏈接 https:// ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • 1、jQuery介紹 jQuery是什麼 jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之後又一個優秀的JavaScript代碼庫(或JavaScript框架)。jQuery設計的宗旨是“write Less,Do More”,即倡導寫更少的代碼,做更多的事情。它封裝 ...
  • 前言 之前的文章把js引擎(aardio封裝庫) 微軟開源的js引擎(ChakraCore))寫好了,這篇文章整點js代碼來測一下bug。測試網站:https://fanyi.youdao.com/index.html#/ 逆向思路 逆向思路可以看有道翻譯js逆向(MD5加密,AES加密)附完整源碼 ...
  • 引言 現代的操作系統(Windows,Linux,Mac OS)等都可以同時打開多個軟體(任務),這些軟體在我們的感知上是同時運行的,例如我們可以一邊瀏覽網頁,一邊聽音樂。而CPU執行代碼同一時間只能執行一條,但即使我們的電腦是單核CPU也可以同時運行多個任務,如下圖所示,這是因為我們的 CPU 的 ...
  • 掌握使用Python進行文本英文統計的基本方法,並瞭解如何進一步優化和擴展這些方法,以應對更複雜的文本分析任務。 ...
  • 背景 Redis多數據源常見的場景: 分區數據處理:當數據量增長時,單個Redis實例可能無法處理所有的數據。通過使用多個Redis數據源,可以將數據分區存儲在不同的實例中,使得數據處理更加高效。 多租戶應用程式:對於多租戶應用程式,每個租戶可以擁有自己的Redis數據源,以確保數據隔離和安全性。 ...