Spring Boot 整合 Shiro ,兩種方式全總結!

江南一點雨發表於2019-06-11

在 Spring Boot 中做許可權管理,一般來說,主流的方案是 Spring Security ,但是,僅僅從技術角度來說,也可以使用 Shiro。

今天鬆哥就來和大家聊聊 Spring Boot 整合 Shiro 的話題!

一般來說,Spring Security 和 Shiro 的比較如下:

  1. Spring Security 是一個重量級的安全管理框架;Shiro 則是一個輕量級的安全管理框架
  2. Spring Security 概念複雜,配置繁瑣;Shiro 概念簡單、配置簡單
  3. Spring Security 功能強大;Shiro 功能簡單
  4. ...

雖然 Shiro 功能簡單,但是也能滿足大部分的業務場景。所以在傳統的 SSM 專案中,一般來說,可以整合 Shiro。

在 Spring Boot 中,由於 Spring Boot 官方提供了大量的非常方便的開箱即用的 Starter ,當然也提供了 Spring Security 的 Starter ,使得在 Spring Boot 中使用 Spring Security 變得更加容易,甚至只需要新增一個依賴就可以保護所有的介面,所以,如果是 Spring Boot 專案,一般選擇 Spring Security 。

這只是一個建議的組合,單純從技術上來說,無論怎麼組合,都是沒有問題的。

在 Spring Boot 中整合 Shiro ,有兩種不同的方案:

  1. 第一種就是原封不動的,將 SSM 整合 Shiro 的配置用 Java 重寫一遍。
  2. 第二種就是使用 Shiro 官方提供的一個 Starter 來配置,但是,這個 Starter 並沒有簡化多少配置。

原生的整合

  • 建立專案

建立一個 Spring Boot 專案,只需要新增 Web 依賴即可:

Spring Boot 整合 Shiro ,兩種方式全總結!

專案建立成功後,加入 Shiro 相關的依賴,完整的 pom.xml 檔案中的依賴如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-web</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.4.0</version>
    </dependency>
</dependencies>
  • 建立 Realm

接下來我們來自定義核心元件 Realm:

public class MyRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        if (!"javaboy".equals(username)) {
            throw new UnknownAccountException("賬戶不存在!");
        }
        return new SimpleAuthenticationInfo(username, "123", getName());
    }
}

在 Realm 中實現簡單的認證操作即可,不做授權,授權的具體寫法和 SSM 中的 Shiro 一樣,不贅述。這裡的認證表示使用者名稱必須是 javaboy ,使用者密碼必須是 123 ,滿足這樣的條件,就能登入成功!

  • 配置 Shiro

接下來進行 Shiro 的配置:

@Configuration
public class ShiroConfig {
    @Bean
    MyRealm myRealm() {
        return new MyRealm();
    }
    
    @Bean
    SecurityManager securityManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm());
        return manager;
    }
    
    @Bean
    ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager());
        bean.setLoginUrl("/login");
        bean.setSuccessUrl("/index");
        bean.setUnauthorizedUrl("/unauthorizedurl");
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/doLogin", "anon");
        map.put("/**", "authc");
        bean.setFilterChainDefinitionMap(map);
        return bean;
    }
}

在這裡進行 Shiro 的配置主要配置 3 個 Bean :

  1. 首先需要提供一個 Realm 的例項。
  2. 需要配置一個 SecurityManager,在 SecurityManager 中配置 Realm。
  3. 配置一個 ShiroFilterFactoryBean ,在 ShiroFilterFactoryBean 中指定路徑攔截規則等。
  4. 配置登入和測試介面。

其中,ShiroFilterFactoryBean 的配置稍微多一些,配置含義如下:

  • setSecurityManager 表示指定 SecurityManager。
  • setLoginUrl 表示指定登入頁面。
  • setSuccessUrl 表示指定登入成功頁面。
  • 接下來的 Map 中配置了路徑攔截規則,注意,要有序。

這些東西都配置完成後,接下來配置登入 Controller:

@RestController
public class LoginController {
    @PostMapping("/doLogin")
    public void doLogin(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password));
            System.out.println("登入成功!");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("登入失敗!");
        }
    }
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
    @GetMapping("/login")
    public String  login() {
        return "please login!";
    }
}

測試時,首先訪問 /hello 介面,由於未登入,所以會自動跳轉到 /login 介面:

Spring Boot 整合 Shiro ,兩種方式全總結!

然後呼叫 /doLogin 介面完成登入:

Spring Boot 整合 Shiro ,兩種方式全總結!

再次訪問 /hello 介面,就可以成功訪問了:

Spring Boot 整合 Shiro ,兩種方式全總結!

使用 Shiro Starter

上面這種配置方式實際上相當於把 SSM 中的 XML 配置拿到 Spring Boot 中用 Java 程式碼重新寫了一遍,除了這種方式之外,我們也可以直接使用 Shiro 官方提供的 Starter 。

  • 建立工程,和上面的一樣

建立成功後,新增 shiro-spring-boot-web-starter ,這個依賴可以代替之前的 shiro-webshiro-spring 兩個依賴,pom.xml 檔案如下:

<dependencies>
    <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.0</version>
    </dependency>
</dependencies>
  • 建立 Realm

這裡的 Realm 和前面的一樣,我就不再贅述。

  • 配置 Shiro 基本資訊

接下來在 application.properties 中配置 Shiro 的基本資訊:

shiro.sessionManager.sessionIdCookieEnabled=true
shiro.sessionManager.sessionIdUrlRewritingEnabled=true
shiro.unauthorizedUrl=/unauthorizedurl
shiro.web.enabled=true
shiro.successUrl=/index
shiro.loginUrl=/login

配置解釋:

  1. 第一行表示是否允許將sessionId 放到 cookie 中
  2. 第二行表示是否允許將 sessionId 放到 Url 地址攔中
  3. 第三行表示訪問未獲授權的頁面時,預設的跳轉路徑
  4. 第四行表示開啟 shiro
  5. 第五行表示登入成功的跳轉頁面
  6. 第六行表示登入頁面
  • 配置 ShiroConfig
@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;
    }
}

這裡的配置和前面的比較像,但是不再需要 ShiroFilterFactoryBean 例項了,替代它的是 ShiroFilterChainDefinition ,在這裡定義 Shiro 的路徑匹配規則即可。

這裡定義完之後,接下來的登入介面定義以及測試方法都和前面的一致,我就不再贅述了。大家可以參考上文。

總結

本文主要向大家介紹了 Spring Boot 整合 Shiro 的兩種方式,一種是傳統方式的 Java 版,另一種則是使用 Shiro 官方提供的 Starter,兩種方式,不知道大家有沒有學會呢?

本文案例,我已經上傳到 GitHub ,歡迎大家 star:https://github.com/lenve/javaboy-code-samples

關於本文,有問題歡迎留言討論。

關注公眾號牧碼小子,專注於 Spring Boot+微服務以及前後端分離等全棧技術,定期視訊教程分享,關注後回覆 Java ,領取鬆哥為你精心準備的 Java 乾貨!
Spring Boot 整合 Shiro ,兩種方式全總結!

相關文章