参考文章:http://www.cnblogs.com/lixj/p/3403584.html
http://www.tuicool.com/articles/AFFBre
一、导入shiro相关jar (1.2.3.jar)
shiro-core
shiro-web
shiro-spring
shiro-ehcache
二、在web.xml配置shiroFilter
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<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>
注意:如果使用struts过滤器一定要把shiroFilter放在strutsFilter前面
三、在spring中配置shiro
<!--自定义Realm 继承自AuthorizingRealm -->
<bean id="myRealm" class="com.jmt.webapp.realm.myRealm" />
<!-- 添加securityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--设置自定义realm -->
<property name="realm" ref="myRealm" />
</bean>
<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" >
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager" />
<!-- 要求登录时的链接,非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
<property name="loginUrl" value="/login.jsp" />
<!-- 用户访问未对其授权的资源时,所显示的连接 -->
<property name="unauthorizedUrl" value="/error/noperms.jsp" />
<property name="filterChainDefinitions">
<value>
<!--
Anon:不指定过滤器
Authc:验证,这些页面必须验证后才能访问,也就是我们说的登录后才能访问。
-->
/login.jsp* = anon
/login.do* = anon
/index.jsp*= anon
/error/noperms.jsp*= anon
/*.jsp* = authc
/*.action* = authc
</value>
</property>
</bean>
<bean id = "cacheManager" class = "org.apache.shiro.cache.ehcache.EhCacheManager" />
四、编写自己Realm
public class myRealm extends AuthorizingRealm{
//依赖注入
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}<pre name="code" class="java"> //权限认证<pre name="code" class="java"> protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
<span> </span>}
<pre name="code" class="java"> //登录验证
<pre name="code" class="java"> protected AuthenticationInfo doGetAuthenticationInfo(
<span> </span>AuthenticationToken authcToken) throws AuthenticationException {
}
五、登录校验
Subject currentUser = SecurityUtils.getSubject();
System.out.println(user.getUserLoginName()+user.getUserPassword()+"4354545");
UsernamePasswordToken token = new UsernamePasswordToken(user.getUserLoginName(),user.getUserPassword());
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException ex) {
System.out.println("用户名没有找到");
} catch (IncorrectCredentialsException ex) {//用户名密码不匹配。
System.out.println("用户名密码不匹配");
}catch (AuthenticationException e) {//其他的登录错误
System.out.println("其他的登录错误");
}
六、权限校验
Subject currentUser = SecurityUtils.getSubject();
if(currentUser.isPermitted("URL")){
System.out.println("验证成功");
}