springboot整合shiro (二) 使用shiro過濾器實現認證資源攔截

我們去寫幾個頁面來實現登錄攔截
核心代碼:

// 添加 Shiro 內置過濾器
        /**
         * Shiro 內置過濾器, 可以實現權限相關的攔截器
         * 常用的過濾器:
         *      anon: 無需認證(登錄)即可訪問
         *      authc: 必須認證纔可訪問
         *      user: 如果使用 rememberMe
         *      perms: 該資源必須得到資源權限才能訪問
         *      role: 該資源必須得到角色權限纔可訪問
         */
        Map<String, String> filterMap = new LinkedHashMap<>();

        filterMap.put("/index", "anon");
        filterMap.put("/login", "anon");
        filterMap.put("/*", "authc");

        filterFactoryBean.setFilterChainDefinitionMap(filterMap);

        // 修改調整的登陸頁面
        filterFactoryBean.setLoginUrl("/toLogin");

1. 登錄和測試頁面的撰寫

首先引入 thymeleaf 依賴

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

然後我們寫幾個頁面
在這裏插入圖片描述
index中就是有兩個鏈接可以跳轉到addupdate頁面, 而login則是實現登錄
controller中添加跳轉

package com.krlin.springbootshiro.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ShiroController {

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/update")
    public String update() {
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "/login";
    }
}

在這裏插入圖片描述
現在點擊跳轉是可以跳轉到添加或者更新頁面的, 這時候我們需要加權限,當點擊添加的時候判斷是否登錄, 如果登錄了就可以跳轉,否則跳轉到登陸頁面

2. shiro實現登錄攔截

我們在 ShiroConfig中做修改
在這裏插入圖片描述

/**
     * 創建 ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean (@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        // 設置安全管理器
        filterFactoryBean.setSecurityManager(securityManager);

        // 添加 Shiro 內置過濾器
        /**
         * Shiro 內置過濾器, 可以實現權限相關的攔截器
         * 常用的過濾器:
         *      anon: 無需認證(登錄)即可訪問
         *      authc: 必須認證纔可訪問
         *      user: 如果使用 rememberMe
         *      perms: 該資源必須得到資源權限才能訪問
         *      role: 該資源必須得到角色權限纔可訪問
         */
        Map<String, String> filterMap = new LinkedHashMap<>();

        filterMap.put("/add", "authc");
        filterMap.put("/update", "authc");

        filterFactoryBean.setFilterChainDefinitionMap(filterMap);

        return filterFactoryBean;
    }

我們給 /add/update 加上authc權限, 再次訪問‘
可以看到,再次點擊添加用戶就會跳轉到 login.jsp 但是因爲login.jsp不存在, 所以是404
在這裏插入圖片描述
我們可以修改他跳轉到指定頁面,

// 修改調整的登陸頁面
filterFactoryBean.setLoginUrl("/toLogin");

在這裏插入圖片描述
這個時候我們點擊添加或者更新就會跳轉到登陸頁面
在這裏插入圖片描述

一般我們對一個網站做攔截處理的時候是對所有路徑攔截,然後去放行某些登錄註冊等路徑, 操作如下
在這裏插入圖片描述
我們去攔截所有的請求, 但是放行 /index 這個請求

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章