Shrio登陸驗證實例詳細解讀
摘要:本文采用了Spring+SpringMVC+Mybatis+Shiro+Msql來寫了一個登陸驗證的實例,下面來看看過程吧!整個工程基于Mavevn來創建,運行環境為JDK1.6+WIN7+tomcat7.
這里主要說了Shiro的搭建過程,Spring+SpringMVC+Mybatis的搭建過可以看這里Spring+Mybatis+SpringMVC+Maven+MySql搭建實例
整體工程免費下載:http://download.csdn.net/detail/evankaka/9331135
最終效果如下:
工程整體的目錄如下:
java代碼如下:
配置文件如下:
頁面資源如下:
好了,下面來簡單說下過程吧!
準備工作:
先建表:
drop table if exists user; CREATE TABLE `user` ( `id` int(11) primary key auto_increment, `name` varchar(20) NOT NULL, `age` int(11) DEFAULT NULL, `birthday` date DEFAULT NULL, `password` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into user values(1,'lin',12,'2013-12-01','123456'); insert into user values(2,'apple',34,'1999-12-01','123456'); insert into user values(3,'evankaka',23,'2017-12-01','123456');
建好后,新建一個Maven的webApp的工程,記得把結構設置成上面的那樣!
下面來看看一些代碼和配置
1、POM文件
注意不要少導包了,如果項目出現紅叉,一般都是JDK版本的設置問題,自己百度一下就可以解決
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lin</groupId> <artifactId>ShiroLearn1</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ShiroLearn1 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本號 --> <spring.version>3.2.8.RELEASE</spring.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <!-- junit版本號 --> <junit.version>4.10</junit.version> <!-- mybatis版本號 --> <mybatis.version>3.2.1</mybatis.version> </properties> <dependencies> <!-- 添加Spring依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!--單元測試依賴 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!--spring單元測試依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!--mybatis依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.0</version> </dependency> <!-- mysql驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <!-- servlet驅動包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <!-- Spring 整合Shiro需要的依賴 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.1</version> </dependency> <!-- Spring 整合Shiro需要的依賴 --> </dependencies> <build> <finalName>ShiroLearn1</finalName> <plugins> <!-- 指定web項目 版本 --> <plugin> <artifactId>maven-war-plugin</artifactId> <configuration> <version>2.4</version> </configuration> </plugin> <!-- 指定編譯使用 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
2、自定義Shiro攔截器
這里這個攔截器完成了用戶名和密碼的驗證,驗證成功后又給用賦角色和權限(注意,這里賦角色和權限我直接寫進去了,沒有使用數據庫,一般都是要通過service層找到用戶名后,再去數據庫查該用戶對應的角色以及權限,然后再加入到shiro中去)
代碼如下:
package com.lin.realm; import java.util.HashSet; import java.util.Set; 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.cache.Cache; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.SimplePrincipalCollection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.lin.domain.User; import com.lin.service.UserService; import com.lin.utils.CipherUtil; public class ShiroDbRealm extends AuthorizingRealm { private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class); private static final String ALGORITHM = "MD5"; @Autowired private UserService userService; public ShiroDbRealm() { super(); } /** * 驗證登陸 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; System.out.println(token.getUsername()); User user = userService.findUserByLoginName(token.getUsername()); System.out.println(user); CipherUtil cipher = new CipherUtil();//MD5加密 if (user != null) { return new SimpleAuthenticationInfo(user.getName(), cipher.generatePassword(user.getPassword()), getName()); }else{ throw new AuthenticationException(); } } /** * 登陸成功之后,進行角色和權限驗證 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { /*這里應該根據userName使用role和permission 的serive層來做判斷,并將對應 的權限加進來,下面簡化了這一步*/ Set<String> roleNames = new HashSet<String>(); Set<String> permissions = new HashSet<String>(); roleNames.add("admin");//添加角色。對應到index.jsp roleNames.add("administrator"); permissions.add("create");//添加權限,對應到index.jsp permissions.add("login.do?main"); permissions.add("login.do?logout"); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames); info.setStringPermissions(permissions); return info; } /** * 清除所有用戶授權信息緩存. */ public void clearCachedAuthorizationInfo(String principal) { SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName()); clearCachedAuthorizationInfo(principals); } /** * 清除所有用戶授權信息緩存. */ public void clearAllCachedAuthorizationInfo() { Cache<Object, AuthorizationInfo> cache = getAuthorizationCache(); if (cache != null) { for (Object key : cache.keys()) { cache.remove(key); } } } // @PostConstruct // public void initCredentialsMatcher() {//MD5鍔犲瘑 // HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ALGORITHM); // setCredentialsMatcher(matcher); // } }
3、shiro的配置文件 :spring-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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-lazy-init="true"> <description>Shiro Configuration</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="cacheManager" /> </bean> <!-- 項目自定義的Realm --> <bean id="shiroDbRealm" class="com.lin.realm.ShiroDbRealm"> <property name="cacheManager" ref="cacheManager" /> </bean> <!-- Shiro Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.do" /> <property name="successUrl" value="/view/index.html" /> <property name="unauthorizedUrl" value="/error/noperms.jsp" /> <property name="filterChainDefinitions"> <value> /index.html = authc /checkLogin.do = anon /login.do = anon /logout.html = anon /** = authc </value> </property> </bean> <!-- 用戶授權信息Cache --> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> <!-- 保證實現了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>
這里簡要說明下:
(1)
securityManager:這個屬性是必須的。
loginUrl:沒有登錄的用戶請求需要登錄的頁面時自動跳轉到登錄頁面,不是必須的屬性,不輸入地址的話會自動尋找項目web項目的根目錄下的”/login.jsp”頁面。
successUrl:登錄成功默認跳轉頁面,不配置則跳轉至”/”。如果登陸前點擊的一個需要登錄的頁面,則在登錄自動跳轉到那個需要登錄的頁面。不跳轉到此。
unauthorizedUrl:沒有權限默認跳轉的頁面。
(2)
anon:例子/admins/**=anon 沒有參數,表示可以匿名使用。
authc:例如/admins/user/**=authc表示需要認證(登錄)才能使用,沒有參數
roles:例子/admins/user/**=roles[admin],參數可以寫多個,多個時必須加上引號,并且參數之間用逗號分割,當有多個參數時,例如admins/user/**=roles["admin,guest"],每個參數通過才算通過,相當于hasAllRoles()方法。
perms:例子/admins/user/**=perms[user:add:*],參數可以寫多個,多個時必須加上引號,并且參數之間用逗號分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],當有多個參數時必須每個參數都通過才通過,想當于isPermitedAll()方法。
rest:例子/admins/user/**=rest[user],根據請求的方法,相當于/admins/user/**=perms[user:method] ,其中method為post,get,delete等。
port:例子/admins/user/**=port[8081],當請求的url的端口不是8081是跳轉到schemal://serverName:8081?queryString,其中schmal是協議http或https等,serverName是你訪問的host,8081是url配置里port的端口,queryString
是你訪問的url里的?后面的參數。
authcBasic:例如/admins/user/**=authcBasic沒有參數表示httpBasic認證
ssl:例子/admins/user/**=ssl沒有參數,表示安全的url請求,協議為https
user:例如/admins/user/**=user沒有參數表示必須存在用戶,當登入操作時不做檢查
注:anon,authcBasic,auchc,user是認證過濾器,
perms,roles,ssl,rest,port是授權過濾器
4、web.xml配置解讀shiro的配置文件(上面的)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Archetype Created Web Application</display-name> <!-- 起始歡迎界面 --> <welcome-file-list> <welcome-file>/login.do</welcome-file> </welcome-file-list> <!-- 讀取spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value> </context-param> <!-- 設計路徑變量值 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>springmvc.root</param-value> </context-param> <!-- Spring字符集過濾器 --> <filter> <filter-name>SpringEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>SpringEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <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> </filter-mapping> <!-- 日志記錄 --> <context-param> <!-- 日志配置文件路徑 --> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <!-- 日志頁面的刷新間隔 --> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止spring內存溢出監聽器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- springMVC核心配置 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!--spingMVC的配置路徑 --> <param-value>classpath:springmvc/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 攔截設置 --> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置session超時時間,單位分鐘 --> <session-config> <session-timeout>15</session-timeout> </session-config> <error-page> <error-code>404</error-code> <location>/WEB-INF/views/error/404.jsp</location> </error-page> <error-page> <error-code>401</error-code> <location>/WEB-INF/views/error/401.jsp</location> </error-page> </web-app>
這里不僅配置了SpringMVC還要配置Shiro!
5、登陸頁面login.jsp
以下是默認登陸的界面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String url = request.getRequestURL().toString(); url = url.substring(0, url.indexOf('/', url.indexOf("http://") + 2)); String context = request.getContextPath(); url += context; application.setAttribute("ctx", url); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${ctx}/checkLogin.do" method="post"> username: <input type="text" name="username"><br> password: <input type="password" name="password"><br> <input type="submit" value="登錄"> </form> </body> </html>
6、驗證成功頁面index.jsp
如果用戶名和密碼正確后,跳轉到的頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%> <% String url = request.getRequestURL().toString(); url = url.substring(0, url.indexOf('/', url.indexOf("http://") + 2)); String context = request.getContextPath(); url += context; application.setAttribute("ctx", url); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Shiro登陸實例</title> </head> <body> <h1>Shiro登陸實例</h1><a href="${ctx}/logout.html">退出</a> <p>一、驗證當前用戶是否為"訪客",即未認證(包含未記住)的用戶</p> <shiro:guest> Hi there! Please <a href="login.jsp">Login</a> or <a href="signup.jsp">Signup</a> today! </shiro:guest> <p>二、認證通過或已記住的用戶</p> <shiro:user> Welcome back John! Not John? Click <a href="login.jsp">here<a> to login. </shiro:user> <p>三、已認證通過的用戶。不包含已記住的用戶,這是與user標簽的區別所在。</p> <shiro:authenticated> <a href="updateAccount.jsp">Update your contact information</a>. </shiro:authenticated> <p>四、未認證通過用戶,與authenticated標簽相對應。與guest標簽的區別是,該標簽包含已記住用戶。</p> <shiro:notAuthenticated> Please <a href="login.jsp">login</a> in order to update your credit card information. </shiro:notAuthenticated> <p>五、輸出當前用戶信息,通常為登錄帳號信息</p> Hello, <shiro:principal/>, how are you today? <p>六、驗證當前用戶是否屬于該角色</p> <shiro:hasRole name="administrator"> <a href="admin.jsp">Administer the system</a> </shiro:hasRole> <p>七、與hasRole標簽邏輯相反,當用戶不屬于該角色時驗證通過</p> <shiro:lacksRole name="administrator"> Sorry, you are not allowed to administer the system. </shiro:lacksRole> <p>八、驗證當前用戶是否屬于以下任意一個角色。</p> <shiro:hasAnyRoles name="developer,manager,administrator"> You are either a developer,manager, or administrator. </shiro:hasAnyRoles> <p>九、驗證當前用戶權限。</p> <shiro:hasPermission name="create"> <p>當前用戶擁有增加的權限!!!!!!!!!!!!!</p> </shiro:hasPermission> <shiro:hasPermission name="delete"> <p>當前用戶擁有刪除的權限!!!!!!!!!!!!!</p> </shiro:hasPermission> </body> </html>
其它頁面就不說了,具體看工程吧!
7、controller層來看看
這里/{id}/showUser主要是來驗證是否連接成功(現在無法測試了),當然在工程里你也可以到src/test/java里的包com.lin.service下的UserServiceTest.java,那里我也寫了一個單元測試的類。
package com.lin.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.lin.domain.User; import com.lin.realm.ShiroDbRealm; import com.lin.service.UserService; import com.lin.utils.CipherUtil; @Controller public class UserControler { private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class); @Autowired private UserService userService; /** * 驗證springmvc與batis連接成功 * @param id * @param request * @return */ @RequestMapping("/{id}/showUser") public String showUser(@PathVariable int id, HttpServletRequest request) { User user = userService.getUserById(id); System.out.println(user.getName()); request.setAttribute("user", user); return "showUser"; } /** * 初始登陸界面 * @param request * @return */ @RequestMapping("/login.do") public String tologin(HttpServletRequest request, HttpServletResponse response, Model model){ logger.debug("來自IP[" + request.getRemoteHost() + "]的訪問"); return "login"; } /** * 驗證用戶名和密碼 * @param request * @return */ @RequestMapping("/checkLogin.do") public String login(HttpServletRequest request) { String result = "login.do"; // 取得用戶名 String username = request.getParameter("username"); //取得 密碼,并用MD5加密 String password = CipherUtil.generatePassword(request.getParameter("password")); //String password = request.getParameter("password"); UsernamePasswordToken token = new UsernamePasswordToken(username, password); Subject currentUser = SecurityUtils.getSubject(); try { System.out.println("----------------------------"); if (!currentUser.isAuthenticated()){//使用shiro來驗證 token.setRememberMe(true); currentUser.login(token);//驗證角色和權限 } System.out.println("result: " + result); result = "index";//驗證成功 } catch (Exception e) { logger.error(e.getMessage()); result = "login。do";//驗證失敗 } return result; } /** * 退出 * @return */ @RequestMapping(value = "/logout") @ResponseBody public String logout() { Subject currentUser = SecurityUtils.getSubject(); String result = "logout"; currentUser.logout(); return result; } }再來看看效果吧!
