自己的项目中很多都用到了Shiro的配置来管理验证登录和权限认证,所以自己简单的小结一下,这里暂时只解释登录验证这一块。
(1)首先在项目的WEB-INF目录下的web.xml配置中:
加上
<!-- Shiro Security filter --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>*.htm</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>*.json</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>*.jsp</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> <!-- Shiro Security filter -->
上面的配置是对请求地址后缀的过滤和转发
这里我的欢迎页的配置直接配置login.jsp了。还是在web.xml中最后加上 <welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
(2)在项目的上下文配置applicationContext.xml中加上:
<import resource="security/applicationContext-shiro.xml" />
这样的话,就能引入applicationContext-shiro.xml的配置,在这个配置中
全文配置如下:
<?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd" default-lazy-init="true"> <description>Shiro安全配置</description> <!-- Shiro's main business-tier object for web-enabled applications --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="shiroDbRealm" /> <property name="cacheManager" ref="shiroEhcacheManager" /> </bean> <!-- 項目自定义的Realm --> <bean id="shiroDbRealm" class="com.baishi.website.User.MyDbRealm"> <property name="userService" ref="userService"/> <!-- 可配置cache token<->认证信息的cache,用于REST等需要频繁认证的场景 --> <!--<property name="authorizationCachingEnabled" value="true"/>--> </bean> <bean id="myAuthc" class="com.baishi.website.base.filter.MyFormAuthenticationFilter"/> <!-- Shiro Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.htm" /> <property name="successUrl" value="/admin.htm" /> <property name="unauthorizedUrl" value="/unauthorized.htm"/> <property name="filters"> <util:map> <entry key="myAuthc" value-ref="myAuthc"/> </util:map> </property> <property name="filterChainDefinitions"> <value> /logout.htm = logout /** = myAuthc </value> </property> </bean> <!-- 用户授权信息Cache, 采用EhCache --> <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:security/ehcache-shiro.xml"/> </bean> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- AOP式方法级权限检查 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" value="true" /> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> </beans>这里面我们关注的是:項目自定义的Realm,在我的目录下com.baishi.website.User.MyDbRealm找到 MyDbRealm这个类
MyDbRealm类的代码如下:
package com.baishi.website.User; import com.baishi.website.entity.Users; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; public class MyDbRealm extends AuthorizingRealm { private UserService userService; /** * 认证回调函数,登录时调用. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; Users user = userService.findUserByLoginName(upToken.getUsername()); if (user == null) { throw new UnknownAccountException("No account found for user [" + user.getUsername() + "]"); } return new SimpleAuthenticationInfo(user, user.getPassword(), getName()); } /** * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用. */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Users user = (Users) principals.fromRealm(getName()).iterator().next(); //user = userService.findAuthDetails(user); if (user != null) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); // for (Role role : user.getRoles()) { // //基于Role的权限信息 // info.addRole(role.getName()); // } // info.addStringPermissions(user.getPermissions()); return info; } else { return null; } } public void setUserService(UserService userService) { this.userService = userService; } }其中你只要关注:认证回调函数,登录时调用这个方法,到时候断点到这里看一下验证。
继续解释applicationContext-shiro.xml的配置:其中MyFormAuthenticationFilter这个类是超时的类配置:
代码如下:
package com.baishi.website.base.filter;
import org.apache.ibatis.logging.LogFactory;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
static {
LogFactory.useStdOutLogging();
}
@Override
protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
HttpServletRequest request1 = (HttpServletRequest) request;
HttpServletResponse response1 = (HttpServletResponse) response;
String uri = request1.getRequestURI();
if (uri.endsWith(".json")) {
response1.setHeader("sessionstatus", "timeout");
} else {
saveRequest(request);
redirectToLogin(request, response);
}
}
}
继续解释配置中<property name="loginUrl" value="/login.htm" />
<property name="successUrl" value="/admin.htm" />
两个属性对应的是登录和成功登录后的两个页面,这里我是在webapp根目录的两个页面:
其中login,jsp的页面代码:
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <html> <head> <base href="<%=basePath%>"> <title>博客后台登陆</title> <shiro:authenticated> <script type="text/javascript"> window.location.href = 'index.htm'; </script> </shiro:authenticated> </head> <body> <p>用户登录</p> <form id="form1" name="form1" method="post" action="login.htm"> <input type="hidden" name="method" value="login" /> <table width="335" height="84" border="0" cellpadding="1" cellspacing="1"> <tr> <td>用户名:</td> <td><label> <input type="text" name="username" id="username" /> </label></td> </tr> <tr> <td>密码:</td> <td><label> <input type="password" name="password" id="password" /> </label></td> </tr> <tr> <td><label> <input type="submit" name="button" id="button" value="登录" /> </label></td> <td><label></label></td> </tr> </table> </form> <p> </p> </body> </html>其中引入shiro的标签,并且
<shiro:authenticated> <script type="text/javascript"> window.location.href = 'index.htm'; </script> </shiro:authenticated>
重定向到index.htm这个页面。
另外在applicationContext-shiro.xml的配置中引入
<!-- 用户授权信息Cache, 采用EhCache -->
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:security/ehcache-shiro.xml"/>
</bean>
ehcache-shiro.xml的配置如下:
<ehcache updateCheck="false" name="shiroCache"> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache>到此 applicationContext-shiro.xml的配置就完成了。
现在实际操作的时候,在用户的Controller类中,我们写上简单代码:
package com.baishi.website.User; import com.alibaba.fastjson.JSON; import com.baishi.website.base.support.BaseControllerSupport; import com.baishi.website.entity.Users; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; @Controller @RequestMapping public class UserController extends BaseControllerSupport { /** * 用户登录后台 */ @RequestMapping(value = "/login", method = RequestMethod.POST) public String home(){ return "login"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "login"; } @RequestMapping(value = {"admin","index"}) public String admin() { return "admin"; }
}
最后还要说的是在MyDbRealm类中findUserByLoginName()这个方法,自己简单的在service层写一个根据用户名查询数据库的方法就行了,在xml 中的查询语句:
<select id="findByLoginName" parameterType="String" resultType="Users">
SELECT
*
FROM users
WHERE
username=#{username}
LIMIT 1
</select>
到此就简单的介绍了,用shiro验证登录的配置。解释一下整个过程的流程吧,启动tomcat,首先进入web.xml中过滤→到Controller类中转到视图页面login.jsp→进入了登录的页面,填入信息提交→到MyDbRealm类中验证回调的方法→验证成功后重定向到主页admin.htm