Spring Boot 整合 Apache Shiro

Apache Shiro™是一个功能强大且易于使用的 Java 安全框架,它执行身份验证、授权、加密和会话管理。借助 Shiro 易于理解的 API,您可以快速轻松地保护任何应用程序——从最小的移动应用程序到最大的 Web 和企业应用程序。

https://shiro.apache.org/

官方文档说明:https://shiro.apache.org/spring-boot.html

在开发的时候,发现其登录功能是直接将用户信息存储到Session中, 过于简陋,应该有一个合适的工具来做这件事。

思考过 SpringSecrity 并不是很适合我的口味。故想考虑使用另一款,Shiro。

Shiro三大核心组件

Subject: 即当前用户,在权限管理的应用程序里往往需要知道谁能够操作什么,谁拥有操作该程序的权利,shiro中则需要通过Subject来提供基础的当前用户信息,Subject 不仅仅代表某个用户,与当前应用交互的任何东西都是Subject,如网络爬虫等。所有的Subject都要绑定到SecurityManager上,与Subject的交互实际上是被转换为与SecurityManager的交互。

SecurityManager: 即所有Subject的管理者,这是Shiro框架的核心组件,可以把他看做是一个Shiro框架的全局管理组件,用于调度各种Shiro框架的服务。作用类似于SpringMVC中的DispatcherServlet,用于拦截所有请求并进行处理。

Realm: Realm是用户的信息认证器和用户的权限人证器,我们需要自己来实现Realm来自定义的管理我们自己系统内部的权限规则。SecurityManager要验证用户,需要从Realm中获取用户。可以把Realm看做是数据源

安装依赖
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring-boot-web-starter</artifactId>
  <version>1.9.0</version>
</dependency>
编写配置类
package cn.codeon.config;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm() {
        SimpleAccountRealm realm = new SimpleAccountRealm();

        realm.addAccount("root", "root");

        return realm;
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/**", "anon"); // all paths are managed via annotations

        // or allow authentication, but NOT require it.
        // chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }
}

除了 SimpleAccountRealm 你也可以自己实现 Realm

直接实现 Realm 接口可能既耗时又容易出错。大多数人选择继承 AuthorizingRealm 抽象类,而不是从头开始。该类实现了常见的身份验证和授权工作流程,以节省您的时间和精力。

内置过滤器