教你 Shiro 整合 SpringBoot,避開(kāi)各種坑

最近搞了下 Shiro 安全框架,找了一些網(wǎng)上的博客文章,但是一到自己實(shí)現(xiàn)的時(shí)候就遇到了各種坑,需要各種查資料看源碼以及各種測(cè)試。
那么這篇文章就教大家如何將 Shiro 整合到 SpringBoot 中,并避開(kāi)一些小坑,這次實(shí)現(xiàn)了基本的登陸以及角色權(quán)限,往后的文章也講解了其他的功能,如 《教你 Shiro + SpringBoot 整合 JWT》

附上源碼:https://github.com/HowieYuan/shiro

依賴包

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

數(shù)據(jù)庫(kù)表

一切從簡(jiǎn),用戶 user 表,以及角色 role 表


user
role

Shiro 相關(guān)類

Shiro 配置類

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必須設(shè)置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // setLoginUrl 如果不設(shè)置值,默認(rèn)會(huì)自動(dòng)尋找Web工程根目錄下的"/login.jsp"頁(yè)面 或 "/login" 映射
        shiroFilterFactoryBean.setLoginUrl("/notLogin");
        // 設(shè)置無(wú)權(quán)限時(shí)跳轉(zhuǎn)的 url;
        shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");

        // 設(shè)置攔截器
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        //游客,開(kāi)發(fā)權(quán)限
        filterChainDefinitionMap.put("/guest/**", "anon");
        //用戶,需要角色權(quán)限 “user”
        filterChainDefinitionMap.put("/user/**", "roles[user]");
        //管理員,需要角色權(quán)限 “admin”
        filterChainDefinitionMap.put("/admin/**", "roles[admin]");
        //開(kāi)放登陸接口
        filterChainDefinitionMap.put("/login", "anon");
        //其余接口一律攔截
        //主要這行代碼必須放在所有權(quán)限設(shè)置的最后,不然會(huì)導(dǎo)致所有 url 都被攔截
        filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        System.out.println("Shiro攔截器工廠類注入成功");
        return shiroFilterFactoryBean;
    }

    /**
     * 注入 securityManager
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 設(shè)置realm.
        securityManager.setRealm(customRealm());
        return securityManager;
    }

    /**
     * 自定義身份認(rèn)證 realm;
     * <p>
     * 必須寫(xiě)這個(gè)類,并加上 @Bean 注解,目的是注入 CustomRealm,
     * 否則會(huì)影響 CustomRealm類 中其他類的依賴注入
     */
    @Bean
    public CustomRealm customRealm() {
        return new CustomRealm();
    }
}

注意:里面的 SecurityManager 類導(dǎo)入的應(yīng)該是 import org.apache.shiro.mgt.SecurityManager; 但是,如果你是復(fù)制代碼過(guò)來(lái)的話,會(huì)默認(rèn)導(dǎo)入 java.lang.SecurityManager 這里也稍稍有點(diǎn)坑,其他的類的話,也是都屬于 shiro 包里面的類

shirFilter 方法中主要是設(shè)置了一些重要的跳轉(zhuǎn) url,比如未登陸時(shí),無(wú)權(quán)限時(shí)的跳轉(zhuǎn);以及設(shè)置了各類 url 的權(quán)限攔截,比如 /user 開(kāi)始的 url 需要 user 權(quán)限,/admin 開(kāi)始的 url 需要 admin 權(quán)限等

權(quán)限攔截 Filter

當(dāng)運(yùn)行一個(gè)Web應(yīng)用程序時(shí),Shiro將會(huì)創(chuàng)建一些有用的默認(rèn) Filter 實(shí)例,并自動(dòng)地將它們置為可用,而這些默認(rèn)的 Filter 實(shí)例是被 DefaultFilter 枚舉類定義的,當(dāng)然我們也可以自定義 Filter 實(shí)例,這些在以后的文章中會(huì)講到


DefaultFilter
Filter 解釋
anon 無(wú)參,開(kāi)放權(quán)限,可以理解為匿名用戶或游客
authc 無(wú)參,需要認(rèn)證
logout 無(wú)參,注銷,執(zhí)行后會(huì)直接跳轉(zhuǎn)到shiroFilterFactoryBean.setLoginUrl(); 設(shè)置的 url
authcBasic 無(wú)參,表示 httpBasic 認(rèn)證
user 無(wú)參,表示必須存在用戶,當(dāng)?shù)侨氩僮鲿r(shí)不做檢查
ssl 無(wú)參,表示安全的URL請(qǐng)求,協(xié)議為 https
perms[user] 參數(shù)可寫(xiě)多個(gè),表示需要某個(gè)或某些權(quán)限才能通過(guò),多個(gè)參數(shù)時(shí)寫(xiě) perms["user, admin"],當(dāng)有多個(gè)參數(shù)時(shí)必須每個(gè)參數(shù)都通過(guò)才算通過(guò)
roles[admin] 參數(shù)可寫(xiě)多個(gè),表示是某個(gè)或某些角色才能通過(guò),多個(gè)參數(shù)時(shí)寫(xiě) roles["admin,user"],當(dāng)有多個(gè)參數(shù)時(shí)必須每個(gè)參數(shù)都通過(guò)才算通過(guò)
rest[user] 根據(jù)請(qǐng)求的方法,相當(dāng)于 perms[user:method],其中 method 為 post,get,delete 等
port[8081] 當(dāng)請(qǐng)求的URL端口不是8081時(shí),跳轉(zhuǎn)到schemal://serverName:8081?queryString 其中 schmal 是協(xié)議 http 或 https 等等,serverName 是你訪問(wèn)的 Host,8081 是 Port 端口,queryString 是你訪問(wèn)的 URL 里的 ? 后面的參數(shù)

常用的主要就是 anon,authc,user,roles,perms 等

注意:anon, authc, authcBasic, user 是第一組認(rèn)證過(guò)濾器,perms, port, rest, roles, ssl 是第二組授權(quán)過(guò)濾器,要通過(guò)授權(quán)過(guò)濾器,就先要完成登陸認(rèn)證操作(即先要完成認(rèn)證才能前去尋找授權(quán)) 才能走第二組授權(quán)器(例如訪問(wèn)需要 roles 權(quán)限的 url,如果還沒(méi)有登陸的話,會(huì)直接跳轉(zhuǎn)到 shiroFilterFactoryBean.setLoginUrl(); 設(shè)置的 url )

自定義 realm 類

我們首先要繼承 AuthorizingRealm 類來(lái)自定義我們自己的 realm 以進(jìn)行我們自定義的身份,權(quán)限認(rèn)證操作。
記得要 Override 重寫(xiě) doGetAuthenticationInfo 和 doGetAuthorizationInfo 兩個(gè)方法(兩個(gè)方法名很相似,不要搞錯(cuò))

public class CustomRealm extends AuthorizingRealm {
    private UserMapper userMapper;

    @Autowired
    private void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 獲取身份驗(yàn)證信息
     * Shiro中,最終是通過(guò) Realm 來(lái)獲取應(yīng)用程序中的用戶、角色及權(quán)限信息的。
     *
     * @param authenticationToken 用戶身份信息 token
     * @return 返回封裝了用戶信息的 AuthenticationInfo 實(shí)例
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("————身份認(rèn)證方法————");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 從數(shù)據(jù)庫(kù)獲取對(duì)應(yīng)用戶名密碼的用戶
        String password = userMapper.getPassword(token.getUsername());
        if (null == password) {
            throw new AccountException("用戶名不正確");
        } else if (!password.equals(new String((char[]) token.getCredentials()))) {
            throw new AccountException("密碼不正確");
        }
        return new SimpleAuthenticationInfo(token.getPrincipal(), password, getName());
    }

    /**
     * 獲取授權(quán)信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("————權(quán)限認(rèn)證————");
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //獲得該用戶角色
        String role = userMapper.getRole(username);
        Set<String> set = new HashSet<>();
        //需要將 role 封裝到 Set 作為 info.setRoles() 的參數(shù)
        set.add(role);
        //設(shè)置該用戶擁有的角色
        info.setRoles(set);
        return info;
    }
}

重寫(xiě)的兩個(gè)方法分別是實(shí)現(xiàn)身份認(rèn)證以及權(quán)限認(rèn)證,shiro 中有個(gè)作登陸操作的 Subject.login() 方法,當(dāng)我們把封裝了用戶名,密碼的 token 作為參數(shù)傳入,便會(huì)跑進(jìn)這兩個(gè)方法里面(不一定兩個(gè)方法都會(huì)進(jìn)入)

其中 doGetAuthorizationInfo 方法只有在需要權(quán)限認(rèn)證時(shí)才會(huì)進(jìn)去,比如前面配置類中配置了 filterChainDefinitionMap.put("/admin/**", "roles[admin]"); 的管理員角色,這時(shí)進(jìn)入 /admin 時(shí)就會(huì)進(jìn)入 doGetAuthorizationInfo 方法來(lái)檢查權(quán)限;而 doGetAuthenticationInfo 方法則是需要身份認(rèn)證時(shí)(比如前面的 Subject.login() 方法)才會(huì)進(jìn)入

再說(shuō)下 UsernamePasswordToken 類,我們可以從該對(duì)象拿到登陸時(shí)的用戶名和密碼(登陸時(shí)會(huì)使用 new UsernamePasswordToken(username, password);),而 get 用戶名或密碼有以下幾個(gè)方法

token.getUsername()  //獲得用戶名 String
token.getPrincipal() //獲得用戶名 Object 
token.getPassword()  //獲得密碼 char[]
token.getCredentials() //獲得密碼 Object

注意:有很多人會(huì)發(fā)現(xiàn),UserMapper 等類,接口無(wú)法通過(guò) @Autowired 注入進(jìn)來(lái),跑程序的時(shí)候會(huì)報(bào) NullPointerException,網(wǎng)上說(shuō)了很多諸如是 Spring 加載順序等原因,但其實(shí)有一個(gè)很重要的地方要大家注意,CustomRealm 這個(gè)類是在 shiro 配置類的 securityManager.setRealm() 方法中設(shè)置進(jìn)去的,而很多人直接寫(xiě)securityManager.setRealm(new CustomRealm()); ,這樣是不行的,必須要使用 @Bean 注入 MyRealm,不能直接 new 對(duì)象:

    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 設(shè)置realm.
        securityManager.setRealm(customRealm());
        return securityManager;
    }

    @Bean
    public CustomRealm customRealm() {
        return new CustomRealm();
    }

道理也很簡(jiǎn)單,和 Controller 中調(diào)用 Service 一樣,都是 SpringBean,不能自己 new

當(dāng)然,同樣的道理也可以這樣寫(xiě):

    @Bean
    public SecurityManager securityManager(CustomRealm customRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 設(shè)置realm.
        securityManager.setRealm(customRealm);
        return securityManager;
    }

然后只要在 CustomRealm 類加上個(gè)類似 @Component 的注解即可

功能實(shí)現(xiàn)

本文的功能全部以接口返回 json 數(shù)據(jù)的方式實(shí)現(xiàn)

根據(jù) url 權(quán)限分配 controller

游客
@RestController
@RequestMapping("/guest")
public class GuestController{
    @Autowired    
    private final ResultMap resultMap;

    @RequestMapping(value = "/enter", method = RequestMethod.GET)
    public ResultMap login() {
        return resultMap.success().message("歡迎進(jìn)入,您的身份是游客");
    }

    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    public ResultMap submitLogin() {
        return resultMap.success().message("您擁有獲得該接口的信息的權(quán)限!");
    }
}
普通登陸用戶
@RestController
@RequestMapping("/user")
public class UserController{
    @Autowired    
    private final ResultMap resultMap;

    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    public ResultMap getMessage() {
        return resultMap.success().message("您擁有用戶權(quán)限,可以獲得該接口的信息!");
    }
}
管理員
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired    
    private final ResultMap resultMap;

    @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
    public ResultMap getMessage() {
        return resultMap.success().message("您擁有管理員權(quán)限,可以獲得該接口的信息!");
    }
}

突然注意到 CustomRealm 類那里拋出了 AccountException 異常,現(xiàn)在建個(gè)類進(jìn)行異常捕獲

@RestControllerAdvice
public class ExceptionController {
    private final ResultMap resultMap;

    @Autowired
    public ExceptionController(ResultMap resultMap) {
        this.resultMap = resultMap;
    }

    // 捕捉 CustomRealm 拋出的異常
    @ExceptionHandler(AccountException.class)
    public ResultMap handleShiroException(Exception ex) {
        return resultMap.fail().message(ex.getMessage());
    }
}

還有進(jìn)行登陸等處理的 LoginController

@RestController
public class LoginController {
    @Autowired    
    private ResultMap resultMap;
    private UserMapper userMapper;

    @RequestMapping(value = "/notLogin", method = RequestMethod.GET)
    public ResultMap notLogin() {
        return resultMap.success().message("您尚未登陸!");
    }

    @RequestMapping(value = "/notRole", method = RequestMethod.GET)
    public ResultMap notRole() {
        return resultMap.success().message("您沒(méi)有權(quán)限!");
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ResultMap logout() {
        Subject subject = SecurityUtils.getSubject();
        //注銷
        subject.logout();
        return resultMap.success().message("成功注銷!");
    }

    /**
     * 登陸
     *
     * @param username 用戶名
     * @param password 密碼
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultMap login(String username, String password) {
        // 從SecurityUtils里邊創(chuàng)建一個(gè) subject
        Subject subject = SecurityUtils.getSubject();
        // 在認(rèn)證提交前準(zhǔn)備 token(令牌)
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 執(zhí)行認(rèn)證登陸
        subject.login(token);
        //根據(jù)權(quán)限,指定返回?cái)?shù)據(jù)
        String role = userMapper.getRole(username);
        if ("user".equals(role)) {
            return resultMap.success().message("歡迎登陸");
        }
        if ("admin".equals(role)) {
            return resultMap.success().message("歡迎來(lái)到管理員頁(yè)面");
        } 
        return resultMap.fail().message("權(quán)限錯(cuò)誤!");
    }
}

測(cè)試

登陸前訪問(wèn)信息接口
普通用戶登陸
密碼錯(cuò)誤
管理員登陸
獲取信息
獲取信息
注銷
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 說(shuō)明:本文很多觀點(diǎn)和內(nèi)容來(lái)自互聯(lián)網(wǎng)以及各種資料,如果侵犯了您的權(quán)益,請(qǐng)及時(shí)聯(lián)系我,我會(huì)刪除相關(guān)內(nèi)容。 權(quán)限管理 基...
    寇寇寇先森閱讀 7,765評(píng)論 8 76
  • 安全應(yīng)該是互聯(lián)網(wǎng)公司的一道生命線,幾乎任何的公司都會(huì)涉及到這方面的需求。在Java領(lǐng)域一般有Spring Secu...
    滄海一粟謙閱讀 2,498評(píng)論 0 3
  • 后臺(tái)管理系統(tǒng) 業(yè)務(wù)場(chǎng)景 spring boot + mybatis后臺(tái)管理系統(tǒng)框架; layUI前端界面; shi...
    漢若已認(rèn)證閱讀 10,198評(píng)論 2 69
  • 說(shuō)到婚姻這個(gè)話題,我并不會(huì)多聊,每段婚姻確實(shí)如每個(gè)人腳上的鞋,合適不合適各人知道。但記得王菲、李亞鵬離婚的消息讓一...
    海茉爾閱讀 233評(píng)論 0 0
  • 石進(jìn)斜的詩(shī)歌專輯 夢(mèng)境與指紋的柔情 裝扮和撫摸,天使的翅膀 拉下的眼簾,是你飛升的軌跡 溫柔藏在花朵 芬芳,催化了...
    石進(jìn)斜閱讀 1,024評(píng)論 28 20

友情鏈接更多精彩內(nèi)容