权限管控
Spring Security
Apache Shiro
原生的整合
创建一个 Spring Boot 项目,加入 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:
在 Realm 中实现简单的认证操作即可,不做授权
配置 Shiro
接下来进行 Shiro 的配置:
在这里进行 Shiro 的配置主要配置 3 个 Bean :
首先需要提供一个 Realm 的实例。
需要配置一个 SecurityManager,在 SecurityManager 中配置 Realm。
配置一个 ShiroFilterFactoryBean ,在 ShiroFilterFactoryBean 中指定路径拦截规则等。
配置登录和测试接口。
其中,ShiroFilterFactoryBean 的配置稍微多一些,配置含义如下:
setSecurityManager 表示指定 SecurityManager。
setLoginUrl 表示指定登录页面。
setSuccessUrl 表示指定登录成功页面。
接下来的 Map 中配置了路径拦截规则,注意,要有序。
这些东西都配置完成后,接下来配置登录 Controller:
测试时,首先访问 /hello 接口,由于未登录,所以会自动跳转到 /login 接口
然后调用 /doLogin 接口完成登录
使用 Shiro Starter
上面这种配置方式实际上相当于把 SSM 中的 XML 配置拿到 Spring Boot 中用 Java 代码重新写了一遍,除了这种方式之外,我们也可以直接使用 Shiro 官方提供的 Starter 。
创建成功后,添加 shiro-spring-boot-web-starter ,这个依赖可以代替之前的 shiro-web 和 shiro-spring 两个依赖,pom.xml 文件如下:
创建 Realm
这里的 Realm 和前面的一样,不再赘述。
配置 Shiro 基本信息
接下来在 application.properties 中配置 Shiro 的基本信息:
配置解释:
第一行表示是否允许将sessionId 放到 cookie 中
第二行表示是否允许将 sessionId 放到 Url 地址拦中
第三行表示访问未获授权的页面时,默认的跳转路径
第四行表示开启 shiro
第五行表示登录成功的跳转页面
第六行表示登录页面
配置 ShiroConfig
这里的配置和前面的比较像,但是不再需要 ShiroFilterFactoryBean 实例了,替代它的是 ShiroFilterChainDefinition ,在这里定义 Shiro 的路径匹配规则即可。
这里定义完之后,接下来的登录接口定义以及测试方法都和前面的一致
Source & Reference
https://mp.weixin.qq.com/s/JU_-gn-yZ4VJJXTZvo7nZQ
https://cloud.tencent.com/developer/article/1643122