亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Springboot整合Shiro實現登錄與權限校驗詳細解讀

 更新時間:2022年04月27日 17:02:36   作者:全棧小定^.^  
本文給大家介紹Springboot整合Shiro的基本使用,Apache?Shiro是Java的一個安全框架,Shiro本身無法知道所持有令牌的用戶是否合法,我們將整合Shiro實現登錄與權限的驗證

Springboot-cli 開發(fā)腳手架系列

Springboot優(yōu)雅的整合Shiro進行登錄校驗,權限認證(附源碼下載)

簡介

Springboo配置Shiro進行登錄校驗,權限認證,附demo演示。

前言

我們致力于讓開發(fā)者快速搭建基礎環(huán)境并讓應用跑起來,提供使用示例供使用者參考,讓初學者快速上手。

本博客項目源碼地址:

項目源碼github地址

項目源碼國內gitee地址

1. 環(huán)境

依賴

     <!-- Shiro核心框架 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.9.0</version>
        </dependency>
        <!-- Shiro使用Spring框架 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.9.0</version>
        </dependency>
        <!-- Thymeleaf中使用Shiro標簽 -->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

yml配置

server:
  port: 9999
  servlet:
    session:
      # 讓Tomcat只能從COOKIE中獲取會話信息,這樣,當沒有Cookie時,URL也就不會被自動添加上 ;jsessionid=… 了。
      tracking-modes: COOKIE

spring:
  thymeleaf:
    # 關閉頁面緩存,便于開發(fā)環(huán)境測試
    cache: false
    # 靜態(tài)資源路徑
    prefix: classpath:/templates/
    # 網頁資源默認.html結尾
    mode: HTML
 

2. 簡介

Shiro三大功能模塊

  • Subject

認證主體,通常指用戶(把操做交給SecurityManager)。

  • SecurityManager

安全管理器,安全管理器,管理全部Subject,能夠配合內部安全組件(關聯Realm)

  • Realm

域對象,用于進行權限信息的驗證,shiro連接數據的橋梁,如我們的登錄校驗,權限校驗就在Realm進行定義。

3. Realm配置

定義用戶實體User ,可根據自己的業(yè)務自行定義

@Data
@Accessors(chain = true)
public class User {
    /**
     * 用戶id
     */
    private Long userId;
    /**
     * 用戶名
     */
    private String username;
    /**
     * 密碼
     */
    private String password;
    /**
     * 用戶別稱
     */
    private String name;
}

重寫AuthorizingRealm 中登錄校驗doGetAuthenticationInfo及授權doGetAuthorizationInfo方法,編寫我們自定義的校驗邏輯。

/**
 * 自定義登錄授權
 *
 * @author ding
 */
public class UserRealm extends AuthorizingRealm {
    /**
     * 授權
     * 此處權限授予
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 在這里為每一個用戶添加vip權限
        info.addStringPermission("vip");
        return info;
    }
    /**
     * 認證
     * 此處實現我們的登錄邏輯,如賬號密碼驗證
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 獲取到token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 從token中獲取到用戶名和密碼
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        // 為了方便,這里模擬獲取用戶
        User user = this.getUser();
        if (!user.getUsername().equals(username)) {
            throw new UnknownAccountException("用戶不存在");
        } else if (!user.getPassword().equals(password)) {
            throw new IncorrectCredentialsException("密碼錯誤");
        }
        // 校驗完成后,此處我們把用戶信息返回,便于后面我們通過Subject獲取用戶的登錄信息
        return new SimpleAuthenticationInfo(user, password, getName());
    }
    /**
     * 此處模擬用戶數據
     * 實際開發(fā)中,換成數據庫查詢獲取即可
     */
    private User getUser() {
        return new User()
                .setName("admin")
                .setUserId(1L)
                .setUsername("admin")
                .setPassword("123456");
    }
}

4. 核心配置

ShiroConfig.java

/**

* Shiro內置過濾器,能夠實現攔截器相關的攔截器

* 經常使用的過濾器:

* anon:無需認證(登陸)能夠訪問

* authc:必須認證才能夠訪問

* user:若是使用rememberMe的功能能夠直接訪問

* perms:該資源必須獲得資源權限才能夠訪問,格式 perms[權限1,權限2]

* role:該資源必須獲得角色權限才能夠訪問

**/

/**
 * shiro核心管理器
 *
 * @author ding
 */
@Configuration
public class ShiroConfig {
    /**
     * 無需認證就可以訪問
     */
    private final static String ANON = "anon";
    /**
     * 必須認證了才能訪問
     */
    private final static String AUTHC = "authc";
    /**
     * 擁有對某個資源的權限才能訪問
     */
    private final static String PERMS = "perms";
    /**
     * 創(chuàng)建realm,這里返回我們上一把定義的UserRealm 
     */
    @Bean(name = "userRealm")
    public UserRealm userRealm() {
        return new UserRealm();
    }
    /**
     * 創(chuàng)建安全管理器
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //綁定realm對象
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    /**
     * 授權過濾器
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // 設置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        // 添加shiro的內置過濾器
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/index", ANON);
        filterMap.put("/userInfo", PERMS + "[vip]");
        filterMap.put("/table2", AUTHC);
        filterMap.put("/table3", PERMS + "[vip2]");
        bean.setFilterChainDefinitionMap(filterMap);
        // 設置跳轉登陸頁
        bean.setLoginUrl("/login");
        // 無權限跳轉
        bean.setUnauthorizedUrl("/unAuth");
        return bean;
    }
    /**
     * Thymeleaf中使用Shiro標簽
     */
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}

5. 接口編寫

IndexController.java

/**
 * @author ding
 */
@Controller
public class IndexController {
    @RequestMapping({"/", "/index"})
    public String index(Model model) {
        model.addAttribute("msg", "hello,shiro");
        return "/index";
    }
    @RequestMapping("/userInfo")
    public String table1(Model model) {
        return "userInfo";
    }
    @RequestMapping("/table")
    public String table(Model model) {
        return "table";
    }
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
        //獲取當前的用戶
        Subject subject = SecurityUtils.getSubject();
        //用來存放錯誤信息
        String msg = "";
        //如果未認證
        if (!subject.isAuthenticated()) {
            //將用戶名和密碼封裝到shiro中
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                // 執(zhí)行登陸方法
                subject.login(token);
            } catch (Exception e) {
                e.printStackTrace();
                msg = "賬號或密碼錯誤";
            }
            //如果msg為空,說明沒有異常,就返回到主頁
            if (msg.isEmpty()) {
                return "redirect:/index";
            } else {
                model.addAttribute("errorMsg", msg);
                return "login";
            }
        }
        return "/login";
    }
    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "index";
    }
    @GetMapping("/unAuth")
    public String unAuth() {
        return "unAuth";
    }
}

6. 網頁資源

在resources中創(chuàng)建templates文件夾存放頁面資源

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首頁</h1>
<!-- 使用shiro標簽 -->
<shiro:authenticated>
    <p>用戶已登錄</p> <a th:href="@{/logout}" rel="external nofollow" >退出登錄</a>
</shiro:authenticated>
<shiro:notAuthenticated>
    <p>用戶未登錄</p>  
</shiro:notAuthenticated>
<br/>
<a th:href="@{/userInfo}" rel="external nofollow" >用戶信息</a>
<a th:href="@{/table}" rel="external nofollow" >table</a>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陸頁</title>
</head>
<body>
<div>
    <p th:text="${errorMsg}"></p>
    <form action="/doLogin" method="post">
        <h2>登陸頁</h2>
        <h6>賬號:admin,密碼:123456</h6>
        <input type="text" id="username"  name="username" placeholder="admin">
        <input type="password" id="password" name="password"  placeholder="123456">
        <button type="submit">登陸</button>
    </form>
</div>
</body>
</html>

userInfo.html

<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>table1</title>
</head>
<body>
<h1>用戶信息</h1>
<!-- 利用shiro獲取用戶信息 -->
用戶名:<shiro:principal property="username"/>
<br/>
用戶完整信息: <shiro:principal/>
</body>
</html>

table.hetml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>table</title>
</head>
<body>
<h1>table</h1>
</body>
</html>

7. 效果演示

啟動項目瀏覽器輸入127.0.0.1:9999

當我們點擊用戶信息和table時會自動跳轉登錄頁面

登錄成功后

獲取用戶信息

此處獲取的就是我們就是我們前面doGetAuthenticationInfo方法返回的用戶信息,這里為了演示就全部返回了,實際生產中密碼是不能返回的。

8. 源碼分享

本項目已收錄

Springboot-cli開發(fā)腳手架,集合各種常用框架使用案例,完善的文檔,致力于讓開發(fā)者快速搭建基礎環(huán)境并讓應用跑起來,并提供豐富的使用示例供使用者參考,幫助初學者快速上手。

項目源碼github地址

項目源碼國內gitee地址

到此這篇關于Springboot整合Shiro實現登錄與權限校驗詳細分解的文章就介紹到這了,更多相關Springboot Shiro登陸校驗內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Spring Boot 參數校驗的具體實現方式

    Spring Boot 參數校驗的具體實現方式

    這篇文章主要介紹了Spring Boot 參數校驗的具體實現方式,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-06-06
  • 解決Mac?m1?電腦?idea?卡頓的問題

    解決Mac?m1?電腦?idea?卡頓的問題

    這篇文章主要介紹了Mac?m1?電腦?idea?卡頓的問題解決,文中給大家補充介紹了IDEA卡頓問題處理方法,需要的朋友可以參考下
    2023-03-03
  • Java互斥鎖簡單實例

    Java互斥鎖簡單實例

    這篇文章主要介紹了Java互斥鎖,較為詳細的分析了java互斥鎖的概念與功能,并實例描述了java互斥鎖的原理與使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-07-07
  • shiro無狀態(tài)web集成的示例代碼

    shiro無狀態(tài)web集成的示例代碼

    本篇文章主要介紹了shiro無狀態(tài)web集成的示例代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • SpringMVC如何獲取多種類型數據響應

    SpringMVC如何獲取多種類型數據響應

    這篇文章主要介紹了SpringMVC如何獲取多種類型數據響應,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2023-11-11
  • Spring?Bean注冊與注入實現方法詳解

    Spring?Bean注冊與注入實現方法詳解

    首先,要學習Spring中的Bean的注入方式,就要先了解什么是依賴注入。依賴注入是指:讓調用類對某一接口的實現類的實現類的依賴關系由第三方注入,以此來消除調用類對某一接口實現類的依賴。Spring容器中支持的依賴注入方式主要有屬性注入、構造函數注入、工廠方法注入
    2022-10-10
  • 詳解Java中多線程異常捕獲Runnable的實現

    詳解Java中多線程異常捕獲Runnable的實現

    這篇文章主要介紹了詳解Java中多線程異常捕獲Runnable的實現的相關資料,希望通過本文能幫助到大家,讓大家理解掌握這樣的知識,需要的朋友可以參考下
    2017-10-10
  • spring?boot實現圖片上傳到后臺的功能(瀏覽器可直接訪問)

    spring?boot實現圖片上傳到后臺的功能(瀏覽器可直接訪問)

    這篇文章主要介紹了spring?boot實現圖片上傳到后臺的功能(瀏覽器可直接訪問),需要的朋友可以參考下
    2022-04-04
  • Spring常用注解 使用注解來構造IoC容器的方法

    Spring常用注解 使用注解來構造IoC容器的方法

    下面小編就為大家分享一篇Spring常用注解 使用注解來構造IoC容器的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • 利用棧使用簡易計算器(Java實現)

    利用棧使用簡易計算器(Java實現)

    這篇文章主要為大家詳細介紹了Java利用棧實現簡易計算器,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-09-09

最新評論