一、shiro的应用场景和介绍
- 实现项目中的权限的管理
二、shiro的优点
- 易于使用 - 易用性是这个项目的最终目标。提供易于理解的 Java Security API。
- 广泛性 - 没有其他安全框架可以达到Apache Shiro宣称的广度,它可以为你的安全需求提供“一站式”服务。
- 灵活性 - Apache Shiro可以工作在任何应用环境中。虽然它工作在Web、EJB和IoC环境中,但它并不依赖这些环境。Shiro既不强加任何规范,也无需过多依赖。
- Web能力 - Apache Shiro对Web应用的支持很神奇,允许你基于应用URL和Web协议(如REST)创建灵活的安全策略,同时还提供了一套控制页面输出的JSP标签库。
三、与spring的整合
1)导入pom坐标
shiro-all<!-- 权限控制 框架 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.2.2</version>
</dependency>
2)配置web.xml
<filter>
<!-- 去spring配置文件中寻找同名bean -->
<filter-name>shiroFilter1</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3)配置applicationContext-shiro.xml
注意:在shiro的配置文件中,配置过滤器时,一定要确保 id的名称与 web.xml中的 <filter-name> 名称一致!!!
a.配置 ShiroFilter的属性
<!-- 配置Shiro核心Filter -->
<bean id="shiroFilter"
class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 安全管理器 -->
<property name="securityManager" ref="securityManager" />
<!-- 未认证,跳转到哪个页面 -->
<property name="loginUrl" value="/login.html" />
<!-- 认证后,没有权限跳转页面 -->
<property name="unauthorizedUrl" value="/unauthor.html" />
<!-- shiro URL控制过滤器规则
规律: value中配置的信息是有顺序的: 从上到下。
anon ----- 配置未认证时,可以访问资源
authc ---- 必须认证成功后,才可访问的资源
roles ----- 访问的资源 需要具备什么角色
perms ----- 访问的资源 需要具备什么权限
-->
<property name="filterChainDefinitions">
<value>
/login.html* = anon
/css/** = anon
/js/** = anon
/upload/** = anon
/images/** = anon
/user_login.action* = anon
/test_Author.action* = perms[user:author]
/** = authc
</value>
</property>
</bean>
b. 配置 安全管理器
<!-- 安全管理器 -->
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- bosRealm 就是我们自定义的realm的对象 -->
<property name="realm" ref="bosRealm" />
</bean>
<!-- Shiro生命周期处理器 -->
<bean id="lifecycleBeanPostProcessor"
class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
c. 自定义一个BosRealm对象
@Service("bosRealm")
public class BosRealm extends AuthorizingRealm {
@Override
// 认证...
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("shiro 认证管理... ");
return null;
}
@Override
// 授权...
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
System.out.println("shiro 授权管理...");
return null;
}
四、测试
1)配置好 applicationContext-shiro.xml的 shiroFilter的访问权限2)直接在浏览器中,访问任意项目的资源界面,如果能跳转到 未登录时配置的 界面, 同时 后台能打印一句"shiro 认证管理... "
则说明 权限shiro框架整合成功
五、在项目中的使用
应用程序 ------- > Subject ------> subject.login(token) --------> SecurityManager安全管理器 ------> 调用 自带的Realm对象-------> 重写安全管理器的 Realm对象 ------->在自定义的Realm对象中,实现 认证 和 授权的方法
初次发博,请多指教!!!