Apache Shiro 简介
Apache Shiro 是 Java 的一个开源安全框架,提供身份验证、授权、密码学和会话管理。
Shiro 框架直观、易用,同时也能提供健壮的安全性。而 Spring Security 功能更强大,相对来说会比较复杂。本次选择的是 Apache Shiro,接下来开始 Shiro 安全框架之旅吧。
名词解释
- 认证:用户身份识别,通常被称为用户“登录”
- 授权:访问控制
- 密码加密:保护或隐藏数据防止被偷窥
- 会话管理:用户访问应用时保持的连接关系。这里主要指 SESSION 和 COOKIE
Apache Shiro 架构介绍
上图为 Shiro 的三个核心组件:Subject,SecurityManager 和 Realms。
- Subject:主体,代表当前操作用户。这个“用户”,不仅仅指代人,也指代与之交互的网络爬虫等等。
- SecurityManager:安全管理器,是 Shiro 的核心。它管理所有的 Subject,并负责与后面的组件交互。有点像 SpringMVC 中的 DispatcherServlet。
- Realm:域,可以看成是安全数据源。Shiro 从 Realm 获取安全数据(如用户、角色、权限)。例如用户登录的时候,Shiro 会从 Realm 配置角色和权限。
Shiro 不提供维护用户或权限,而是通过 Realm 让开发人员自己注入。
Maven 引入 jar 包
1 | <!-- shiro 安全框架--> |
web.xml 配置
首先配置过滤器,让请求资源经过 Shiro 的过滤处理。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- shiro 安全过滤器 配置在 DispatcherServlet 之前-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring-web.xml 配置
在 SpringMVC 中启用注解方式授权。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<!-- 配置使 Spring 采用 CGLIB 代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 启用shrio授权注解拦截方式 -->
<aop:config proxy-target-class="true"></aop:config>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!-- shiro cacheManager 配置 ,还是没有成功 -->
<cache:annotation-driven cache-manager="cacheManager"/>
<bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:shiro/ehcache.xml" />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehCacheManagerFactory"/>
applicationContext-shiro.xml 配置
1 | <?xml version="1.0" encoding="UTF-8"?> |
ehcache-shiro.xml 配置
1 | <ehcache updateCheck="false" name="shiroCache"> |
登录示例
1 | /** |
小记
未完待续。
参考资料
- Apache Shiro官网 http://shiro.apache.org/
- Apache Shiro 维基百科 https://zh.wikipedia.org/wiki/Apache_Shiro
- Apache Shiro 使用手册 http://www.iteye.com/blogs/tag/%E5%AE%89%E5%85%A8%E6%A1%86%E6%9E%B6
- 跟我学Shiro目录贴 http://jinnianshilongnian.iteye.com/blog/2018398
- 让Apache Shiro保护你的应用 http://www.infoq.com/cn/articles/apache-shiro
- 在 Web 项目中应用 Apache Shiro https://www.ibm.com/developerworks/cn/java/j-lo-shiro/
- quick4j 通用 JavaWeb 项目骨架 https://github.com/starzou/quick4j