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還有很多其他強大的功能,這裏就不細說了
源碼在此:點擊下載源碼!
The end!!!