SpringBoot集成Shiro实现多数据源认证授权与分布式会话(一)

项目背景

在最近重构后的项目中使用了springboot+shiro的技术栈,shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码学和会话管理.shiro包含三个核心组件subject,securityManager和realm.subject即当前操作用户,代表了当前用户的安全操作,shiro底层使用了threadlocal来存取当前用户的subject.
securityManager则是管理所有用户的安全操作,属于框架的核心组件,shiro通过它来管理内部组件与提供各种服务。
realm充当了shiro与数据之间的桥梁,实质上就是封装好的一个安全相关的DAO。
本系统使用了shiro来处理用户的身份认证与权限校验。

具体实现

首先在项目的pom文件中引入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
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${org.apache.shiro-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${org.apache.shiro-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${org.apache.shiro-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${org.apache.shiro-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-aspectj</artifactId>
<version>${org.apache.shiro-version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-quartz</artifactId>
<version>${org.apache.shiro-version}</version>
</dependency>

然后创建一个shiro的配置类ShiroConfiguration,shiro使用了过滤器shiroFilter来作为入口点,用于拦截需要安全控制的请求.

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
/**
* ShiroFilterFactoryBean 处理拦截资源文件问题。
* Filter Chain定义说明 1、一个URL可以配置多个Filter,使用逗号分隔
2、当设置多个过滤器时,全部验证通过,才视为通过
* 3、部分过滤器可指定参数,如perms,roles
*/
@Bean
public ShiroFilterFactoryBean shirFilter() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必须设置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager());
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
shiroFilterFactoryBean.setLoginUrl("/login.html");
// 登录成功后要跳转的链接
shiroFilterFactoryBean.setSuccessUrl("/admin/index.html");
// 未授权界面;
shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
//Shiro自定义认证过滤器
Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();//获取filters
filters.put("authc", new CustomerFormAuthenticationFilter());
shiroFilterFactoryBean.setFilters(filters);
// 拦截器.
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//拦截的,从上向下顺序执行,匹配成功就不再继续往下走
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("/img/favicon.ico", "anon,noSessionCreation");
filterChainDefinitionMap.put("/templates/system/public/**", "anon");
filterChainDefinitionMap.put("/vertifyCode/**", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/toLogin", "anon");
// <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}

设置系统的sessionid,框架默认为: JSESSIONID,可改成其他的如token.

1
2
3
4
5
6
@Bean
public SimpleCookie wapsession() {
SimpleCookie simpleCookie = new SimpleCookie("token");
simpleCookie.setMaxAge(2592000);
return simpleCookie;
}

接下来配置cookie管理器.

1
2
3
4
5
6
7
@Bean
public SimpleCookie rememberMeCookie() {
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
simpleCookie.setMaxAge(2592000);
simpleCookie.setHttpOnly(true);
return simpleCookie;
}

提供了记住我(RememberMe)的功能.

1
2
3
4
5
6
7
8
@Bean
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
byte[] cipherKey = Base64.decode("4AvVhmFLUs0KTA3Kprsdag==");
cookieRememberMeManager.setCookie(rememberMeCookie());
cookieRememberMeManager.setCipherKey(cipherKey);
return cookieRememberMeManager;
}

配置securityManager安全管理器.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager() {
logger.info("注入Shiro的Web过滤器-->securityManager", ShiroFilterFactoryBean.class);
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setAuthenticator(authenticator());
//设置多Realm,用于获取认证凭证
Collection<Realm> realms = new ArrayList<>();
realms.add(appShiroRealm());
realms.add(pcShiroRealm());
realms.add(thirdPathShiroRealm());
securityManager.setRealms(realms);
//注入缓存管理器
//securityManager.setCacheManager(ehCacheManager());
//注入会话管理器
securityManager.setSessionManager(sessionManager());
//注入Cookie(记住我)管理器(remenberMeManager)
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}

定义数据源Realm.

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
/*
* @describe 自定义AppRealm
* @param []
* @return com.hongsui.win.home.controller.admin.web.realm.AppShiroRealm
*/
@Bean
public AppShiroRealm appShiroRealm() {
AppShiroRealm appShiroRealm = new AppShiroRealm();
appShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return appShiroRealm;
}

/*
* @describe 自定义AppRealm
* @param []
* @return com.hongsui.win.home.controller.admin.web.realm.PcShiroRealm
*/
@Bean
public PcShiroRealm pcShiroRealm() {
PcShiroRealm pcShiroRealm = new PcShiroRealm();
pcShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return pcShiroRealm;
}

/*
* @describe 自定义ThirdRealm
* @param []
* @return com.hongsui.win.home.controller.admin.web.realm.ThirdPathShiroRealm
*/
@Bean
public ThirdPathShiroRealm thirdPathShiroRealm() {
ThirdPathShiroRealm thirdPathShiroRealm = new ThirdPathShiroRealm();
thirdPathShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return thirdPathShiroRealm;
}

配置会话管理器.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Bean
public CustomerWebSessionManager sessionManager() {
CustomerWebSessionManager sessionManager = new CustomerWebSessionManager();
//会话验证器调度时间
sessionManager.setSessionValidationInterval(1800000);
//定时检查失效的session
sessionManager.setSessionValidationSchedulerEnabled(true);
//是否在会话过期后会调用SessionDAO的delete方法删除会话 默认true
sessionManager.setDeleteInvalidSessions(true);
sessionManager.setSessionDAO(redisSessionDAO());
sessionManager.setSessionIdUrlRewritingEnabled(false);
sessionManager.setSessionIdCookie(wapsession());
sessionManager.setSessionIdCookieEnabled(true);
return sessionManager;
}

保证实现了Shiro内部lifecycle函数的bean执行.

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

开启Shiro的注解(如@RequiresRoles,@RequiresPermissions等等),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证,配置以下两个bean(DefaultAdvisorAutoProxyCreatorAuthorizationAttributeSourceAdvisor)即可实现此功能.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}

@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor =
new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(getDefaultWebSecurityManager());
return authorizationAttributeSourceAdvisor;
}

到此shiro框架已经与springboot集成到项目中了,之后就可以编写相应的realm代码以及在controller层实现登录认证了.