本文基于你已经能搭建springmvc+mybatis+maven项目,在此基础上,加入shiro框架。文末会提供一个demo。
原理:
大多数框架都符合这样的逻辑:有一个核心控制器,用户调用核心控制器,然后核心控制器找到对应的响应事件进行处理,然后反馈结果给用户。而这个核心控制器,是我们不必深入了解的,只要正确配置即可。
对shiro来说,他是处理用户的权限和认证的,所以我们稍微变通下:用户(Subject)调用shiro的核心控制器(Shiro SecurityManage),然后核心控制器进行相应的处理(获取用户的认证结果或者权限),然后反馈给用户。如下图所示:
对开发人员来说,只需:
1)配置Shiro SecurityManager
2)定义自己的Realm。因为用户/权限因项目不同而不同,所以shiro框架需要用户自定义用户/权限,然后通过Realm注入即可。
3)通过Subject访问Shiro SecurityManager
代码实现:
第一步:pom.xml文件中引入需要的jar
<span style="white-space:pre"> </span><dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.4</version>
</dependency>
<span style="white-space:pre"> </span><dependency>
<span style="white-space:pre"> </span><groupId>com.alibaba</groupId>
<span style="white-space:pre"> </span><artifactId>druid</artifactId>
<span style="white-space:pre"> </span><version>1.0.11</version>
<span style="white-space:pre"> </span></dependency>
第二步:定义shiro配置文件applicationContext-shiro.xml;我们只做三件事,配置securityManager,然后注入自定义的Realm,最后对指定的URL进行过滤(红色标注是需要自己修改的)。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
">
<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->
<bean id="myRealm" <span style="color:#3333ff;">class="<span style="color:#ff0000;">com.realm.MyRealm"</span>/>
<!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm" />
</bean>
<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
<!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager" />
<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
<property name="loginUrl" value="<span style="color:#cc0000;">/items/login</span>"
<!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码为main.jsp了) -->
<!-- <property name="successUrl" value="/"/> -->
<!-- 用户访问未对其授权的资源时,所显示的连接 -->
<!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->
<property name="unauthorizedUrl" value="/" />
<!-- Shiro连接约束配置,即过滤链的定义 -->
<!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 -->
<!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
<!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->
<!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
<property name="filterChainDefinitions">
<value>
<span style="color:#ff0000;">/items/queryItems=authc</span>
</value>
</property>
</bean>
</beans>
第三步:自定义Realm
package com.realm;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
public class MyRealm extends AuthorizingRealm {
/**
* 为当前登录的Subject授予角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
//此处应该去数据库查询用户权限信息,然后将权限信息返回
return null;
}
/**
* 验证当前登录的Subject
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
//获取基于用户名和密码的令牌
UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
System.out.println("验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
//此处应该去数据库查询用户信息,然后跟页面传来的数据进行对比。此处我们直接返回,不做任何处理。
System.out.println(token.getUsername()+token.getPassword());
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), this.getName());
this.setSession("currentUser", token.getUsername());
return authcInfo;
}
/**
* 将一些数据放到ShiroSession中,以便于其它地方使用
*/
private void setSession(Object key, Object value){
Subject currentUser = SecurityUtils.getSubject();
if(null != currentUser){
Session session = currentUser.getSession();
session.setTimeout(10000);
System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
if(null != session){
session.setAttribute(key, value);
}
}
}
}
第四步:通过Subject访问Shiro SecurityManager,我们只需在接口中加入:
Subject sub = SecurityUtils.getSubject();
try {
UsernamePasswordToken token = new UsernamePasswordToken(item.getId(), item.getName());
token.setRememberMe(true);
<span style="white-space:pre"> </span>sub.login(token);
} catch (IncorrectCredentialsException e) {
return null;
}
if(sub.isAuthenticated()){
System.out.println("通过验证");
}
当然了要记得,在web.xml中引用applicationContext-shiro.xml,并配置使用此过滤器
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:config/spring/applicationContext-*.xml
<span style="white-space:pre"> </span></param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->
<!-- 这里filter-name必须对应applicationContext.xml中定义的<bean id="shiroFilter"/> -->
<!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 -->
<!-- 通常会将此filter-mapping放置到最前面(即其他filter-mapping前面),以保证它是过滤器链中第一个起作用的 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->
<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>
demo
demo使用的数据库是oracle,只需要一个表MY_ITEM,包含三个字段:id、name、price。
如何测试:
接口1:http://localhost:8080/study/items/queryItems
接口2:http://localhost:8080/study/items/login
访问接口1会自动跳转到接口2,然后再在浏览器中输入接口1,则会显示出接口1的查询结果。为了测试,我设置的session过期时间是10s,手速不要太慢,10s之后再访问接口1还是会自动跳转到接口2。
特别感谢张开涛老师的shiro教程,当然还有敬佩的孔老师。