從頭開始——SSM+Shiro實現登陸的安全認證
Shiro功能概述:
Shiro是一個功能強大且靈活的開源安全框架,可以清晰地處理身份驗證,授權,企業會話管理和加密。
-
身份驗證:有時也稱為“登入”,這是證明使用者是他們所說的人的行為。
-
授權:訪問控制的過程,即確定“誰”可以訪問“什麼”。
-
會話管理:即使在非Web或EJB應用程式中,也可以管理特定於使用者的會話。
-
加密:使用加密演算法保持資料安全,同時仍然易於使用。
Shiro的簡要概述:
我們傳統的登入認證方式是,從前端頁面獲取到使用者輸入的賬號和密碼之後,傳到後臺直接去資料庫查詢賬號和密碼是否匹配和存在,如果匹配和存在就登入成功,沒有就提示登陸失敗
而shiro的認證方式則是,從前端頁面獲取到使用者輸入的賬號和密碼之後,傳入給一個UsernamePasswordToken物件也就是令牌,
然後再把令牌傳給subject,subject會呼叫自定義的 realm,
realm做的事情就是用前端使用者輸入的使用者名稱,去資料庫查詢出一條記錄(只用使用者名稱去查,查詢拿到返回使用者名稱和密碼),然後再把兩個密碼進行對比,不一致就跑出異常
也就是說如果subject.login(token);沒有丟擲異常,就表示使用者名稱和密碼是匹配的,那麼就表示登入成功!
今天要做的就是在SSM專案中整合Shiro安全框架實現簡單的登陸認證!
廢話不多說,開幹!
第一步,先看看基本的專案結構(前臺頁面和靜態資源我已經匯入了,原始碼會放在最後)
然後新增maven依賴
<!--宣告版本--> <properties> <servlet.version>3.1.0</servlet.version> <jsp.version>2.3.1</jsp.version> <jstl.version>1.2</jstl.version> <mybatis.version>3.4.6</mybatis.version> <mybatis-spring.version>1.3.2</mybatis-spring.version> <spring.version>4.3.13.RELEASE</spring.version> <mysql.version>5.1.40</mysql.version> <log4j.version>1.2.17</log4j.version> <shiro.version>1.3.2</shiro.version> </properties> <dependencies> <!--新增shiro依賴--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>${shiro.version}</version> </dependency> <!-- 加入servlet的依賴 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <!-- 加入jsp的依賴 --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> <!-- 加入jstl的依賴 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- 加入mybtais的依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- 加入mybtais-spring的依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- 加入spring的依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</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-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</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-tx</artifactId> <version>${spring.version}</version> </dependency> <!-- 加入springmvc的依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- 加入mysql的依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 加入log4j的依賴 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> </dependencies>
然後開始建立對應的介面和類
(關於專案中的實體類和mapper檔案還有mapping檔案的自動生成方法參見這裡)
首先在realm中建立一個UserRealm繼承AuthorizingRealm並重新它的兩個方法
package com.sixmac.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm {
/**
* 認證的時候回撥
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
/**
* 授權的時候回撥
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
然後是shiro的配置檔案application-shiro.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 掃描realm -->
<context:component-scan
base-package="com.sixmac.realm"></context:component-scan>
<!-- 建立憑證管理器 -->
<!--MD5加密-->
<!--<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!–<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="2"></property>–>
</bean>-->
<!-- 建立 userRealm -->
<bean id="userRealm" class="com.sixmac.realm.UserRealm">
<!--<property name="credentialsMatcher" ref="credentialsMatcher"></property>-->
</bean>
<!-- securityManager安全管理器 -->
<bean id="securityManager"
class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"></property>
</bean>
<!-- Shiro 的Web過濾器 id必須和web.xml裡面的shiroFilter的 targetBeanName的值一樣 -->
<bean id="shiroFilter"
class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全介面,這個屬性是必須的 -->
<property name="securityManager" ref="securityManager" />
<!-- 要求登入時的連結(登入頁面地址),非必須的屬性,預設會自動尋找Web工程根目錄下的"/login.jsp"頁面 -->
<property name="loginUrl" value="/login/toLogin" />
<!-- 登入成功後要跳轉的連線(本例中此屬性用不到,因為登入成功後的處理邏輯在UserController裡硬編碼) -->
<!-- <property name="successUrl" value="/success.action"/> -->
<!-- 使用者訪問未對其授權的資源時,所顯示的連線 -->
<property name="unauthorizedUrl" value="/refuse.jsp" />
<!-- 過慮器鏈定義,從上向下順序執行,一般將/**放在最下邊 -->
<property name="filterChainDefinitions">
<value>
<!-- /** = authc 所有url都必須認證通過才可以訪問 -->
/index.jsp*=anon
/login/toLogin*=anon
/login/login*=anon
<!-- 如果使用者訪問user/logout就使用Shiro登出session -->
/login/logout = logout
<!-- /** = anon所有url都不可以匿名訪問 -->
<!-- /** = authc -->
<!-- /*/* = authc -->
<!-- /** = authc所有url都不可以匿名訪問 必須放到最後面 -->
/** = authc
</value>
</property>
</bean>
</beans>
然後是配置檔案:application-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 解析db.properties 因為 db.properties裡面有username=root 如果在下面的資料來源中使用${username}它取到的是當前系統的登陸名
如果要使用db.properties裡面的username必須加system-properties-mode="FALLBACK"這個屬性 -->
<context:property-placeholder location="classpath:db.properties"
system-properties-mode="FALLBACK" />
<!-- 配置資料來源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</bean>
<!-- 配置sqlSessinoFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--mybatis的配置檔案 -->
<property name="configLocation" value="classpath:mybatis.cfg.xml" />
<!--掃描 XXXmapper.xml對映檔案,配置掃描的路徑 這個不配置也可以,但是不配置的話,下面dao和xxxMapper.xml必須放在同一個包下面 -->
<property name="mapperLocations">
<array>
<value>classpath:com/sixmac/mapping/*.xml</value>
</array>
</property>
</bean>
<!-- Mapper介面所在包名,Spring會自動查詢之中的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 以下的配置只能指向一個包 如果配置多個呢 就在包的中間加, -->
<property name="basePackage" value="com.sixmac.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
然後是application-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" 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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 掃描service -->
<context:component-scan base-package="com.sixmac.service.impl"></context:component-scan>
<!-- 1,配置事務 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 2 宣告事務切面 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="start*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 進行aop的配置 -->
<aop:config>
<!-- 宣告切入點 -->
<aop:pointcut expression="execution(* com.sixmac.service.impl.*.*(..))" id="pc1" />
<!--<aop:pointcut expression="execution(* com.sixmac.service.impl.*.*(..))" id="pc2" />-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pc1" />
<!--<aop:advisor advice-ref="txAdvice" pointcut-ref="pc2" />-->
</aop:config>
</beans>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 引入application-dao.xml application-service.xml -->
<import resource="classpath:application-dao.xml" />
<import resource="classpath:application-service.xml" />
<import resource="classpath:application-shiro.xml"/>
</beans>
springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 掃描controller -->
<context:component-scan base-package="com.sixmac.controller"></context:component-scan>
<!-- 配置對映器和介面卡 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置檢視解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 攔截器 -->
<!-- <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/user/toLogin*" />
<mvc:exclude-mapping path="/user/login*" />
<bean class="com.sixmac.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors> -->
<!-- 過濾靜態資源 -->
<mvc:default-servlet-handler />
</beans>
mybatis.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- 導標頭檔案 -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的核心配置檔案 -->
<configuration>
<!-- 配置日誌的輸出方式 -->
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<!-- 別外優化 -->
<typeAliases>
<package name="com.sixmac.domain"/>
</typeAliases>
<!--<!– 分頁外掛 –>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>-->
</configuration>
dp.properties:
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/manager
username=root
password=root
web.xml:
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>erp1</display-name>
<!-- 編碼過濾器開始 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 編碼過濾器結束 -->
<!--過濾靜態資源,一定要放在Spring的Dispatcher的前面-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
<!-- shiro整合開始 -->
<!-- shiro過慮器,DelegatingFilterProxy通過代理模式將spring容器中的bean和filter關聯起來 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!-- 設定true由servlet容器控制filter的生命週期 -->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<!-- 設定spring容器filter的bean id,如果不設定則找與filter-name一致的bean -->
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<!-- 代表訪問springmvc【是springmvc的前端控制器的servlet的名字】這個Servlet時就啟用shiro的認證和授權 -->
<servlet-name>springmvc</servlet-name>
<!-- 攔截所有的url 包括 css js image 等等 -->
<!-- <url-pattern>/*</url-pattern> -->
</filter-mapping>
<!-- shiro整合結束 -->
<!-- 配置spring的監聽器開始 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置spring的監聽器結束 -->
<!-- 配置前端控制器開始 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--用來標記是否在專案啟動時就加在此Servlet,0或正數表示容器在應用啟動時就載入這個Servlet, 當是一個負數時或者沒有指定時,則指示容器在該servlet被選擇時才載入.正數值越小啟動優先值越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--為DispatcherServlet建立對映 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 攔截所有請求,千萬注意是(/)而不是(/*) -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置前端控制器結束 -->
</web-app>
配置檔案沒問題的話就建立controller,設定頁面跳轉路徑與登陸請求路徑
package com.sixmac.controller;
import com.sixmac.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("login")
public class LoginController {
@RequestMapping("toLogin")
public String toLogin(){
return "login.jsp";
}
@RequestMapping("login")
public String login(String loginname, String password, Model model, HttpSession session){
UsernamePasswordToken token = new UsernamePasswordToken(loginname, password);
// 得到認證主體
Subject subject = SecurityUtils.getSubject();
try {
//這裡會載入自定義的realm
subject.login(token); //把令牌放到login裡面進行查詢,如果查詢賬號和密碼時候匹配,如果匹配就把user物件獲取出來,失敗就拋異常
System.out.println("認證成功!");
User user = (User) subject.getPrincipal();//獲取登入成功的使用者物件(以前是直接去service裡呼叫方法面查)
session.setAttribute("user",user);//放入session
return "/system/index.jsp";
}catch (Exception e){
model.addAttribute("error","使用者名稱密碼不匹配!");
return "login.jsp";
}
}
}
然後在自定義的realm裡寫shiro登陸認證的方法
package com.sixmac.realm;
import com.sixmac.domain.User;
import com.sixmac.service.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserRealm extends AuthorizingRealm {
@Autowired
private LoginService loginService;
/**
* 認證的時候回撥
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken userToken = (UsernamePasswordToken) token;//獲取令牌(裡面存放new UsernamePasswordToken的時候放入的賬號和密碼)
String loginname = userToken.getUsername();
User user = loginService.login(loginname);//去資料庫查詢使用者名稱是否存在,如果存在返回物件(賬號和密碼都有的物件)
if (user!=null){
//引數1.使用者認證的物件(Controller中subject.getPrincipal()方法返回的物件),
//引數2.從資料庫根據使用者名稱查詢到的使用者密碼
//引數3.把當前自定義的realm物件傳給SimpleAuthenticationInfo,在配置檔案需要注入
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
return info;
}else {
return null;
}
}
/**
* 授權的時候回撥
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
到這裡基本上就完成了shiro的登陸認證,核心程式碼其實就只有這麼多,當然這只是最簡單的一部分,shiro還有很多其他強大的功能,這裡就不細說了