轻松搞定安全框架(Shiro)

本文介绍如何使用SpringBoot和Shiro框架实现安全认证和授权,包括依赖导入、属性配置、实体类创建及伪造数据等步骤。通过Shiro的Subject、SecurityManager和Realm核心组件,以及EhCache缓存配置,实现高效安全的用户权限管理。

SpringBoot 是为了简化 Spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程

Shiro 是 Apache 旗下开源的一款强大且易用的Java安全框架,身份验证、授权、加密、会话管理。 相比 Spring Security 而言 Shiro 更加轻量级,且 API 更易于理解…

Shiro

Shiro 主要分为 安全认证 和 接口授权 两个部分,其中的核心组件为 SubjectSecurityManagerRealms,公共部分 Shiro 都已经为我们封装好了,我们只需要按照一定的规则去编写响应的代码即可…

  • Subject 即表示主体,将用户的概念理解为当前操作的主体,因为它即可以是一个通过浏览器请求的用户,也可能是一个运行的程序,外部应用与 Subject 进行交互,记录当前操作用户。Subject 代表了当前用户的安全操作,SecurityManager 则管理所有用户的安全操作。
  • SecurityManager 即安全管理器,对所有的 Subject 进行安全管理,并通过它来提供安全管理的各种服务(认证、授权等)
  • Realm 充当了应用与数据安全间的 桥梁 或 连接器。当对用户执行认证(登录)和授权(访问控制)验证时,Shiro 会从应用配置的 Realm 中查找用户及其权限信息。

本章目标

利用 Spring Boot 与 Shiro 实现安全认证和授权….

导入依赖

依赖 spring-boot-starter-web

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<shiro.version>1.4.0</shiro.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- shiro 相关包 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- End -->
</dependencies>

属性配置

缓存配置

Shiro 为我们提供了 CacheManager 即缓存管理,将用户权限数据存储在缓存,可以提高它的性能。支持 EhCacheRedis 等常规缓存,这里为了简单起见就用 EhCache 了 , 在resources 目录下创建一个 ehcache-shiro.xml 文件

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="shiroCache">
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>

实体类

创建一个 User.java ,标记为数据库用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.battcn.entity;

/**
* @author Levin
* @since 2018/6/28 0028
*/
public class User {
/** 自增ID */
private Long id;
/** 账号 */
private String username;
/** 密码 */
private String password;
/** 角色名:Shiro 支持多个角色,而且接收参数也是 Set<String> 集合,但这里为了简单起见定义成 String 类型了 */
private String roleName;
/** 是否禁用 */
private boolean locked;
// 省略 GET SET 构造函数...
}

伪造数据

支持 rolespermissions,比如你一个接口可以允许用户拥有某一个角色,也可以是拥有某一个 permission …

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.battcn.config;

import com.battcn.entity.User;

import java.util.*;

/**
* 主要不想连接数据库..
*
* @author Levin
* @since 2018/6/28 0028
*/
public class DBCache {

/**
* K 用户名
* V 用户信息
*/
public static final Map<String, User> USERS_CACHE = new HashMap<>();
/**
* K 角色ID
* V 权限编码
*/
public static final Map<String, Collection<String>> PERMISSIONS_CACHE = new HashMap<>();

static {
// TODO 假设这是数据库记录
USERS_CACHE.put("u1", new User(1L, "u1", "p1", "admin", true));
USERS_CACHE.put("u2", new User(2L, "u2", "p2", "admin", false));
USERS_CACHE.put("u3", new User(3L, "u3", "p3", "test", true));

PERMISSIONS_CACHE.put("admin", Arrays.asList("user:list", "user:add", "user:edit"));
PERMISSIONS_CACHE.put("test", Collections.singletonList("user:list"));

}
}

ShiroConfiguration

Shiro 的主要配置信息都在此文件内实现;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package com.battcn.config;


import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
* Shiro 配置
*
* @author Levin
*/
@Configuration
public class ShiroConfiguration {

private static final Logger log = LoggerFactory.getLogger(ShiroConfiguration.class);

@Bean
public EhCacheManager getEhCacheManager() {
EhCacheManager em = new EhCacheManager();
em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
return em;
}


@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}


/**
* 加密器:这样一来数据库就可以是密文存储,为了演示我就不开启了
*
* @return HashedCredentialsMatcher
*/
// @Bean
// public HashedCredentialsMatcher hashedCredentialsMatcher() {
// HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// //散列算法:这里使用MD5算法;
// hashedCredentialsMatcher.setHashAlgorithmName("md5");
// //散列的次数,比如散列两次,相当于 md5(md5(""));
// hashedCredentialsMatcher.setHashIterations(2);
// return hashedCredentialsMatcher;
// }


@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
autoProxyCreator.setProxyTargetClass(true);
return autoProxyCreator;
}

@Bean(name = "authRealm")
public AuthRealm authRealm(EhCacheManager cacheManager) {
AuthRealm authRealm = new AuthRealm();
authRealm.setCacheManager(cacheManager);
return authRealm;
}

@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(AuthRealm authRealm) {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(authRealm);
// <!-- 用户授权/认证信息Cache, 采用EhCache 缓存 -->
defaultWebSecurityManager.setCacheManager(getEhCacheManager());
return defaultWebSecurityManager;
}

@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(
DefaultWebSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}

/**
* ShiroFilter<br/>
* 注意这里参数中的 StudentService 和 IScoreDao 只是一个例子,因为我们在这里可以用这样的方式获取到相关访问数据库的对象,
* 然后读取数据库相关配置,配置到 shiroFilterFactoryBean 的访问规则中。实际项目中,请使用自己的Service来处理业务逻辑。
*
* @param securityManager 安全管理器
* @return ShiroFilterFactoryBean
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必须设置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 如果不设置默认会自动寻找Web工程根目录下的"/login"页面
shiroFilterFactoryBean.setLoginUrl("/login");
// 登录成功后要跳转的连接
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/denied");
loadShiroFilterChain(shiroFilterFactoryBean);
return shiroFilterFactoryBean;
}

/**
* 加载shiroFilter权限控制规则(从数据库读取然后配置)
*/
private void loadShiroFilterChain(ShiroFilterFactoryBean shiroFilterFactoryBean) {
/////////////////////// 下面这些规则配置最好配置到配置文件中 ///////////////////////

转载于:https://www.cnblogs.com/lywJ/p/10715363.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值